commit_id,project,commit_message,type,url,git_diff 8601529be8f92954b05f982a1d5f6b9e2025bace,elasticsearch,"Optimize multiple cluster state processing on- receiving nodes Nodes that receive the cluster state, and they have several- of those pending, can optimize and try and process potentially only one of- those. closes -5139--",p,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java b/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java index 5a237fd7e3cc7..a44914168e2ca 100644 --- a/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java +++ b/src/main/java/org/elasticsearch/cluster/service/InternalClusterService.java @@ -369,9 +369,9 @@ public void run() { newClusterState = builder.build(); logger.debug(""got first state from fresh master [{}]"", newClusterState.nodes().masterNodeId()); } else if (newClusterState.version() < previousClusterState.version()) { - // we got this cluster state from the master, filter out based on versions (don't call listeners) - logger.debug(""got old cluster state ["" + newClusterState.version() + ""<"" + previousClusterState.version() + ""] from source ["" + source + ""], ignoring""); - return; + // we got a cluster state with older version, when we are *not* the master, let it in since it might be valid + // we check on version where applicable, like at ZenDiscovery#handleNewClusterStateFromMaster + logger.debug(""got smaller cluster state when not master ["" + newClusterState.version() + ""<"" + previousClusterState.version() + ""] from source ["" + source + ""]""); } } diff --git a/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java b/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java index ec942f054fc0f..40db1a02dc3af 100644 --- a/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java +++ b/src/main/java/org/elasticsearch/discovery/local/LocalDiscovery.java @@ -19,6 +19,7 @@ package org.elasticsearch.discovery.local; +import com.google.common.base.Objects; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchIllegalStateException; import org.elasticsearch.Version; @@ -306,6 +307,10 @@ private void publish(LocalDiscovery[] members, ClusterState clusterState, final discovery.clusterService.submitStateUpdateTask(""local-disco-receive(from master)"", new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { + if (nodeSpecificClusterState.version() < currentState.version() && Objects.equal(nodeSpecificClusterState.nodes().masterNodeId(), currentState.nodes().masterNodeId())) { + return currentState; + } + ClusterState.Builder builder = ClusterState.builder(nodeSpecificClusterState); // if the routing table did not change, use the original one if (nodeSpecificClusterState.routingTable().version() == currentState.routingTable().version()) { diff --git a/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java b/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java index 92f59a44545f2..ca59bfad0bfdd 100644 --- a/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java +++ b/src/main/java/org/elasticsearch/discovery/zen/ZenDiscovery.java @@ -19,6 +19,7 @@ package org.elasticsearch.discovery.zen; +import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.elasticsearch.ElasticsearchException; @@ -43,6 +44,7 @@ import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.discovery.Discovery; import org.elasticsearch.discovery.DiscoveryService; import org.elasticsearch.discovery.DiscoverySettings; @@ -64,6 +66,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; @@ -527,8 +530,22 @@ public void clusterStateProcessed(String source, ClusterState oldState, ClusterS }); } - void handleNewClusterStateFromMaster(final ClusterState newState, final PublishClusterStateAction.NewClusterStateListener.NewStateProcessed newStateProcessed) { + static class ProcessClusterState { + final ClusterState clusterState; + final PublishClusterStateAction.NewClusterStateListener.NewStateProcessed newStateProcessed; + volatile boolean processed; + + ProcessClusterState(ClusterState clusterState, PublishClusterStateAction.NewClusterStateListener.NewStateProcessed newStateProcessed) { + this.clusterState = clusterState; + this.newStateProcessed = newStateProcessed; + } + } + + private final BlockingQueue processNewClusterStates = ConcurrentCollections.newBlockingQueue(); + + void handleNewClusterStateFromMaster(ClusterState newClusterState, final PublishClusterStateAction.NewClusterStateListener.NewStateProcessed newStateProcessed) { if (master) { + final ClusterState newState = newClusterState; clusterService.submitStateUpdateTask(""zen-disco-master_receive_cluster_state_from_another_master ["" + newState.nodes().masterNode() + ""]"", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { @@ -560,17 +577,63 @@ public void onFailure(String source, Throwable t) { }); } else { - if (newState.nodes().localNode() == null) { - logger.warn(""received a cluster state from [{}] and not part of the cluster, should not happen"", newState.nodes().masterNode()); + if (newClusterState.nodes().localNode() == null) { + logger.warn(""received a cluster state from [{}] and not part of the cluster, should not happen"", newClusterState.nodes().masterNode()); newStateProcessed.onNewClusterStateFailed(new ElasticsearchIllegalStateException(""received state from a node that is not part of the cluster"")); } else { if (currentJoinThread != null) { logger.debug(""got a new state from master node, though we are already trying to rejoin the cluster""); } - clusterService.submitStateUpdateTask(""zen-disco-receive(from master ["" + newState.nodes().masterNode() + ""])"", Priority.URGENT, new ProcessedClusterStateUpdateTask() { + final ProcessClusterState processClusterState = new ProcessClusterState(newClusterState, newStateProcessed); + processNewClusterStates.add(processClusterState); + + clusterService.submitStateUpdateTask(""zen-disco-receive(from master ["" + newClusterState.nodes().masterNode() + ""])"", Priority.URGENT, new ProcessedClusterStateUpdateTask() { @Override public ClusterState execute(ClusterState currentState) { + // we already processed it in a previous event + if (processClusterState.processed) { + return currentState; + } + + // TODO: once improvement that we can do is change the message structure to include version and masterNodeId + // at the start, this will allow us to keep the ""compressed bytes"" around, and only parse the first page + // to figure out if we need to use it or not, and only once we picked the latest one, parse the whole state + + + // try and get the state with the highest version out of all the ones with the same master node id + ProcessClusterState stateToProcess = processNewClusterStates.poll(); + if (stateToProcess == null) { + return currentState; + } + stateToProcess.processed = true; + while (true) { + ProcessClusterState potentialState = processNewClusterStates.peek(); + // nothing else in the queue, bail + if (potentialState == null) { + break; + } + // if its not from the same master, then bail + if (!Objects.equal(stateToProcess.clusterState.nodes().masterNodeId(), potentialState.clusterState.nodes().masterNodeId())) { + break; + } + + // we are going to use it for sure, poll (remove) it + potentialState = processNewClusterStates.poll(); + potentialState.processed = true; + + if (potentialState.clusterState.version() > stateToProcess.clusterState.version()) { + // we found a new one + stateToProcess = potentialState; + } + } + + ClusterState updatedState = stateToProcess.clusterState; + + // if the new state has a smaller version, and it has the same master node, then no need to process it + if (updatedState.version() < currentState.version() && Objects.equal(updatedState.nodes().masterNodeId(), currentState.nodes().masterNodeId())) { + return currentState; + } // we don't need to do this, since we ping the master, and get notified when it has moved from being a master // because it doesn't have enough master nodes... @@ -578,25 +641,25 @@ public ClusterState execute(ClusterState currentState) { // return disconnectFromCluster(newState, ""not enough master nodes on new cluster state received from ["" + newState.nodes().masterNode() + ""]""); //} - latestDiscoNodes = newState.nodes(); + latestDiscoNodes = updatedState.nodes(); // check to see that we monitor the correct master of the cluster if (masterFD.masterNode() == null || !masterFD.masterNode().equals(latestDiscoNodes.masterNode())) { masterFD.restart(latestDiscoNodes.masterNode(), ""new cluster state received and we are monitoring the wrong master ["" + masterFD.masterNode() + ""]""); } - ClusterState.Builder builder = ClusterState.builder(newState); + ClusterState.Builder builder = ClusterState.builder(updatedState); // if the routing table did not change, use the original one - if (newState.routingTable().version() == currentState.routingTable().version()) { + if (updatedState.routingTable().version() == currentState.routingTable().version()) { builder.routingTable(currentState.routingTable()); } // same for metadata - if (newState.metaData().version() == currentState.metaData().version()) { + if (updatedState.metaData().version() == currentState.metaData().version()) { builder.metaData(currentState.metaData()); } else { // if its not the same version, only copy over new indices or ones that changed the version - MetaData.Builder metaDataBuilder = MetaData.builder(newState.metaData()).removeAllIndices(); - for (IndexMetaData indexMetaData : newState.metaData()) { + MetaData.Builder metaDataBuilder = MetaData.builder(updatedState.metaData()).removeAllIndices(); + for (IndexMetaData indexMetaData : updatedState.metaData()) { IndexMetaData currentIndexMetaData = currentState.metaData().index(indexMetaData.index()); if (currentIndexMetaData == null || currentIndexMetaData.version() != indexMetaData.version()) { metaDataBuilder.put(indexMetaData, false);" 0135f0311318d8596fdeabca9f266cdac8f5589b,camel,CAMEL-6048: camel-xmljson fixed issue so- attrbiutes with name type can be serialized. Thanks to Arne M Stroksen for- the patch.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1443634 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-xmljson/src/main/java/org/apache/camel/dataformat/xmljson/XmlJsonDataFormat.java b/components/camel-xmljson/src/main/java/org/apache/camel/dataformat/xmljson/XmlJsonDataFormat.java index 103de3814dcfc..1120d73fc6cc3 100644 --- a/components/camel-xmljson/src/main/java/org/apache/camel/dataformat/xmljson/XmlJsonDataFormat.java +++ b/components/camel-xmljson/src/main/java/org/apache/camel/dataformat/xmljson/XmlJsonDataFormat.java @@ -120,6 +120,7 @@ protected void doStart() throws Exception { } } else { serializer.setTypeHintsEnabled(false); + serializer.setTypeHintsCompatibility(false); } } diff --git a/components/camel-xmljson/src/test/java/org/apache/camel/dataformat/xmljson/XmlJsonOptionsTest.java b/components/camel-xmljson/src/test/java/org/apache/camel/dataformat/xmljson/XmlJsonOptionsTest.java index 2d681593761cd..8c5b20abbabf2 100644 --- a/components/camel-xmljson/src/test/java/org/apache/camel/dataformat/xmljson/XmlJsonOptionsTest.java +++ b/components/camel-xmljson/src/test/java/org/apache/camel/dataformat/xmljson/XmlJsonOptionsTest.java @@ -53,6 +53,24 @@ public void testSomeOptionsToJSON() throws Exception { mockJSON.assertIsSatisfied(); } + @Test + public void testXmlWithTypeAttributesToJSON() throws Exception { + InputStream inStream = getClass().getClassLoader().getResourceAsStream(""org/apache/camel/dataformat/xmljson/testMessage4.xml""); + String in = context.getTypeConverter().convertTo(String.class, inStream); + + MockEndpoint mockJSON = getMockEndpoint(""mock:json""); + mockJSON.expectedMessageCount(1); + mockJSON.message(0).body().isInstanceOf(byte[].class); + + Object json = template.requestBody(""direct:marshal"", in); + String jsonString = context.getTypeConverter().convertTo(String.class, json); + JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString); + assertEquals(""JSON must contain 1 top-level element"", 1, obj.entrySet().size()); + assertTrue(""Top-level element must be named root"", obj.has(""root"")); + + mockJSON.assertIsSatisfied(); + } + @Test public void testSomeOptionsToXML() throws Exception { InputStream inStream = getClass().getClassLoader().getResourceAsStream(""org/apache/camel/dataformat/xmljson/testMessage1.json""); diff --git a/components/camel-xmljson/src/test/resources/org/apache/camel/dataformat/xmljson/testMessage4.xml b/components/camel-xmljson/src/test/resources/org/apache/camel/dataformat/xmljson/testMessage4.xml new file mode 100644 index 0000000000000..05e498379d32c --- /dev/null +++ b/components/camel-xmljson/src/test/resources/org/apache/camel/dataformat/xmljson/testMessage4.xml @@ -0,0 +1,16 @@ + + 1 + 2 + + c.a.1 + c.b.2 + + a + b + c + 1 + 2 + 3 + true + + \ No newline at end of file" e2c33ed6590eacc62ddf04c48a735146cd977362,elasticsearch,lucene 4: Fixed- BitsetExecutionChildQuerySearchTests class.--,c,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/index/search/child/ChildCollector.java b/src/main/java/org/elasticsearch/index/search/child/ChildCollector.java index 974cd1e273910..33e7366668e4d 100644 --- a/src/main/java/org/elasticsearch/index/search/child/ChildCollector.java +++ b/src/main/java/org/elasticsearch/index/search/child/ChildCollector.java @@ -80,13 +80,13 @@ public void collect(int doc) throws IOException { return; } for (Tuple tuple : readers) { - IndexReader indexReader = tuple.v1(); + AtomicReader indexReader = tuple.v1(); IdReaderTypeCache idReaderTypeCache = tuple.v2(); if (idReaderTypeCache == null) { // might be if we don't have that doc with that type in this reader continue; } int parentDocId = idReaderTypeCache.docById(parentId); - if (parentDocId != -1) { + if (parentDocId != -1 && (indexReader.getLiveDocs() == null || indexReader.getLiveDocs().get(parentDocId))) { FixedBitSet docIdSet = parentDocs().get(indexReader.getCoreCacheKey()); if (docIdSet == null) { docIdSet = new FixedBitSet(indexReader.maxDoc());" e4bbfd537a63a52a6094491504fc7b0bb54bcb0e,drools,fixing reflection constructor to use int instead of- long for ksessionId--,c,https://github.com/kiegroup/drools,"diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java index 02cd409adc2..3343babc7b3 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/KnowledgeStoreServiceImpl.java @@ -81,7 +81,7 @@ private CommandExecutor buildCommanService(long sessionId, try { Class< ? extends CommandExecutor> serviceClass = getCommandServiceClass(); - Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( int.class, + Constructor< ? extends CommandExecutor> constructor = serviceClass.getConstructor( long.class, KnowledgeBase.class, KnowledgeSessionConfiguration.class, Environment.class );" 874b4979d00ef6c9c350efcb77bc452bcfea8754,hadoop,YARN-1920. Fixed- TestFileSystemApplicationHistoryStore failure on windows. Contributed by- Vinod Kumar Vavilapalli. svn merge --ignore-ancestry -c 1586414 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1586420 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 188a80035ac85..e2af3191db8e9 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -82,6 +82,9 @@ Release 2.4.1 - UNRELEASED YARN-1910. Fixed a race condition in TestAMRMTokens that causes the test to fail more often on Windows. (Xuan Gong via vinodkv) + YARN-1920. Fixed TestFileSystemApplicationHistoryStore failure on windows. + (Vinod Kumar Vavilapalli via zjshen) + Release 2.4.0 - 2014-04-07 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java index 4c8d7452a251e..a5725ebfffeeb 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/FileSystemApplicationHistoryStore.java @@ -179,7 +179,7 @@ public ApplicationHistoryData getApplication(ApplicationId appId) LOG.info(""Completed reading history information of application "" + appId); return historyData; } catch (IOException e) { - LOG.error(""Error when reading history file of application "" + appId); + LOG.error(""Error when reading history file of application "" + appId, e); throw e; } finally { hfReader.close(); @@ -296,7 +296,7 @@ public ApplicationAttemptHistoryData getApplicationAttempt( return historyData; } catch (IOException e) { LOG.error(""Error when reading history file of application attempt"" - + appAttemptId); + + appAttemptId, e); throw e; } finally { hfReader.close(); @@ -344,7 +344,7 @@ public ContainerHistoryData getContainer(ContainerId containerId) + containerId); return historyData; } catch (IOException e) { - LOG.error(""Error when reading history file of container "" + containerId); + LOG.error(""Error when reading history file of container "" + containerId, e); throw e; } finally { hfReader.close(); @@ -420,7 +420,7 @@ public void applicationStarted(ApplicationStartData appStart) + appStart.getApplicationId()); } catch (IOException e) { LOG.error(""Error when openning history file of application "" - + appStart.getApplicationId()); + + appStart.getApplicationId(), e); throw e; } outstandingWriters.put(appStart.getApplicationId(), hfWriter); @@ -437,7 +437,7 @@ public void applicationStarted(ApplicationStartData appStart) + appStart.getApplicationId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing start information of application "" - + appStart.getApplicationId()); + + appStart.getApplicationId(), e); throw e; } } @@ -456,7 +456,7 @@ public void applicationFinished(ApplicationFinishData appFinish) + appFinish.getApplicationId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing finish information of application "" - + appFinish.getApplicationId()); + + appFinish.getApplicationId(), e); throw e; } finally { hfWriter.close(); @@ -480,7 +480,7 @@ public void applicationAttemptStarted( + appAttemptStart.getApplicationAttemptId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing start information of application attempt "" - + appAttemptStart.getApplicationAttemptId()); + + appAttemptStart.getApplicationAttemptId(), e); throw e; } } @@ -501,7 +501,7 @@ public void applicationAttemptFinished( + appAttemptFinish.getApplicationAttemptId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing finish information of application attempt "" - + appAttemptFinish.getApplicationAttemptId()); + + appAttemptFinish.getApplicationAttemptId(), e); throw e; } } @@ -521,7 +521,7 @@ public void containerStarted(ContainerStartData containerStart) + containerStart.getContainerId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing start information of container "" - + containerStart.getContainerId()); + + containerStart.getContainerId(), e); throw e; } } @@ -541,7 +541,7 @@ public void containerFinished(ContainerFinishData containerFinish) + containerFinish.getContainerId() + "" is written""); } catch (IOException e) { LOG.error(""Error when writing finish information of container "" - + containerFinish.getContainerId()); + + containerFinish.getContainerId(), e); } } @@ -676,9 +676,10 @@ public Entry(HistoryDataKey key, byte[] value) { private TFile.Reader reader; private TFile.Reader.Scanner scanner; + FSDataInputStream fsdis; public HistoryFileReader(Path historyFile) throws IOException { - FSDataInputStream fsdis = fs.open(historyFile); + fsdis = fs.open(historyFile); reader = new TFile.Reader(fsdis, fs.getFileStatus(historyFile).getLen(), getConfig()); @@ -707,7 +708,7 @@ public void reset() throws IOException { } public void close() { - IOUtils.cleanup(LOG, scanner, reader); + IOUtils.cleanup(LOG, scanner, reader, fsdis); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java index 627b7b2dd656e..d31018c118134 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/applicationhistoryservice/TestFileSystemApplicationHistoryStore.java @@ -23,6 +23,8 @@ import org.junit.Assert; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; @@ -42,6 +44,9 @@ public class TestFileSystemApplicationHistoryStore extends ApplicationHistoryStoreTestUtils { + private static Log LOG = LogFactory + .getLog(TestFileSystemApplicationHistoryStore.class.getName()); + private FileSystem fs; private Path fsWorkingPath; @@ -50,9 +55,12 @@ public void setup() throws Exception { fs = new RawLocalFileSystem(); Configuration conf = new Configuration(); fs.initialize(new URI(""/""), conf); - fsWorkingPath = new Path(""Test""); + fsWorkingPath = + new Path(""target"", + TestFileSystemApplicationHistoryStore.class.getSimpleName()); fs.delete(fsWorkingPath, true); - conf.set(YarnConfiguration.FS_APPLICATION_HISTORY_STORE_URI, fsWorkingPath.toString()); + conf.set(YarnConfiguration.FS_APPLICATION_HISTORY_STORE_URI, + fsWorkingPath.toString()); store = new FileSystemApplicationHistoryStore(); store.init(conf); store.start(); @@ -67,6 +75,7 @@ public void tearDown() throws Exception { @Test public void testReadWriteHistoryData() throws IOException { + LOG.info(""Starting testReadWriteHistoryData""); testWriteHistoryData(5); testReadHistoryData(5); } @@ -167,6 +176,7 @@ private void testReadHistoryData( @Test public void testWriteAfterApplicationFinish() throws IOException { + LOG.info(""Starting testWriteAfterApplicationFinish""); ApplicationId appId = ApplicationId.newInstance(0, 1); writeApplicationStartData(appId); writeApplicationFinishData(appId); @@ -203,6 +213,7 @@ public void testWriteAfterApplicationFinish() throws IOException { @Test public void testMassiveWriteContainerHistoryData() throws IOException { + LOG.info(""Starting testMassiveWriteContainerHistoryData""); long mb = 1024 * 1024; long usedDiskBefore = fs.getContentSummary(fsWorkingPath).getLength() / mb; ApplicationId appId = ApplicationId.newInstance(0, 1); @@ -221,12 +232,14 @@ public void testMassiveWriteContainerHistoryData() throws IOException { @Test public void testMissingContainerHistoryData() throws IOException { + LOG.info(""Starting testMissingContainerHistoryData""); testWriteHistoryData(3, true, false); testReadHistoryData(3, true, false); } @Test public void testMissingApplicationAttemptHistoryData() throws IOException { + LOG.info(""Starting testMissingApplicationAttemptHistoryData""); testWriteHistoryData(3, false, true); testReadHistoryData(3, false, true); }" 2eeb4ebd8c3af6f5838efe510da4c92ceb0ceb35,elasticsearch,improve memcached test--,p,https://github.com/elastic/elasticsearch,"diff --git a/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java b/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java index 71c01e745a039..2a5bcbd2c7c72 100644 --- a/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java +++ b/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java @@ -21,6 +21,7 @@ import net.spy.memcached.MemcachedClient; import org.elasticsearch.node.Node; +import org.hamcrest.Matchers; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -31,6 +32,8 @@ import static org.elasticsearch.common.xcontent.XContentFactory.*; import static org.elasticsearch.node.NodeBuilder.*; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; /** * @author kimchy (shay.banon) @@ -56,20 +59,29 @@ public void tearDown() { } @Test public void testSimpleOperations() throws Exception { - Future setResult = memcachedClient.set(""/test/person/1"", 0, jsonBuilder().startObject().field(""test"", ""value"").endObject().copiedBytes()); - setResult.get(10, TimeUnit.SECONDS); + Future setResult = memcachedClient.set(""/test/person/1"", 0, jsonBuilder().startObject().field(""test"", ""value"").endObject().copiedBytes()); + assertThat(setResult.get(10, TimeUnit.SECONDS), equalTo(true)); String getResult = (String) memcachedClient.get(""/_refresh""); System.out.println(""REFRESH "" + getResult); + assertThat(getResult, Matchers.containsString(""\""total\"":10"")); + assertThat(getResult, Matchers.containsString(""\""successful\"":5"")); + assertThat(getResult, Matchers.containsString(""\""failed\"":0"")); getResult = (String) memcachedClient.get(""/test/person/1""); System.out.println(""GET "" + getResult); + assertThat(getResult, Matchers.containsString(""\""_index\"":\""test\"""")); + assertThat(getResult, Matchers.containsString(""\""_type\"":\""person\"""")); + assertThat(getResult, Matchers.containsString(""\""_id\"":\""1\"""")); - Future deleteResult = memcachedClient.delete(""/test/person/1""); - deleteResult.get(10, TimeUnit.SECONDS); + Future deleteResult = memcachedClient.delete(""/test/person/1""); + assertThat(deleteResult.get(10, TimeUnit.SECONDS), equalTo(true)); getResult = (String) memcachedClient.get(""/_refresh""); System.out.println(""REFRESH "" + getResult); + assertThat(getResult, Matchers.containsString(""\""total\"":10"")); + assertThat(getResult, Matchers.containsString(""\""successful\"":5"")); + assertThat(getResult, Matchers.containsString(""\""failed\"":0"")); getResult = (String) memcachedClient.get(""/test/person/1""); System.out.println(""GET "" + getResult);" a429e230b632c40cf3167cbac54ea87b6ad87297,spring-framework,revised version checks and exception signatures--,p,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java index d784450b6726..878053a0eb31 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java @@ -42,7 +42,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -583,10 +582,9 @@ protected List getDefaultStrategies(ApplicationContext context, Class * @param context the current Portlet ApplicationContext * @param clazz the strategy implementation class to instantiate * @return the fully configured strategy instance - * @throws BeansException if initialization failed * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() */ - protected Object createDefaultStrategy(ApplicationContext context, Class clazz) throws BeansException { + protected Object createDefaultStrategy(ApplicationContext context, Class clazz) { return context.getAutowireCapableBeanFactory().createBean(clazz); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java index 75cad59c52e2..3ddac18c10db 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java @@ -32,7 +32,6 @@ import javax.portlet.ResourceResponse; import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationListener; @@ -258,7 +257,7 @@ public void setUserinfoUsernameAttributes(String[] userinfoUsernameAttributes) { * have been set. Creates this portlet's ApplicationContext. */ @Override - protected final void initPortletBean() throws PortletException, BeansException { + protected final void initPortletBean() throws PortletException { getPortletContext().log(""Initializing Spring FrameworkPortlet '"" + getPortletName() + ""'""); if (logger.isInfoEnabled()) { logger.info(""FrameworkPortlet '"" + getPortletName() + ""': initialization started""); @@ -273,7 +272,7 @@ protected final void initPortletBean() throws PortletException, BeansException { logger.error(""Context initialization failed"", ex); throw ex; } - catch (BeansException ex) { + catch (RuntimeException ex) { logger.error(""Context initialization failed"", ex); throw ex; } @@ -289,9 +288,8 @@ protected final void initPortletBean() throws PortletException, BeansException { *

Delegates to {@link #createPortletApplicationContext} for actual creation. * Can be overridden in subclasses. * @return the ApplicationContext for this portlet - * @throws BeansException if the context couldn't be initialized */ - protected ApplicationContext initPortletApplicationContext() throws BeansException { + protected ApplicationContext initPortletApplicationContext() { ApplicationContext parent = PortletApplicationContextUtils.getWebApplicationContext(getPortletContext()); ApplicationContext pac = createPortletApplicationContext(parent); @@ -320,13 +318,10 @@ protected ApplicationContext initPortletApplicationContext() throws BeansExcepti * ConfigurablePortletApplicationContext. Can be overridden in subclasses. * @param parent the parent ApplicationContext to use, or null if none * @return the Portlet ApplicationContext for this portlet - * @throws BeansException if the context couldn't be initialized * @see #setContextClass * @see org.springframework.web.portlet.context.XmlPortletApplicationContext */ - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) - throws BeansException { - + protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) { Class contextClass = getContextClass(); if (logger.isDebugEnabled()) { logger.debug(""Portlet with name '"" + getPortletName() + @@ -338,7 +333,6 @@ protected ApplicationContext createPortletApplicationContext(ApplicationContext ""': custom ApplicationContext class ["" + contextClass.getName() + ""] is not of type ConfigurablePortletApplicationContext""); } - ConfigurablePortletApplicationContext pac = (ConfigurablePortletApplicationContext) BeanUtils.instantiateClass(contextClass); @@ -400,19 +394,17 @@ public final ApplicationContext getPortletApplicationContext() { *

The default implementation is empty; subclasses may override this method * to perform any initialization they require. * @throws PortletException in case of an initialization exception - * @throws BeansException if thrown by ApplicationContext methods */ - protected void initFrameworkPortlet() throws PortletException, BeansException { + protected void initFrameworkPortlet() throws PortletException { } /** * Refresh this portlet's application context, as well as the * dependent state of the portlet. - * @throws BeansException in case of errors * @see #getPortletApplicationContext() * @see org.springframework.context.ConfigurableApplicationContext#refresh() */ - public void refresh() throws BeansException { + public void refresh() { ApplicationContext pac = getPortletApplicationContext(); if (!(pac instanceof ConfigurableApplicationContext)) { throw new IllegalStateException(""Portlet ApplicationContext does not support refresh: "" + pac); @@ -438,10 +430,9 @@ public void onApplicationEvent(ContextRefreshedEvent event) { * Called after successful context refresh. *

This implementation is empty. * @param context the current Portlet ApplicationContext - * @throws BeansException in case of errors * @see #refresh() */ - protected void onRefresh(ApplicationContext context) throws BeansException { + protected void onRefresh(ApplicationContext context) { // For subclasses: do nothing by default. } diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java index d94b9907f841..e870cd5525f3 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java @@ -35,7 +35,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -322,7 +321,7 @@ public void setCleanupAfterInclude(boolean cleanupAfterInclude) { * This implementation calls {@link #initStrategies}. */ @Override - protected void onRefresh(ApplicationContext context) throws BeansException { + protected void onRefresh(ApplicationContext context) { initStrategies(context); } @@ -673,11 +672,10 @@ protected List getDefaultStrategies(ApplicationContext context, Class * @param context the current WebApplicationContext * @param clazz the strategy implementation class to instantiate * @return the fully configured strategy instance - * @throws BeansException if initialization failed * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean */ - protected Object createDefaultStrategy(ApplicationContext context, Class clazz) throws BeansException { + protected Object createDefaultStrategy(ApplicationContext context, Class clazz) { return context.getAutowireCapableBeanFactory().createBean(clazz); } @@ -742,7 +740,7 @@ protected void doDispatch(HttpServletRequest request, HttpServletResponse respon int interceptorIndex = -1; try { - ModelAndView mv = null; + ModelAndView mv; boolean errorView = false; try { @@ -1032,13 +1030,11 @@ protected ModelAndView processHandlerException(HttpServletRequest request, * @throws Exception if there's a problem rendering the view */ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception { - // Determine locale for request and apply it to the response. Locale locale = this.localeResolver.resolveLocale(request); response.setLocale(locale); - View view = null; - + View view; if (mv.isReference()) { // We need to resolve the view name. view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request); @@ -1076,7 +1072,7 @@ protected String getDefaultViewName(HttpServletRequest request) throws Exception /** * Resolve the given view name into a View object (to be rendered). - *

Default implementations asks all ViewResolvers of this dispatcher. + *

The default implementations asks all ViewResolvers of this dispatcher. * Can be overridden for custom resolution strategies, potentially based on * specific model attributes or request parameters. * @param viewName the name of the view to resolve @@ -1088,9 +1084,7 @@ protected String getDefaultViewName(HttpServletRequest request) throws Exception * (typically in case of problems creating an actual View object) * @see ViewResolver#resolveViewName */ - protected View resolveViewName(String viewName, - Map model, - Locale locale, + protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request) throws Exception { for (ViewResolver viewResolver : this.viewResolvers) { diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/FrameworkServlet.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/FrameworkServlet.java index 820cd0d702c8..f4fefa855519 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/FrameworkServlet.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/FrameworkServlet.java @@ -24,7 +24,6 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationListener; @@ -297,7 +296,7 @@ public void setDispatchTraceRequest(boolean dispatchTraceRequest) { * have been set. Creates this servlet's WebApplicationContext. */ @Override - protected final void initServletBean() throws ServletException, BeansException { + protected final void initServletBean() throws ServletException { getServletContext().log(""Initializing Spring FrameworkServlet '"" + getServletName() + ""'""); if (this.logger.isInfoEnabled()) { this.logger.info(""FrameworkServlet '"" + getServletName() + ""': initialization started""); @@ -312,7 +311,7 @@ protected final void initServletBean() throws ServletException, BeansException { this.logger.error(""Context initialization failed"", ex); throw ex; } - catch (BeansException ex) { + catch (RuntimeException ex) { this.logger.error(""Context initialization failed"", ex); throw ex; } @@ -329,11 +328,10 @@ protected final void initServletBean() throws ServletException, BeansException { *

Delegates to {@link #createWebApplicationContext} for actual creation * of the context. Can be overridden in subclasses. * @return the WebApplicationContext instance - * @throws BeansException if the context couldn't be initialized * @see #setContextClass * @see #setContextConfigLocation */ - protected WebApplicationContext initWebApplicationContext() throws BeansException { + protected WebApplicationContext initWebApplicationContext() { WebApplicationContext wac = findWebApplicationContext(); if (wac == null) { // No fixed context defined for this servlet - create a local one. @@ -397,12 +395,9 @@ protected WebApplicationContext findWebApplicationContext() { * before returning the context instance. * @param parent the parent ApplicationContext to use, or null if none * @return the WebApplicationContext for this servlet - * @throws BeansException if the context couldn't be initialized * @see org.springframework.web.context.support.XmlWebApplicationContext */ - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - + protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { Class contextClass = getContextClass(); if (this.logger.isDebugEnabled()) { this.logger.debug(""Servlet with name '"" + getServletName() + @@ -415,26 +410,27 @@ protected WebApplicationContext createWebApplicationContext(WebApplicationContex ""': custom WebApplicationContext class ["" + contextClass.getName() + ""] is not of type ConfigurableWebApplicationContext""); } - ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); // Assign the best possible id value. - ServletContext servletContext = getServletContext(); - if (servletContext.getMajorVersion() > 2 || servletContext.getMinorVersion() >= 5) { - // Servlet 2.5's getContextPath available! - wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContext.getContextPath() + ""/"" + getServletName()); - } - else { + ServletContext sc = getServletContext(); + if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) { // Servlet <= 2.4: resort to name specified in web.xml, if any. - String servletContextName = servletContext.getServletContextName(); + String servletContextName = sc.getServletContextName(); if (servletContextName != null) { - wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContextName + ""."" + getServletName()); + wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContextName + + ""."" + getServletName()); } else { wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + getServletName()); } } + else { + // Servlet 2.5's getContextPath available! + wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + sc.getContextPath() + + ""/"" + getServletName()); + } wac.setParent(parent); wac.setServletContext(getServletContext()); @@ -485,19 +481,17 @@ public final WebApplicationContext getWebApplicationContext() { * the WebApplicationContext has been loaded. The default implementation is empty; * subclasses may override this method to perform any initialization they require. * @throws ServletException in case of an initialization exception - * @throws BeansException if thrown by ApplicationContext methods */ - protected void initFrameworkServlet() throws ServletException, BeansException { + protected void initFrameworkServlet() throws ServletException { } /** * Refresh this servlet's application context, as well as the * dependent state of the servlet. - * @throws BeansException in case of errors * @see #getWebApplicationContext() * @see org.springframework.context.ConfigurableApplicationContext#refresh() */ - public void refresh() throws BeansException { + public void refresh() { WebApplicationContext wac = getWebApplicationContext(); if (!(wac instanceof ConfigurableApplicationContext)) { throw new IllegalStateException(""WebApplicationContext does not support refresh: "" + wac); @@ -523,10 +517,9 @@ public void onApplicationEvent(ContextRefreshedEvent event) { * Called after successful context refresh. *

This implementation is empty. * @param context the current WebApplicationContext - * @throws BeansException in case of errors * @see #refresh() */ - protected void onRefresh(ApplicationContext context) throws BeansException { + protected void onRefresh(ApplicationContext context) { // For subclasses: do nothing by default. } @@ -540,7 +533,7 @@ protected void onRefresh(ApplicationContext context) throws BeansException { */ @Override protected final void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { processRequest(request, response); } @@ -551,7 +544,7 @@ protected final void doGet(HttpServletRequest request, HttpServletResponse respo */ @Override protected final void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { processRequest(request, response); } @@ -562,7 +555,7 @@ protected final void doPost(HttpServletRequest request, HttpServletResponse resp */ @Override protected final void doPut(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { processRequest(request, response); } @@ -573,7 +566,7 @@ protected final void doPut(HttpServletRequest request, HttpServletResponse respo */ @Override protected final void doDelete(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { processRequest(request, response); } @@ -584,7 +577,9 @@ protected final void doDelete(HttpServletRequest request, HttpServletResponse re * @see #doService */ @Override - protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doOptions(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + super.doOptions(request, response); if (this.dispatchOptionsRequest) { processRequest(request, response); @@ -597,7 +592,9 @@ protected void doOptions(HttpServletRequest request, HttpServletResponse respons * @see #doService */ @Override - protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + protected void doTrace(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + super.doTrace(request, response); if (this.dispatchTraceRequest) { processRequest(request, response); @@ -715,7 +712,7 @@ protected String getUsernameForRequest(HttpServletRequest request) { * @see javax.servlet.http.HttpServlet#doPost */ protected abstract void doService(HttpServletRequest request, HttpServletResponse response) - throws Exception; + throws Exception; /** diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java index d1336917cc2b..22345a31f0a1 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -26,7 +26,6 @@ import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.access.BeanFactoryLocator; import org.springframework.beans.factory.access.BeanFactoryReference; import org.springframework.context.ApplicationContext; @@ -167,14 +166,10 @@ public class ContextLoader { * ""{@link #CONFIG_LOCATION_PARAM contextConfigLocation}"" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext - * @throws IllegalStateException if there is already a root application context present - * @throws BeansException if the context failed to initialize * @see #CONTEXT_CLASS_PARAM * @see #CONFIG_LOCATION_PARAM */ - public WebApplicationContext initWebApplicationContext(ServletContext servletContext) - throws IllegalStateException, BeansException { - + public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( ""Cannot initialize context because there is already a root application context present - "" + @@ -229,32 +224,24 @@ public WebApplicationContext initWebApplicationContext(ServletContext servletCon * Can be overridden in subclasses. *

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 sc current servlet context * @param parent the parent ApplicationContext to use, or null if none * @return the root WebApplicationContext - * @throws BeansException if the context couldn't be initialized * @see ConfigurableWebApplicationContext */ - protected WebApplicationContext createWebApplicationContext( - ServletContext servletContext, ApplicationContext parent) throws BeansException { - - Class contextClass = determineContextClass(servletContext); + protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent) { + Class contextClass = determineContextClass(sc); if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException(""Custom context class ["" + contextClass.getName() + ""] is not of type ["" + ConfigurableWebApplicationContext.class.getName() + ""]""); } - ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); // Assign the best possible id value. - if (servletContext.getMajorVersion() > 2 || servletContext.getMinorVersion() >= 5) { - // Servlet 2.5's getContextPath available! - wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContext.getContextPath()); - } - else { + if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) { // Servlet <= 2.4: resort to name specified in web.xml, if any. - String servletContextName = servletContext.getServletContextName(); + String servletContextName = sc.getServletContextName(); if (servletContextName != null) { wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContextName); } @@ -262,13 +249,16 @@ protected WebApplicationContext createWebApplicationContext( wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX); } } + else { + // Servlet 2.5's getContextPath available! + wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + sc.getContextPath()); + } wac.setParent(parent); - wac.setServletContext(servletContext); - wac.setConfigLocation(servletContext.getInitParameter(CONFIG_LOCATION_PARAM)); - customizeContext(servletContext, wac); + wac.setServletContext(sc); + wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM)); + customizeContext(sc, wac); wac.refresh(); - return wac; } @@ -277,11 +267,10 @@ protected WebApplicationContext createWebApplicationContext( * default XmlWebApplicationContext or a custom context class if specified. * @param servletContext current servlet context * @return the WebApplicationContext implementation class to use - * @throws ApplicationContextException if the context class couldn't be loaded * @see #CONTEXT_CLASS_PARAM * @see org.springframework.web.context.support.XmlWebApplicationContext */ - protected Class determineContextClass(ServletContext servletContext) throws ApplicationContextException { + protected Class determineContextClass(ServletContext servletContext) { String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); if (contextClassName != null) { try { @@ -336,12 +325,9 @@ protected void customizeContext( * which also use the same configuration parameters. * @param servletContext current servlet context * @return the parent application context, or null if none - * @throws BeansException if the context couldn't be initialized * @see org.springframework.context.access.ContextSingletonBeanFactoryLocator */ - protected ApplicationContext loadParentContext(ServletContext servletContext) - throws BeansException { - + protected ApplicationContext loadParentContext(ServletContext servletContext) { ApplicationContext parentContext = null; String locatorFactorySelector = servletContext.getInitParameter(LOCATOR_FACTORY_SELECTOR_PARAM); String parentContextKey = servletContext.getInitParameter(LOCATOR_FACTORY_KEY_PARAM);" da5ff665396d5f0cbd70b9ea8a53387c0b40cbd1,orientdb,Fixed problem with linkeset modified right after- query in remote configuration--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java index c3c0d2514ff..2bc08a33eda 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java +++ b/core/src/main/java/com/orientechnologies/orient/core/type/tree/OMVRBTreeRID.java @@ -101,6 +101,8 @@ public OMVRBTreePersistent load() { @Override public OIdentifiable internalPut(final OIdentifiable e, final OIdentifiable v) { + ((OMVRBTreeRIDProvider) dataProvider).lazyUnmarshall(); + if (e.getIdentity().isNew()) { final ORecord record = e.getRecord(); @@ -114,7 +116,6 @@ else if (newEntries.containsKey(record)) return null; } - ((OMVRBTreeRIDProvider) dataProvider).lazyUnmarshall(); return super.internalPut(e, null); }" cff8f47eb7a1ad17442ec0d3c9bb596d29873faf,camel,"CAMEL-1338: Added basic operator support for- simple language - end users is confused its not working, and nice to have- core support for basic operators. Added ?method=methodname for the bean- langauge so its in line with the bean component.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@744707 13f79535-47bb-0310-9956-ffa450edef68-",a,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java index 18ad5f6c5b6dd..dc10bb91e3b4e 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java @@ -289,6 +289,22 @@ public String toString() { }; } + /** + * Returns the expression for the exchanges inbound message body type + */ + public static Expression bodyType() { + return new ExpressionAdapter() { + public Object evaluate(Exchange exchange) { + return exchange.getIn().getBody().getClass(); + } + + @Override + public String toString() { + return ""bodyType""; + } + }; + } + /** * Returns the expression for the exchanges inbound message body converted * to the given type @@ -444,6 +460,23 @@ public String toString() { }; } + /** + * Returns an expression which converts the given expression to the given type the type + * expression is evaluted to + */ + public static Expression convertTo(final Expression expression, final Expression type) { + return new ExpressionAdapter() { + public Object evaluate(Exchange exchange) { + return expression.evaluate(exchange, type.evaluate(exchange).getClass()); + } + + @Override + public String toString() { + return """" + expression + "".convertTo("" + type + "")""; + } + }; + } + /** * Returns a tokenize expression which will tokenize the string with the * given token diff --git a/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java b/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java index 96b3bda6ef116..7fbad60098181 100644 --- a/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java +++ b/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java @@ -82,13 +82,20 @@ public Predicate createPredicate(String expression) { public Expression createExpression(String expression) { ObjectHelper.notNull(expression, ""expression""); - int idx = expression.lastIndexOf('.'); String beanName = expression; String method = null; + + // we support both the .method name and the ?method= syntax + // as the ?method= syntax is very common for the bean component + int idx = expression.lastIndexOf('.'); if (idx > 0) { beanName = expression.substring(0, idx); method = expression.substring(idx + 1); + } else if (expression.contains(""?method="")) { + beanName = ObjectHelper.before(expression, ""?""); + method = ObjectHelper.after(expression, ""?method=""); } + return new BeanExpression(beanName, method); } diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java new file mode 100644 index 0000000000000..5bb7b7af07410 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java @@ -0,0 +1,72 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.language.simple; + +/** + * Operators supported by simple language + *

    + *
  • EQ : ==
  • + *
  • GT : >
  • + *
  • GTE : >=
  • + *
  • LT : <
  • + *
  • LTE : <=
  • + *
  • NOT : !=
  • + *
+ */ +public enum SimpleLangaugeOperator { + + EQ, GT, GTE, LT, LTE, NOT; + + public static SimpleLangaugeOperator asOperator(String text) { + if (""=="".equals(text)) { + return EQ; + } else if ("">"".equals(text)) { + return GT; + } else if ("">="".equals(text)) { + return GTE; + } else if (""<"".equals(text)) { + return LT; + } else if (""<="".equals(text)) { + return LTE; + } else if (""!="".equals(text)) { + return NOT; + } + throw new IllegalArgumentException(""Operator not supported: "" + text); + } + + public String getOperatorText(SimpleLangaugeOperator operator) { + if (operator == EQ) { + return ""==""; + } else if (operator == GT) { + return "">""; + } else if (operator == GTE) { + return "">=""; + } else if (operator == LT) { + return ""<""; + } else if (operator == LTE) { + return ""<=""; + } else if (operator == NOT) { + return ""!=""; + } + return """"; + } + + @Override + public String toString() { + return getOperatorText(this); + } +} diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java index b7d9d4e375701..2cd984df69eb3 100644 --- a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java +++ b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java @@ -18,30 +18,113 @@ import java.util.ArrayList; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.camel.Exchange; import org.apache.camel.Expression; import org.apache.camel.Predicate; import org.apache.camel.builder.ExpressionBuilder; import org.apache.camel.builder.PredicateBuilder; +import org.apache.camel.impl.ExpressionAdapter; import org.apache.camel.spi.Language; +import org.apache.camel.util.ObjectHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.apache.camel.language.simple.SimpleLangaugeOperator.*; /** * Abstract base class for Simple languages. */ public abstract class SimpleLanguageSupport implements Language { - + + protected static final Pattern PATTERN = Pattern.compile(""^\\$\\{(.+)\\}\\s+(==|>|>=|<|<=|!=|is)\\s+(.+)$""); + protected final Log log = LogFactory.getLog(getClass()); + public Predicate createPredicate(String expression) { return PredicateBuilder.toPredicate(createExpression(expression)); } public Expression createExpression(String expression) { - if (expression.indexOf(""${"") >= 0) { - return createComplexExpression(expression); + Matcher matcher = PATTERN.matcher(expression); + if (matcher.matches()) { + if (log.isDebugEnabled()) { + log.debug(""Expression is evaluated as operator expression: "" + expression); + } + return createOperatorExpression(matcher, expression); + } else if (expression.indexOf(""${"") >= 0) { + if (log.isDebugEnabled()) { + log.debug(""Expression is evaluated as complex expression: "" + expression); + } + return createComplexConcatExpression(expression); + } else { + if (log.isDebugEnabled()) { + log.debug(""Expression is evaluated as simple expression: "" + expression); + } + return createSimpleExpression(expression); + } + } + + private Expression createOperatorExpression(final Matcher matcher, final String expression) { + final Expression left = createSimpleExpression(matcher.group(1)); + final SimpleLangaugeOperator operator = asOperator(matcher.group(2)); + + // the right hand side expression can either be a constant expression wiht ' ' + // or another simple expression using ${ } placeholders + String text = matcher.group(3); + + final Expression right; + // special null handling + if (""null"".equals(text)) { + right = createConstantExpression(null); + } else { + // text can either be a constant enclosed by ' ' or another expression using ${ } placeholders + String constant = ObjectHelper.between(text, ""'"", ""'""); + String simple = ObjectHelper.between(text, ""${"", ""}""); + + Expression exp = simple != null ? createSimpleExpression(simple) : createConstantExpression(constant); + // to support numeric comparions using > and < operators we must convert the right hand side + // to the same type as the left + right = ExpressionBuilder.convertTo(exp, left); } - return createSimpleExpression(expression); + + return new ExpressionAdapter() { + @Override + protected String assertionFailureMessage(Exchange exchange) { + return super.assertionFailureMessage(exchange); + } + + @Override + public Object evaluate(Exchange exchange) { + Predicate predicate = null; + if (operator == EQ) { + predicate = PredicateBuilder.isEqualTo(left, right); + } else if (operator == GT) { + predicate = PredicateBuilder.isGreaterThan(left, right); + } else if (operator == GTE) { + predicate = PredicateBuilder.isGreaterThanOrEqualTo(left, right); + } else if (operator == LT) { + predicate = PredicateBuilder.isLessThan(left, right); + } else if (operator == LTE) { + predicate = PredicateBuilder.isLessThanOrEqualTo(left, right); + } else if (operator == NOT) { + predicate = PredicateBuilder.isNotEqualTo(left, right); + } + + if (predicate == null) { + throw new IllegalArgumentException(""Unsupported operator: "" + operator + "" for expression: "" + expression); + } + return predicate.matches(exchange); + } + + @Override + public String toString() { + return left + "" "" + operator + "" "" + right; + } + }; } - protected Expression createComplexExpression(String expression) { + protected Expression createComplexConcatExpression(String expression) { List results = new ArrayList(); int pivot = 0; @@ -74,6 +157,10 @@ protected Expression createConstantExpression(String expression, int start, int return ExpressionBuilder.constantExpression(expression.substring(start, end)); } + protected Expression createConstantExpression(String expression) { + return ExpressionBuilder.constantExpression(expression); + } + /** * Creates the simple expression based on the extracted content from the ${ } place holders * diff --git a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java index 0ee0bb795d7b9..c1429a98444c5 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java @@ -291,6 +291,28 @@ public static String capitalize(String text) { return answer; } + public static String after(String text, String after) { + if (!text.contains(after)) { + return null; + } + return text.substring(text.indexOf(after) + after.length()); + } + + public static String before(String text, String before) { + if (!text.contains(before)) { + return null; + } + return text.substring(0, text.indexOf(before)); + } + + public static String between(String text, String after, String before) { + text = after(text, after); + if (text == null) { + return null; + } + return before(text, before); + } + /** * Returns true if the collection contains the specified value */ diff --git a/camel-core/src/test/java/org/apache/camel/language/BeanTest.java b/camel-core/src/test/java/org/apache/camel/language/BeanTest.java index 8ef7bfe3ca5c9..a4f2d0b916867 100644 --- a/camel-core/src/test/java/org/apache/camel/language/BeanTest.java +++ b/camel-core/src/test/java/org/apache/camel/language/BeanTest.java @@ -32,10 +32,12 @@ public class BeanTest extends LanguageTestSupport { public void testSimpleExpressions() throws Exception { assertExpression(""foo.cheese"", ""abc""); + assertExpression(""foo?method=cheese"", ""abc""); } public void testPredicates() throws Exception { assertPredicate(""foo.isFooHeaderAbc""); + assertPredicate(""foo?method=isFooHeaderAbc""); } public void testBeanTypeExpression() throws Exception { diff --git a/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java b/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java new file mode 100644 index 0000000000000..cafb0b0adbc1d --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java @@ -0,0 +1,143 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.language; + +import org.apache.camel.Exchange; +import org.apache.camel.LanguageTestSupport; +import org.apache.camel.impl.JndiRegistry; + +/** + * @version $Revision$ + */ +public class SimpleOperatorTest extends LanguageTestSupport { + + @Override + protected JndiRegistry createRegistry() throws Exception { + JndiRegistry jndi = super.createRegistry(); + jndi.bind(""generator"", new MyFileNameGenerator()); + return jndi; + } + + public void testEqualOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} == 'abc'"", true); + assertExpression(""${in.header.foo} == 'def'"", false); + assertExpression(""${in.header.foo} == '1'"", false); + + // integer to string comparioson + assertExpression(""${in.header.bar} == '123'"", true); + assertExpression(""${in.header.bar} == '444'"", false); + assertExpression(""${in.header.bar} == '1'"", false); + } + + public void testNotEqualOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} != 'abc'"", false); + assertExpression(""${in.header.foo} != 'def'"", true); + assertExpression(""${in.header.foo} != '1'"", true); + + // integer to string comparioson + assertExpression(""${in.header.bar} != '123'"", false); + assertExpression(""${in.header.bar} != '444'"", true); + assertExpression(""${in.header.bar} != '1'"", true); + } + + public void testGreatherThanOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} > 'aaa'"", true); + assertExpression(""${in.header.foo} > 'def'"", false); + + // integer to string comparioson + assertExpression(""${in.header.bar} > '100'"", true); + assertExpression(""${in.header.bar} > '123'"", false); + assertExpression(""${in.header.bar} > '200'"", false); + } + + public void testGreatherThanOrEqualOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} >= 'aaa'"", true); + assertExpression(""${in.header.foo} >= 'abc'"", true); + assertExpression(""${in.header.foo} >= 'def'"", false); + + // integer to string comparioson + assertExpression(""${in.header.bar} >= '100'"", true); + assertExpression(""${in.header.bar} >= '123'"", true); + assertExpression(""${in.header.bar} >= '200'"", false); + } + + public void testLessThanOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} < 'aaa'"", false); + assertExpression(""${in.header.foo} < 'def'"", true); + + // integer to string comparioson + assertExpression(""${in.header.bar} < '100'"", false); + assertExpression(""${in.header.bar} < '123'"", false); + assertExpression(""${in.header.bar} < '200'"", true); + } + + public void testLessThanOrEqualOperator() throws Exception { + // string to string comparison + assertExpression(""${in.header.foo} <= 'aaa'"", false); + assertExpression(""${in.header.foo} <= 'abc'"", true); + assertExpression(""${in.header.foo} <= 'def'"", true); + + // integer to string comparioson + assertExpression(""${in.header.bar} <= '100'"", false); + assertExpression(""${in.header.bar} <= '123'"", true); + assertExpression(""${in.header.bar} <= '200'"", true); + } + + public void testIsNull() throws Exception { + assertExpression(""${in.header.foo} == null"", false); + assertExpression(""${in.header.none} == null"", true); + } + + public void testIsNotNull() throws Exception { + assertExpression(""${in.header.foo} != null"", true); + assertExpression(""${in.header.none} != null"", false); + } + + public void testRightOperatorIsSimpleLanauge() throws Exception { + // operator on right side is also using ${ } placeholders + assertExpression(""${in.header.foo} == ${in.header.foo}"", true); + assertExpression(""${in.header.foo} == ${in.header.bar}"", false); + } + + public void testRightOperatorIsBeanLanauge() throws Exception { + // operator on right side is also using ${ } placeholders + assertExpression(""${in.header.foo} == ${bean:generator.generateFilename}"", true); + + assertExpression(""${in.header.bar} == ${bean:generator.generateId}"", true); + assertExpression(""${in.header.bar} >= ${bean:generator.generateId}"", true); + } + + protected String getLanguageName() { + return ""simple""; + } + + public class MyFileNameGenerator { + public String generateFilename(Exchange exchange) { + return ""abc""; + } + + public int generateId(Exchange exchange) { + return 123; + } + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java b/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java index fffec73fd0bb2..624e03b4b6383 100644 --- a/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java +++ b/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java @@ -150,4 +150,22 @@ public void testCreateIteratorWithStringAndSemiColonSeparator() { assertEquals(""c"", it.next()); } + public void testBefore() { + assertEquals(""Hello "", ObjectHelper.before(""Hello World"", ""World"")); + assertEquals(""Hello "", ObjectHelper.before(""Hello World Again"", ""World"")); + assertEquals(null, ObjectHelper.before(""Hello Again"", ""Foo"")); + } + + public void testAfter() { + assertEquals("" World"", ObjectHelper.after(""Hello World"", ""Hello"")); + assertEquals("" World Again"", ObjectHelper.after(""Hello World Again"", ""Hello"")); + assertEquals(null, ObjectHelper.after(""Hello Again"", ""Foo"")); + } + + public void testBetween() { + assertEquals(""foo bar"", ObjectHelper.between(""Hello 'foo bar' how are you"", ""'"", ""'"")); + assertEquals(""foo bar"", ObjectHelper.between(""Hello ${foo bar} how are you"", ""${"", ""}"")); + assertEquals(null, ObjectHelper.between(""Hello ${foo bar} how are you"", ""'"", ""'"")); + } + }" 59b8a139d72463fbf324e851a9e6daf918fe1b22,spring-framework,JndiObjectFactoryBean explicitly only chooses- public interfaces as default proxy interfaces (SPR-5869)--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java index 9914e0dbdae3..504a96ad8c64 100644 --- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java +++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.jndi; import java.lang.reflect.Method; - +import java.lang.reflect.Modifier; import javax.naming.Context; import javax.naming.NamingException; @@ -295,7 +295,12 @@ private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws Na throw new IllegalStateException( ""Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'""); } - proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader)); + Class[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader); + for (Class ifc : ifcs) { + if (Modifier.isPublic(ifc.getModifiers())) { + proxyFactory.addInterface(ifc); + } + } } if (jof.exposeAccessContext) { proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));" 143e48c25abfebb6c8c6d3250c0745f5636398b4,hadoop,YARN-2493. Added node-labels page on RM web UI.- Contributed by Wangda Tan (cherry picked from commit- b7442bf92eb6e1ae64a0f9644ffc2eee4597aad5)--,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index e4622a136405f..d52acc79854e0 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -123,6 +123,8 @@ Release 2.7.0 - UNRELEASED YARN-2993. Several fixes (missing acl check, error log msg ...) and some refinement in AdminService. (Yi Liu via junping_du) + YARN-2943. Added node-labels page on RM web UI. (Wangda Tan via jianhe) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java index 070aa1fc85864..e888cc56d8229 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java @@ -72,8 +72,8 @@ public class CommonNodeLabelsManager extends AbstractService { protected Dispatcher dispatcher; - protected ConcurrentMap labelCollections = - new ConcurrentHashMap(); + protected ConcurrentMap labelCollections = + new ConcurrentHashMap(); protected ConcurrentMap nodeCollections = new ConcurrentHashMap(); @@ -82,19 +82,6 @@ public class CommonNodeLabelsManager extends AbstractService { protected NodeLabelsStore store; - protected static class Label { - private Resource resource; - - protected Label() { - this.resource = Resource.newInstance(0, 0); - } - - public Resource getResource() { - return this.resource; - } - - } - /** * A Host can have multiple Nodes */ @@ -201,7 +188,7 @@ protected void initDispatcher(Configuration conf) { protected void serviceInit(Configuration conf) throws Exception { initNodeLabelStore(conf); - labelCollections.put(NO_LABEL, new Label()); + labelCollections.put(NO_LABEL, new NodeLabel(NO_LABEL)); } protected void initNodeLabelStore(Configuration conf) throws Exception { @@ -271,7 +258,7 @@ public void addToCluserNodeLabels(Set labels) throws IOException { for (String label : labels) { // shouldn't overwrite it to avoid changing the Label.resource if (this.labelCollections.get(label) == null) { - this.labelCollections.put(label, new Label()); + this.labelCollections.put(label, new NodeLabel(label)); newLabels.add(label); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java new file mode 100644 index 0000000000000..766864887d02f --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java @@ -0,0 +1,96 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.nodelabels; + +import org.apache.commons.lang.StringUtils; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.util.resource.Resources; + +public class NodeLabel implements Comparable { + private Resource resource; + private int numActiveNMs; + private String labelName; + + public NodeLabel(String labelName) { + this(labelName, Resource.newInstance(0, 0), 0); + } + + protected NodeLabel(String labelName, Resource res, int activeNMs) { + this.labelName = labelName; + this.resource = res; + this.numActiveNMs = activeNMs; + } + + public void addNode(Resource nodeRes) { + Resources.addTo(resource, nodeRes); + numActiveNMs++; + } + + public void removeNode(Resource nodeRes) { + Resources.subtractFrom(resource, nodeRes); + numActiveNMs--; + } + + public Resource getResource() { + return this.resource; + } + + public int getNumActiveNMs() { + return numActiveNMs; + } + + public String getLabelName() { + return labelName; + } + + public NodeLabel getCopy() { + return new NodeLabel(labelName, resource, numActiveNMs); + } + + @Override + public int compareTo(NodeLabel o) { + // We should always put empty label entry first after sorting + if (labelName.isEmpty() != o.getLabelName().isEmpty()) { + if (labelName.isEmpty()) { + return -1; + } + return 1; + } + + return labelName.compareTo(o.getLabelName()); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof NodeLabel) { + NodeLabel other = (NodeLabel) obj; + return Resources.equals(resource, other.getResource()) + && StringUtils.equals(labelName, other.getLabelName()) + && (other.getNumActiveNMs() == numActiveNMs); + } + return false; + } + + @Override + public int hashCode() { + final int prime = 502357; + return (int) ((((long) labelName.hashCode() << 8) + + (resource.hashCode() << 4) + numActiveNMs) % prime); + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java index 91d2a2019ab8f..62c3c7a0ef3d0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java @@ -32,4 +32,5 @@ public interface YarnWebParams { String APP_STATE = ""app.state""; String QUEUE_NAME = ""queue.name""; String NODE_STATE = ""node.state""; + String NODE_LABEL = ""node.label""; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java index 646441a10f78f..828d1bc34dac3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java @@ -19,10 +19,12 @@ package org.apache.hadoop.yarn.server.resourcemanager.nodelabels; import java.io.IOException; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -37,6 +39,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.nodelabels.NodeLabel; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeLabelsUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; @@ -360,8 +363,8 @@ private void updateResourceMappings(Map before, // no label in the past if (oldLabels.isEmpty()) { // update labels - Label label = labelCollections.get(NO_LABEL); - Resources.subtractFrom(label.getResource(), oldNM.resource); + NodeLabel label = labelCollections.get(NO_LABEL); + label.removeNode(oldNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { @@ -370,11 +373,11 @@ private void updateResourceMappings(Map before, } else { // update labels for (String labelName : oldLabels) { - Label label = labelCollections.get(labelName); + NodeLabel label = labelCollections.get(labelName); if (null == label) { continue; } - Resources.subtractFrom(label.getResource(), oldNM.resource); + label.removeNode(oldNM.resource); } // update queues, only queue can access this node will be subtract @@ -395,8 +398,8 @@ private void updateResourceMappings(Map before, // no label in the past if (newLabels.isEmpty()) { // update labels - Label label = labelCollections.get(NO_LABEL); - Resources.addTo(label.getResource(), newNM.resource); + NodeLabel label = labelCollections.get(NO_LABEL); + label.addNode(newNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { @@ -405,8 +408,8 @@ private void updateResourceMappings(Map before, } else { // update labels for (String labelName : newLabels) { - Label label = labelCollections.get(labelName); - Resources.addTo(label.getResource(), newNM.resource); + NodeLabel label = labelCollections.get(labelName); + label.addNode(newNM.resource); } // update queues, only queue can access this node will be subtract @@ -475,4 +478,21 @@ public boolean checkAccess(UserGroupInformation user) { public void setRMContext(RMContext rmContext) { this.rmContext = rmContext; } + + public List pullRMNodeLabelsInfo() { + try { + readLock.lock(); + List infos = new ArrayList(); + + for (Entry entry : labelCollections.entrySet()) { + NodeLabel label = entry.getValue(); + infos.add(label.getCopy()); + } + + Collections.sort(infos); + return infos; + } finally { + readLock.unlock(); + } + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java index ce8fd9e2263ce..db00bb04921b1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java @@ -33,7 +33,8 @@ public class NavBlock extends HtmlBlock { h3(""Cluster""). ul(). li().a(url(""cluster""), ""About"")._(). - li().a(url(""nodes""), ""Nodes"")._(); + li().a(url(""nodes""), ""Nodes"")._(). + li().a(url(""nodelabels""), ""Node Labels"")._(); UL>>> subAppsList = mainList. li().a(url(""apps""), ""Applications""). ul(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java new file mode 100644 index 0000000000000..5e8c1ed5bf2ec --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java @@ -0,0 +1,91 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.webapp; + +import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; + +import org.apache.hadoop.yarn.nodelabels.NodeLabel; +import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; +import org.apache.hadoop.yarn.webapp.SubView; +import org.apache.hadoop.yarn.webapp.YarnWebParams; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TABLE; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TBODY; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TR; +import org.apache.hadoop.yarn.webapp.view.HtmlBlock; + +import com.google.inject.Inject; + +public class NodeLabelsPage extends RmView { + static class NodeLabelsBlock extends HtmlBlock { + final ResourceManager rm; + + @Inject + NodeLabelsBlock(ResourceManager rm, ViewContext ctx) { + super(ctx); + this.rm = rm; + } + + @Override + protected void render(Block html) { + TBODY> tbody = html.table(""#nodelabels""). + thead(). + tr(). + th("".name"", ""Label Name""). + th("".numOfActiveNMs"", ""Num Of Active NMs""). + th("".totalResource"", ""Total Resource""). + _()._(). + tbody(); + + RMNodeLabelsManager nlm = rm.getRMContext().getNodeLabelManager(); + for (NodeLabel info : nlm.pullRMNodeLabelsInfo()) { + TR>> row = + tbody.tr().td( + info.getLabelName().isEmpty() ? """" : info + .getLabelName()); + int nActiveNMs = info.getNumActiveNMs(); + if (nActiveNMs > 0) { + row = row.td() + .a(url(""nodes"", + ""?"" + YarnWebParams.NODE_LABEL + ""="" + info.getLabelName()), + String.valueOf(nActiveNMs)) + ._(); + } else { + row = row.td(String.valueOf(nActiveNMs)); + } + row.td(info.getResource().toString())._(); + } + tbody._()._(); + } + } + + @Override protected void preHead(Page.HTML<_> html) { + commonPreHead(html); + String title = ""Node labels of the cluster""; + setTitle(title); + set(DATATABLES_ID, ""nodelabels""); + setTableStyles(html, ""nodelabels"", "".healthStatus {width:10em}"", + "".healthReport {width:10em}""); + } + + @Override protected Class content() { + return NodeLabelsBlock.class; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java index d3849ae5fc495..f28a9a88bc3be 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java @@ -1,24 +1,25 @@ /** -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* ""License""); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an ""AS IS"" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.hadoop.yarn.server.resourcemanager.webapp; -import static org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebApp.NODE_STATE; +import static org.apache.hadoop.yarn.webapp.YarnWebParams.NODE_STATE; +import static org.apache.hadoop.yarn.webapp.YarnWebParams.NODE_LABEL; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID; @@ -28,7 +29,9 @@ import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.NodeState; +import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeInfo; @@ -60,26 +63,20 @@ protected void render(Block html) { ResourceScheduler sched = rm.getResourceScheduler(); String type = $(NODE_STATE); - TBODY> tbody = html.table(""#nodes""). - thead(). - tr(). - th("".nodelabels"", ""Node Labels""). - th("".rack"", ""Rack""). - th("".state"", ""Node State""). - th("".nodeaddress"", ""Node Address""). - th("".nodehttpaddress"", ""Node HTTP Address""). - th("".lastHealthUpdate"", ""Last health-update""). - th("".healthReport"", ""Health-report""). - th("".containers"", ""Containers""). - th("".mem"", ""Mem Used""). - th("".mem"", ""Mem Avail""). - th("".vcores"", ""VCores Used""). - th("".vcores"", ""VCores Avail""). - th("".nodeManagerVersion"", ""Version""). - _()._(). - tbody(); + String labelFilter = $(NODE_LABEL, CommonNodeLabelsManager.ANY).trim(); + TBODY> tbody = + html.table(""#nodes"").thead().tr().th("".nodelabels"", ""Node Labels"") + .th("".rack"", ""Rack"").th("".state"", ""Node State"") + .th("".nodeaddress"", ""Node Address"") + .th("".nodehttpaddress"", ""Node HTTP Address"") + .th("".lastHealthUpdate"", ""Last health-update"") + .th("".healthReport"", ""Health-report"") + .th("".containers"", ""Containers"").th("".mem"", ""Mem Used"") + .th("".mem"", ""Mem Avail"").th("".vcores"", ""VCores Used"") + .th("".vcores"", ""VCores Avail"") + .th("".nodeManagerVersion"", ""Version"")._()._().tbody(); NodeState stateFilter = null; - if(type != null && !type.isEmpty()) { + if (type != null && !type.isEmpty()) { stateFilter = NodeState.valueOf(type.toUpperCase()); } Collection rmNodes = this.rm.getRMContext().getRMNodes().values(); @@ -97,9 +94,9 @@ protected void render(Block html) { } } for (RMNode ni : rmNodes) { - if(stateFilter != null) { + if (stateFilter != null) { NodeState state = ni.getState(); - if(!stateFilter.equals(state)) { + if (!stateFilter.equals(state)) { continue; } } else { @@ -109,61 +106,71 @@ protected void render(Block html) { continue; } } + // Besides state, we need to filter label as well. + if (!labelFilter.equals(RMNodeLabelsManager.ANY)) { + if (labelFilter.isEmpty()) { + // Empty label filter means only shows nodes without label + if (!ni.getNodeLabels().isEmpty()) { + continue; + } + } else if (!ni.getNodeLabels().contains(labelFilter)) { + // Only nodes have given label can show on web page. + continue; + } + } NodeInfo info = new NodeInfo(ni, sched); - int usedMemory = (int)info.getUsedMemory(); - int availableMemory = (int)info.getAvailableMemory(); - TR>> row = tbody.tr(). - td(StringUtils.join("","", info.getNodeLabels())). - td(info.getRack()). - td(info.getState()). - td(info.getNodeId()); + int usedMemory = (int) info.getUsedMemory(); + int availableMemory = (int) info.getAvailableMemory(); + TR>> row = + tbody.tr().td(StringUtils.join("","", info.getNodeLabels())) + .td(info.getRack()).td(info.getState()).td(info.getNodeId()); if (isInactive) { row.td()._(""N/A"")._(); } else { String httpAddress = info.getNodeHTTPAddress(); - row.td().a(""//"" + httpAddress, - httpAddress)._(); + row.td().a(""//"" + httpAddress, httpAddress)._(); } - row.td().br().$title(String.valueOf(info.getLastHealthUpdate()))._(). - _(Times.format(info.getLastHealthUpdate()))._(). - td(info.getHealthReport()). - td(String.valueOf(info.getNumContainers())). - td().br().$title(String.valueOf(usedMemory))._(). - _(StringUtils.byteDesc(usedMemory * BYTES_IN_MB))._(). - td().br().$title(String.valueOf(availableMemory))._(). - _(StringUtils.byteDesc(availableMemory * BYTES_IN_MB))._(). - td(String.valueOf(info.getUsedVirtualCores())). - td(String.valueOf(info.getAvailableVirtualCores())). - td(ni.getNodeManagerVersion()). - _(); + row.td().br().$title(String.valueOf(info.getLastHealthUpdate()))._() + ._(Times.format(info.getLastHealthUpdate()))._() + .td(info.getHealthReport()) + .td(String.valueOf(info.getNumContainers())).td().br() + .$title(String.valueOf(usedMemory))._() + ._(StringUtils.byteDesc(usedMemory * BYTES_IN_MB))._().td().br() + .$title(String.valueOf(availableMemory))._() + ._(StringUtils.byteDesc(availableMemory * BYTES_IN_MB))._() + .td(String.valueOf(info.getUsedVirtualCores())) + .td(String.valueOf(info.getAvailableVirtualCores())) + .td(ni.getNodeManagerVersion())._(); } tbody._()._(); } } - @Override protected void preHead(Page.HTML<_> html) { + @Override + protected void preHead(Page.HTML<_> html) { commonPreHead(html); String type = $(NODE_STATE); String title = ""Nodes of the cluster""; - if(type != null && !type.isEmpty()) { - title = title+"" (""+type+"")""; + if (type != null && !type.isEmpty()) { + title = title + "" ("" + type + "")""; } setTitle(title); set(DATATABLES_ID, ""nodes""); set(initID(DATATABLES, ""nodes""), nodesTableInit()); setTableStyles(html, ""nodes"", "".healthStatus {width:10em}"", - "".healthReport {width:10em}""); + "".healthReport {width:10em}""); } - @Override protected Class content() { + @Override + protected Class content() { return NodesBlock.class; } private String nodesTableInit() { StringBuilder b = tableInit().append("", aoColumnDefs: [""); b.append(""{'bSearchable': false, 'aTargets': [ 6 ]}""); - b.append("", {'sType': 'title-numeric', 'bSearchable': false, "" + - ""'aTargets': [ 7, 8 ] }""); + b.append("", {'sType': 'title-numeric', 'bSearchable': false, "" + + ""'aTargets': [ 7, 8 ] }""); b.append("", {'sType': 'title-numeric', 'aTargets': [ 4 ]}""); b.append(""]}""); return b.toString(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java index 67c73b812737a..c0e68349e4ab5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java @@ -61,6 +61,7 @@ public void setup() { route(pajoin(""/app"", APPLICATION_ID), RmController.class, ""app""); route(""/scheduler"", RmController.class, ""scheduler""); route(pajoin(""/queue"", QUEUE_NAME), RmController.class, ""queue""); + route(""/nodelabels"", RmController.class, ""nodelabels""); } @Override diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java index f186bf498b0f0..972432b9882d1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java @@ -28,7 +28,6 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.util.StringHelper; import org.apache.hadoop.yarn.webapp.Controller; -import org.apache.hadoop.yarn.webapp.WebAppException; import org.apache.hadoop.yarn.webapp.YarnWebParams; import com.google.inject.Inject; @@ -93,4 +92,9 @@ public void queue() { public void submit() { setTitle(""Application Submission Not Allowed""); } + + public void nodelabels() { + setTitle(""Node Labels""); + render(NodeLabelsPage.class); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java index 278c151ff668b..2d863d1af5c09 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java @@ -30,11 +30,13 @@ import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** @@ -53,7 +55,12 @@ public static List newNodes(int racks, int nodesPerRack, // One unhealthy node per rack. list.add(nodeInfo(i, perNode, NodeState.UNHEALTHY)); } - list.add(newNodeInfo(i, perNode)); + if (j == 0) { + // One node with label + list.add(nodeInfo(i, perNode, NodeState.RUNNING, ImmutableSet.of(""x""))); + } else { + list.add(newNodeInfo(i, perNode)); + } } } return list; @@ -100,10 +107,12 @@ private static class MockRMNodeImpl implements RMNode { private String healthReport; private long lastHealthReportTime; private NodeState state; + private Set labels; public MockRMNodeImpl(NodeId nodeId, String nodeAddr, String httpAddress, Resource perNode, String rackName, String healthReport, - long lastHealthReportTime, int cmdPort, String hostName, NodeState state) { + long lastHealthReportTime, int cmdPort, String hostName, NodeState state, + Set labels) { this.nodeId = nodeId; this.nodeAddr = nodeAddr; this.httpAddress = httpAddress; @@ -114,6 +123,7 @@ public MockRMNodeImpl(NodeId nodeId, String nodeAddr, String httpAddress, this.cmdPort = cmdPort; this.hostName = hostName; this.state = state; + this.labels = labels; } @Override @@ -207,16 +217,33 @@ public long getLastHealthReportTime() { @Override public Set getNodeLabels() { - return RMNodeLabelsManager.EMPTY_STRING_SET; + if (labels != null) { + return labels; + } + return CommonNodeLabelsManager.EMPTY_STRING_SET; } }; - private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr) { - return buildRMNode(rack, perNode, state, httpAddr, NODE_ID++, null, 123); + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr) { + return buildRMNode(rack, perNode, state, httpAddr, null); } - + + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr, Set labels) { + return buildRMNode(rack, perNode, state, httpAddr, NODE_ID++, null, 123, + labels); + } + private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr, int hostnum, String hostName, int port) { + return buildRMNode(rack, perNode, state, httpAddr, hostnum, hostName, port, + null); + } + + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr, int hostnum, String hostName, int port, + Set labels) { final String rackName = ""rack""+ rack; final int nid = hostnum; final String nodeAddr = hostName + "":"" + nid; @@ -228,13 +255,18 @@ private static RMNode buildRMNode(int rack, final Resource perNode, final String httpAddress = httpAddr; String healthReport = (state == NodeState.UNHEALTHY) ? null : ""HealthyMe""; return new MockRMNodeImpl(nodeID, nodeAddr, httpAddress, perNode, - rackName, healthReport, 0, nid, hostName, state); + rackName, healthReport, 0, nid, hostName, state, labels); } public static RMNode nodeInfo(int rack, final Resource perNode, NodeState state) { return buildRMNode(rack, perNode, state, ""N/A""); } + + public static RMNode nodeInfo(int rack, final Resource perNode, + NodeState state, Set labels) { + return buildRMNode(rack, perNode, state, ""N/A"", labels); + } public static RMNode newNodeInfo(int rack, final Resource perNode) { return buildRMNode(rack, perNode, NodeState.RUNNING, ""localhost:0""); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java index 842eaecad3202..e21fcf9d6ab5d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java @@ -839,7 +839,7 @@ public void testRecoverSchedulerAppAndAttemptSynchronously() throws Exception { // Test if RM on recovery receives the container release request from AM // before it receives the container status reported by NM for recovery. this // container should not be recovered. - @Test (timeout = 30000) + @Test (timeout = 50000) public void testReleasedContainerNotRecovered() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java index ed675f3736324..e4cdc71c781fb 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -27,6 +28,7 @@ import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.nodelabels.NodeLabel; import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; @@ -428,4 +430,35 @@ public void testRemoveLabelsFromNode() throws Exception { Assert.fail(""IOException from removeLabelsFromNode "" + e); } } + + private void checkNodeLabelInfo(List infos, String labelName, int activeNMs, int memory) { + for (NodeLabel info : infos) { + if (info.getLabelName().equals(labelName)) { + Assert.assertEquals(activeNMs, info.getNumActiveNMs()); + Assert.assertEquals(memory, info.getResource().getMemory()); + return; + } + } + Assert.fail(""Failed to find info has label="" + labelName); + } + + @Test(timeout = 5000) + public void testPullRMNodeLabelsInfo() throws IOException { + mgr.addToCluserNodeLabels(toSet(""x"", ""y"", ""z"")); + mgr.activateNode(NodeId.newInstance(""n1"", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance(""n2"", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance(""n3"", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance(""n4"", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance(""n5"", 1), Resource.newInstance(10, 0)); + mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId(""n1""), toSet(""x""), + toNodeId(""n2""), toSet(""x""), toNodeId(""n3""), toSet(""y""))); + + // x, y, z and """" + List infos = mgr.pullRMNodeLabelsInfo(); + Assert.assertEquals(4, infos.size()); + checkNodeLabelInfo(infos, RMNodeLabelsManager.NO_LABEL, 2, 20); + checkNodeLabelInfo(infos, ""x"", 2, 20); + checkNodeLabelInfo(infos, ""y"", 1, 10); + checkNodeLabelInfo(infos, ""z"", 0, 0); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java index bb38079ccea50..62713cfc7c183 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java @@ -106,4 +106,49 @@ public void testNodesBlockRenderForLostNodes() { * numberOfActualTableHeaders + numberOfThInMetricsTable)).print( "" + src=""http://www.restlet.org/images/logo200"" />

@@ -28,62 +28,62 @@

Timeline

    -
  • 2007 Q1 -
      -
    • [Optional] 1.0 RC2 release
    • -
    • 1.0 release. List - of issues must be resolved (documentation, etc.).
    • -
    -
  • -
  • 2007 Q2 - -
  • 2007 Q3 - -
  • -
  • 2008 Q1 -
      -
    • [JSR] Submission of a proposal to standardize a - Restlet API 2.0 to the JCP -
    • [JSR] If submission approved, formation of expert - group
    • -
    • [JSR] Write first draft
    • -
    -
  • -
  • 2008 Q2 -
      -
    • [JSR] Updates to the draft (optional)
    • -
    • [JSR] Public Review
    • -
    -
  • -
  • 2008 Q3 -
      -
    • [JSR] Drafts updates (optional)
    • -
    • [JSR] Draft Specification approval ballot by EC
    • -
    -
  • -
  • 2008 Q4 -
      -
    • [JSR] Proposed final draft
    • -
    • [JSR] Completion of RI and TCK
    • -
    -
  • -
  • 2009 Q1 -
      -
    • [JSR] Final draft Submission
    • -
    • [JSR] Final approval ballot by EC
    • -
    • [JSR] Final release of Restlet API 2.0
    • -
    • 2.0 release
    • -
    -
  • +
  • 2007 Q1 +
      +
    • [Optional] 1.0 RC3 release
    • +
    • 1.0 release. List + of issues must be resolved (documentation, etc.).
    • +
    +
  • +
  • 2007 Q2 + +
  • 2007 Q3 + +
  • +
  • 2008 Q1 +
      +
    • [JSR] Submission of a proposal to standardize a + Restlet API 2.0 to the JCP +
    • [JSR] If submission approved, formation of expert + group
    • +
    • [JSR] Write first draft
    • +
    +
  • +
  • 2008 Q2 +
      +
    • [JSR] Updates to the draft (optional)
    • +
    • [JSR] Public Review
    • +
    +
  • +
  • 2008 Q3 +
      +
    • [JSR] Drafts updates (optional)
    • +
    • [JSR] Draft Specification approval ballot by EC
    • +
    +
  • +
  • 2008 Q4 +
      +
    • [JSR] Proposed final draft
    • +
    • [JSR] Completion of RI and TCK
    • +
    +
  • +
  • 2009 Q1 +
      +
    • [JSR] Final draft Submission
    • +
    • [JSR] Final approval ballot by EC
    • +
    • [JSR] Final release of Restlet API 2.0
    • +
    • 2.0 release
    • +
    +

@@ -92,15 +92,15 @@

Conclusion

Due to the open source nature of the Restlet project, the above timeline is subject to change. However, we will do our best to respect it and update it as frequently as possible. Please, feel free to contact us for questions and + href=""mailto:contact@noelios.com"">contact us for questions and comments.


- Last modified on 2006-12-26. Copyright © 2005-2007 + Last modified on 2007-01-09. Copyright © 2005-2007 Jérôme Louvel. Restlet is a registered trademark of Noelios Consulting. + href=""http://www.noelios.com"">Noelios Consulting. diff --git a/build/www/tutorial.html b/build/www/tutorial.html index 2a7b31c6cc..2e64110fbd 100644 --- a/build/www/tutorial.html +++ b/build/www/tutorial.html @@ -538,7 +538,7 @@

Notes


- Last modified on 2006-12-26. Copyright © 2005-2007 + Last modified on 2007-01-09. Copyright © 2005-2007 Jérôme Louvel. Restlet is a registered trademark of Noelios Consulting. diff --git a/build/www/tutorial.pdf b/build/www/tutorial.pdf index 7b6e58a3e1..f788e61873 100644 Binary files a/build/www/tutorial.pdf and b/build/www/tutorial.pdf differ diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java b/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java index 77b74d0e5d..0a33f8169b 100644 --- a/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java +++ b/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java @@ -651,23 +651,6 @@ public void parse(Logger logger, Form form, Representation webForm) { } } - /** - * Parses an URL encoded query string into a given form. - * - * @param logger - * The logger to use. - * @param form - * The target form. - * @param queryString - * Query string. - * @deprecated Use the parse(Logger,String,CharacterSet) method to specify - * the encoding. This method uses the UTF-8 character set. - */ - @Deprecated - public void parse(Logger logger, Form form, String queryString) { - parse(logger, form, queryString, CharacterSet.UTF_8); - } - /** * Parses an URL encoded query string into a given form. * diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java index c69385d022..caf2f93070 100644 --- a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java +++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java @@ -69,24 +69,6 @@ public FormReader(Logger logger, Representation representation) } } - /** - * Constructor. - * - * @param logger - * The logger. - * @param query - * The query string. - * @deprecated Use the FormReader(Logger,String,CharacterSet) constructor to - * specify the encoding. - */ - @Deprecated - public FormReader(Logger logger, String query) throws IOException { - this.logger = logger; - this.stream = new ByteArrayInputStream(query.getBytes()); - this.characterSet = CharacterSet.UTF_8; - - } - /** * Constructor. * diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java index 78d4d3df88..4cf06b5261 100644 --- a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java +++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java @@ -35,24 +35,6 @@ * @author Jerome Louvel (contact@noelios.com) */ public class FormUtils { - /** - * Parses a query into a given form. - * - * @param logger - * The logger. - * @param form - * The target form. - * @param query - * Query string. - * @deprecated Use the parseQuery(Logger,Form, String,CharacterSet) method - * to specify the encoding. This method uses the UTF-8 character - * set. - */ - @Deprecated - public static void parseQuery(Logger logger, Form form, String query) { - parseQuery(logger, form, query, CharacterSet.UTF_8); - } - /** * Parses a query into a given form. * @@ -112,27 +94,6 @@ public static void parsePost(Logger logger, Form form, Representation post) { } } - /** - * Reads the parameters whose name is a key in the given map.
If a - * matching parameter is found, its value is put in the map.
If - * multiple values are found, a list is created and set in the map. - * - * @param logger - * The logger. - * @param query - * The query string. - * @param parameters - * The parameters map controlling the reading. - * @deprecated Use the getParameters(Logger,String,Map,CharacterSet) method to specify the encoding. This - * method uses the UTF-8 character set. - */ - @Deprecated - public static void getParameters(Logger logger, String query, - Map parameters) throws IOException { - getParameters(logger, query, parameters, CharacterSet.UTF_8); - } - /** * Reads the parameters whose name is a key in the given map.
If a * matching parameter is found, its value is put in the map.
If @@ -170,27 +131,6 @@ public static void getParameters(Logger logger, Representation post, new FormReader(logger, post).readParameters(parameters); } - /** - * Reads the first parameter with the given name. - * - * @param logger - * The logger. - * @param query - * The query string. - * @param name - * The parameter name to match. - * @return The parameter. - * @throws IOException - * @deprecated Use the getFirstParameter(Logger,String,String,CharacterSet) - * method to specify the encoding. This method uses the UTF-8 - * character set. - */ - @Deprecated - public static Parameter getFirstParameter(Logger logger, String query, - String name) throws IOException { - return getFirstParameter(logger, query, name, CharacterSet.UTF_8); - } - /** * Reads the first parameter with the given name. * @@ -228,27 +168,6 @@ public static Parameter getFirstParameter(Logger logger, return new FormReader(logger, post).readFirstParameter(name); } - /** - * Reads the parameters with the given name.
If multiple values are - * found, a list is returned created. - * - * @param logger - * The logger. - * @param query - * The query string. - * @param name - * The parameter name to match. - * @return The parameter value or list of values. - * @deprecated Use the getParameter(Logger,String,String,CharacterSet) - * method to specify the encoding. This method uses the UTF-8 - * character set. - */ - @Deprecated - public static Object getParameter(Logger logger, String query, String name) - throws IOException { - return getParameter(logger, query, name, CharacterSet.UTF_8); - } - /** * Reads the parameters with the given name.
If multiple values are * found, a list is returned created. @@ -314,23 +233,4 @@ public static Parameter create(CharSequence name, CharSequence value, return result; } - - /** - * Creates a parameter. - * - * @param name - * The parameter name buffer. - * @param value - * The parameter value buffer (can be null). - * @return The created parameter. - * @throws IOException - * @deprecated Use the create(CharSequence,CharSequence,CharacterSet) method - * instead. This method uses the UTF-8 character set. - */ - @Deprecated - public static Parameter create(CharSequence name, CharSequence value) - throws IOException { - return create(name, value, CharacterSet.UTF_8); - } - } diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java index 60a75b3718..8cda5c5875 100644 --- a/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java +++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java @@ -111,25 +111,6 @@ public static Appendable appendQuote(CharSequence source, return destination; } - /** - * Appends a source string as an URI encoded string. - * - * @param source - * The source string to format. - * @param destination - * The appendable destination. - * @throws IOException - * @deprecated Use the - * appendUriEncoded(CharSequence,Appendable,CharacterSet) method - * to specify the encoding. This method uses the UTF-8 character - * set. - */ - @Deprecated - public static Appendable appendUriEncoded(CharSequence source, - Appendable destination) throws IOException { - return appendUriEncoded(source, destination, CharacterSet.UTF_8); - } - /** * Appends a source string as an URI encoded string. * diff --git a/module/org.restlet/src/org/restlet/data/Form.java b/module/org.restlet/src/org/restlet/data/Form.java index e16175cb07..306efd5bc3 100644 --- a/module/org.restlet/src/org/restlet/data/Form.java +++ b/module/org.restlet/src/org/restlet/data/Form.java @@ -73,23 +73,6 @@ public Form(Logger logger, Representation representation) { Factory.getInstance().parse(logger, this, representation); } - /** - * Constructor. - * - * @param logger - * The logger to use. - * @param queryString - * The Web form parameters as a string. - * @throws IOException - * @deprecated Use the Form(Logger,String,CharacterSet) constructor to - * specify the encoding. This method uses the UTF-8 character - * set. - */ - @Deprecated - public Form(Logger logger, String queryString) { - Factory.getInstance().parse(logger, this, queryString); - } - /** * Constructor. * @@ -125,7 +108,8 @@ public Form(Representation webForm) { * @throws IOException */ public Form(String queryString) { - this(Logger.getLogger(Form.class.getCanonicalName()), queryString); + this(Logger.getLogger(Form.class.getCanonicalName()), queryString, + CharacterSet.UTF_8); } /** @@ -204,19 +188,6 @@ public Representation getWebRepresentation(CharacterSet characterSet) { MediaType.APPLICATION_WWW_FORM, null, characterSet); } - /** - * URL encodes the form. - * - * @return The encoded form. - * @throws IOException - * @deprecated Use the urlEncode(CharacterSet) method to specify the - * encoding. This method uses the UTF-8 character set. - */ - @Deprecated - public String urlEncode() throws IOException { - return encode(CharacterSet.UTF_8); - } - /** * Encodes the form using the standard URI encoding mechanism and the UTF-8 * character set. diff --git a/module/org.restlet/src/org/restlet/data/Parameter.java b/module/org.restlet/src/org/restlet/data/Parameter.java index dd812ff6df..ebdbd48d98 100644 --- a/module/org.restlet/src/org/restlet/data/Parameter.java +++ b/module/org.restlet/src/org/restlet/data/Parameter.java @@ -145,33 +145,6 @@ public String toString() { return getName() + "": "" + getValue(); } - /** - * Encodes the parameter. - * - * @return The encoded string. - * @throws IOException - * @deprecated Use the urlEncode(CharacterSet) method to specify the - * encoding. This method uses the UTF-8 character set. - */ - @Deprecated - public String urlEncode() throws IOException { - return encode(CharacterSet.UTF_8); - } - - /** - * Encodes the parameter and append the result to the given buffer. - * - * @param buffer - * The buffer to append. - * @throws IOException - * @deprecated Use the urlEncode(Appendable,CharacterSet) method to specify - * the encoding. This method uses the UTF-8 character set. - */ - @Deprecated - public void urlEncode(Appendable buffer) throws IOException { - encode(buffer, CharacterSet.UTF_8); - } - /** * Encodes the parameter using the standard URI encoding mechanism. * diff --git a/module/org.restlet/src/org/restlet/resource/DomRepresentation.java b/module/org.restlet/src/org/restlet/resource/DomRepresentation.java index ba340584a8..d6fa094950 100644 --- a/module/org.restlet/src/org/restlet/resource/DomRepresentation.java +++ b/module/org.restlet/src/org/restlet/resource/DomRepresentation.java @@ -94,22 +94,6 @@ public DomRepresentation(MediaType mediaType, Document xmlDocument) { this.dom = xmlDocument; } - /** - * Constructor. - * - * @param mediaType - * The representation's media type. - * @param xmlRepresentation - * A source XML representation to parse. - * @deprecated Use the other constructor instead. - */ - @Deprecated - public DomRepresentation(MediaType mediaType, - Representation xmlRepresentation) { - super(mediaType); - this.xmlRepresentation = xmlRepresentation; - } - /** * Constructor. * diff --git a/module/org.restlet/src/org/restlet/resource/Representation.java b/module/org.restlet/src/org/restlet/resource/Representation.java index a3fb1de0b3..f96dfb24be 100644 --- a/module/org.restlet/src/org/restlet/resource/Representation.java +++ b/module/org.restlet/src/org/restlet/resource/Representation.java @@ -120,19 +120,6 @@ public String getText() throws IOException { return result; } - /** - * Converts the representation to a string value. Be careful when using this - * method as the conversion of large content to a string fully stored in - * memory can result in OutOfMemoryErrors being thrown. - * - * @return The representation as a string value. - * @deprecated Use getText instead. - */ - @Deprecated - public String getValue() throws IOException { - return getText(); - } - /** * Indicates if some fresh content is available, without having to actually * call one of the content manipulation method like getStream() that would diff --git a/module/org.restlet/src/org/restlet/resource/Resource.java b/module/org.restlet/src/org/restlet/resource/Resource.java index 0dd7b041dc..268c5d5b6a 100644 --- a/module/org.restlet/src/org/restlet/resource/Resource.java +++ b/module/org.restlet/src/org/restlet/resource/Resource.java @@ -23,7 +23,6 @@ import java.util.logging.Logger; import org.restlet.data.Reference; -import org.restlet.data.ReferenceList; import org.restlet.data.Status; /** @@ -58,9 +57,6 @@ public class Resource { /** The identifier. */ private Reference identifier; - /** The modifiable list of identifiers. */ - private ReferenceList identifiers; - /** The modifiable list of variants. */ private List variants; @@ -80,7 +76,6 @@ public Resource() { public Resource(Logger logger) { this.logger = logger; this.identifier = null; - this.identifiers = null; this.variants = null; } @@ -142,21 +137,6 @@ public Reference getIdentifier() { return this.identifier; } - /** - * Returns the list of all the identifiers for the resource. The list is - * composed of the official identifier followed by all the alias - * identifiers. - * - * @return The list of all the identifiers for the resource. - * @deprecated No obvious usage. More the role of Handler to map URIs. - */ - @Deprecated - public ReferenceList getIdentifiers() { - if (this.identifiers == null) - this.identifiers = new ReferenceList(); - return this.identifiers; - } - /** * Returns the logger to use. * @@ -252,18 +232,6 @@ public void setIdentifier(String identifierUri) { setIdentifier(new Reference(identifierUri)); } - /** - * Sets a new list of all the identifiers for the resource. - * - * @param identifiers - * The new list of identifiers. - * @deprecated No obvious usage. More the role of Handler to map URIs. - */ - @Deprecated - public void setIdentifiers(ReferenceList identifiers) { - this.identifiers = identifiers; - } - /** * Sets the logger to use. * diff --git a/module/org.restlet/src/org/restlet/resource/StringRepresentation.java b/module/org.restlet/src/org/restlet/resource/StringRepresentation.java index 1d55c4e36d..d92e48f2e9 100644 --- a/module/org.restlet/src/org/restlet/resource/StringRepresentation.java +++ b/module/org.restlet/src/org/restlet/resource/StringRepresentation.java @@ -146,18 +146,6 @@ public String getText() { return (this.text == null) ? null : this.text.toString(); } - /** - * Sets the string value. - * - * @param text - * The string value. - * @deprecated Use setText instead. - */ - @Deprecated - public void setValue(String text) { - setText(text); - } - /** * Sets the string value. * diff --git a/module/org.restlet/src/org/restlet/util/Factory.java b/module/org.restlet/src/org/restlet/util/Factory.java index b416d27068..ce4b23ce9a 100644 --- a/module/org.restlet/src/org/restlet/util/Factory.java +++ b/module/org.restlet/src/org/restlet/util/Factory.java @@ -51,7 +51,7 @@ public abstract class Factory { .getCanonicalName()); /** Common version info. */ - public static final String MINOR_NUMBER = ""2""; + public static final String MINOR_NUMBER = ""3""; public static final String VERSION_LONG = ""1.0 RC"" + MINOR_NUMBER; @@ -272,21 +272,6 @@ public abstract Variant getPreferredVariant(ClientInfo client, public abstract void parse(Logger logger, Form form, Representation representation); - /** - * Parses an URL encoded query string into a given form. - * - * @param logger - * The logger to use. - * @param form - * The target form. - * @param queryString - * Query string. - * @deprecated Use the parse(Logger,String,CharacterSet) method to - * specify the encoding. - */ - @Deprecated - public abstract void parse(Logger logger, Form form, String queryString); - /** * Parses an URL encoded query string into a given form. * diff --git a/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java b/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java index 2e5ac4e842..78b6219ece 100644 --- a/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java +++ b/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java @@ -32,7 +32,6 @@ import org.restlet.data.Language; import org.restlet.data.MediaType; import org.restlet.data.Reference; -import org.restlet.data.ReferenceList; import org.restlet.data.Tag; import org.restlet.resource.Representation; import org.restlet.resource.Result; @@ -163,19 +162,6 @@ public Reference getIdentifier() { return getWrappedRepresentation().getIdentifier(); } - /** - * Returns the list of all the identifiers for the resource. The list is - * composed of the official identifier followed by all the alias - * identifiers. - * - * @return The list of all the identifiers for the resource. - * @deprecated No obvious usage. More the role of Handler to map URIs. - */ - @Deprecated - public ReferenceList getIdentifiers() { - return getWrappedRepresentation().getIdentifiers(); - } - /** * Returns the language or null if not applicable. * @@ -258,19 +244,6 @@ public String getText() throws IOException { return getWrappedRepresentation().getText(); } - /** - * Converts the representation to a string value. Be careful when using this - * method as the conversion of large content to a string fully stored in - * memory can result in OutOfMemoryErrors being thrown. - * - * @return The representation as a string value. - * @deprecated Use getText instead - */ - @Deprecated - public String getValue() throws IOException { - return getWrappedRepresentation().getValue(); - } - /** * Returns a full representation for a given variant previously returned via * the getVariants() method. The default implementation directly returns the @@ -424,18 +397,6 @@ public void setIdentifier(String identifierUri) { getWrappedRepresentation().setIdentifier(identifierUri); } - /** - * Sets a new list of all the identifiers for the resource. - * - * @param identifiers - * The new list of identifiers. - * @deprecated No obvious usage. More the role of Handler to map URIs. - */ - @Deprecated - public void setIdentifiers(ReferenceList identifiers) { - getWrappedRepresentation().setIdentifiers(identifiers); - } - /** * Sets the language or null if not applicable. * diff --git a/module/org.restlet/src/org/restlet/util/WrapperResource.java b/module/org.restlet/src/org/restlet/util/WrapperResource.java index a94ef728d7..fd277788c3 100644 --- a/module/org.restlet/src/org/restlet/util/WrapperResource.java +++ b/module/org.restlet/src/org/restlet/util/WrapperResource.java @@ -22,7 +22,6 @@ import java.util.logging.Logger; import org.restlet.data.Reference; -import org.restlet.data.ReferenceList; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.Result; @@ -108,20 +107,6 @@ public Reference getIdentifier() { return getWrappedResource().getIdentifier(); } - /** - * Returns the list of all the identifiers for the resource. The list is - * composed of the official identifier followed by all the alias - * identifiers. - * - * @return The list of all the identifiers for the resource. - * @deprecated The URIs should only be managed by the application routers - * and handlers. - */ - @Deprecated - public ReferenceList getIdentifiers() { - return getWrappedResource().getIdentifiers(); - } - /** * Returns the logger to use. * @@ -217,19 +202,6 @@ public void setIdentifier(String identifierUri) { getWrappedResource().setIdentifier(identifierUri); } - /** - * Sets a new list of all the identifiers for the resource. - * - * @param identifiers - * The new list of identifiers. - * @deprecated The URIs should only be managed by the application routers - * and handlers. - */ - @Deprecated - public void setIdentifiers(ReferenceList identifiers) { - getWrappedResource().setIdentifiers(identifiers); - } - /** * Sets the logger to use. *" 9869e7875cf052f6c54e4ffedf9fa70f3803e3da,ReactiveX-RxJava,Removed synchronized block as per RxJava guidelines- (6.7).--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/operators/OperationSwitch.java b/rxjava-core/src/main/java/rx/operators/OperationSwitch.java index 7138fd00d7..44c88a0dcb 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationSwitch.java +++ b/rxjava-core/src/main/java/rx/operators/OperationSwitch.java @@ -93,29 +93,27 @@ public void onError(Exception e) { @Override public void onNext(Observable args) { - synchronized (subscription) { - Subscription previousSubscription = subscription.get(); - if (previousSubscription != null) { - previousSubscription.unsubscribe(); - } - - subscription.set(args.subscribe(new Observer() { - @Override - public void onCompleted() { - // Do nothing. - } - - @Override - public void onError(Exception e) { - // Do nothing. - } - - @Override - public void onNext(T args) { - observer.onNext(args); - } - })); + Subscription previousSubscription = subscription.get(); + if (previousSubscription != null) { + previousSubscription.unsubscribe(); } + + subscription.set(args.subscribe(new Observer() { + @Override + public void onCompleted() { + // Do nothing. + } + + @Override + public void onError(Exception e) { + // Do nothing. + } + + @Override + public void onNext(T args) { + observer.onNext(args); + } + })); } }" 546dd6e5458d5fa4e36c2d7fc1aaa1a12f4f0973,ReactiveX-RxJava,non-deterministic- testUserSubscriberUsingRequestAsync--fix non-deterministic failures of BackpressureTests.testUserSubscriberUsingRequestAsync--I was able to replicate the occasional failure by putting it in a tight loop. With these changes it no longer fails.-,c,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/test/java/rx/BackpressureTests.java b/rxjava-core/src/test/java/rx/BackpressureTests.java index bf357675eb..babffd3f52 100644 --- a/rxjava-core/src/test/java/rx/BackpressureTests.java +++ b/rxjava-core/src/test/java/rx/BackpressureTests.java @@ -344,7 +344,7 @@ public void onNext(Integer t) { assertEquals(20, batches.get()); } - @Test(timeout = 2000) + @Test public void testUserSubscriberUsingRequestAsync() throws InterruptedException { AtomicInteger c = new AtomicInteger(); final AtomicInteger totalReceived = new AtomicInteger(); @@ -372,14 +372,20 @@ public void onError(Throwable e) { public void onNext(Integer t) { int total = totalReceived.incrementAndGet(); received.incrementAndGet(); + boolean done = false; if (total >= 2000) { + done = true; unsubscribe(); - latch.countDown(); } if (received.get() == 100) { batches.incrementAndGet(); - request(100); received.set(0); + if (!done) { + request(100); + } + } + if (done) { + latch.countDown(); } } @@ -470,8 +476,8 @@ public void request(long n) { long _c = requested.getAndAdd(n); if (_c == 0) { while (!s.isUnsubscribed()) { - s.onNext(i++); counter.incrementAndGet(); + s.onNext(i++); if (requested.decrementAndGet() == 0) { // we're done emitting the number requested so return return;" 2d2e9e06218153e725310e1b24cefb870cda12cc,elasticsearch,fixed issue from merge--,c,https://github.com/elastic/elasticsearch,"diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java index f7cbfa7fcb894..23b0513545cbf 100644 --- a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java +++ b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/DiversifiedSamplerIT.java @@ -215,7 +215,7 @@ public void testPartiallyUnmappedDiversifyField() throws Exception { .execute().actionGet(); assertSearchResponse(response); Sampler sample = response.getAggregations().get(""sample""); - assertThat(sample.getDocCount(), greaterThan(0l)); + assertThat(sample.getDocCount(), greaterThan(0L)); Terms authors = sample.getAggregations().get(""authors""); assertThat(authors.getBuckets().size(), greaterThan(0)); } @@ -230,7 +230,7 @@ public void testWhollyUnmappedDiversifyField() throws Exception { .setQuery(new TermQueryBuilder(""genre"", ""fantasy"")).setFrom(0).setSize(60).addAggregation(sampleAgg).execute().actionGet(); assertSearchResponse(response); Sampler sample = response.getAggregations().get(""sample""); - assertThat(sample.getDocCount(), equalTo(0l)); + assertThat(sample.getDocCount(), equalTo(0L)); Terms authors = sample.getAggregations().get(""authors""); assertNull(authors); }" 45c6da487d959e7731e3de8d1a86c386fc5172cb,restlet-framework-java,"Add comments describing methods (from HTTP, Webdav- RFC).--",p,https://github.com/restlet/restlet-framework-java,"diff --git a/module/org.restlet/src/org/restlet/data/Method.java b/module/org.restlet/src/org/restlet/data/Method.java index a67ef703a9..a970d493d2 100644 --- a/module/org.restlet/src/org/restlet/data/Method.java +++ b/module/org.restlet/src/org/restlet/data/Method.java @@ -28,73 +28,195 @@ public final class Method extends Metadata { private static final String BASE_WEBDAV = ""http://www.webdav.org/specs/rfc2518.html""; + /** + * Used with a proxy that can dynamically switch to being a tunnel. + * + * @see HTTP + * RFC - 9.9 CONNECT + */ public static final Method CONNECT = new Method(""CONNECT"", ""Used with a proxy that can dynamically switch to being a tunnel"", BASE_HTTP + ""#sec9.9""); + /** + * Creates a duplicate of the source resource, identified by the + * Request-URI, in the destination resource, identified by the URI in the + * Destination header. + * + * @see WEBDAV + * RFC - 8.8 COPY Method + */ public static final Method COPY = new Method( ""COPY"", ""Creates a duplicate of the source resource, identified by the Request-URI, in the destination resource, identified by the URI in the Destination header"", BASE_WEBDAV + ""#METHOD_COPY""); + /** + * Requests that the origin server deletes the resource identified by the + * request URI. + * + * @see HTTP + * RFC - 9.7 DELETE + */ public static final Method DELETE = new Method( ""DELETE"", ""Requests that the origin server deletes the resource identified by the request URI"", BASE_HTTP + ""#sec9.7""); + /** + * Retrieves whatever information (in the form of an entity) that is + * identified by the request URI. + * + * @see HTTP + * RFC - 9.3 GET + */ public static final Method GET = new Method( ""GET"", ""Retrieves whatever information (in the form of an entity) that is identified by the request URI"", BASE_HTTP + ""#sec9.3""); + /** + * Identical to GET except that the server must not return a message body in + * the response but only the message header. + * + * @see HTTP + * RFC - 9.4 GET + */ public static final Method HEAD = new Method( ""HEAD"", ""Identical to GET except that the server must not return a message body in the response"", BASE_HTTP + ""#sec9.4""); + /** + * Used to take out a lock of any access type on the resource identified by + * the request URI. + * + * @see WEBDAV + * RFC - 8.10 LOCK Method + */ public static final Method LOCK = new Method(""LOCK"", ""Used to take out a lock of any access type (WebDAV)"", BASE_WEBDAV + ""#METHOD_LOCK""); + /** + * MKCOL creates a new collection resource at the location specified by the + * Request URI. + * + * @see WEBDAV + * RFC - 8.3 MKCOL Method + */ public static final Method MKCOL = new Method(""MKCOL"", ""Used to create a new collection (WebDAV)"", BASE_WEBDAV + ""#METHOD_MKCOL""); + /** + * Logical equivalent of a copy, followed by consistency maintenance + * processing, followed by a delete of the source where all three actions + * are performed atomically. + * + * @see WEBDAV + * RFC - 8.3 MKCOL Method + */ public static final Method MOVE = new Method( ""MOVE"", ""Logical equivalent of a copy, followed by consistency maintenance processing, followed by a delete of the source (WebDAV)"", BASE_WEBDAV + ""#METHOD_MOVE""); + /** + * Requests for information about the communication options available on the + * request/response chain identified by the URI. + * + * @see HTTP + * RFC - 9.2 OPTIONS + */ public static final Method OPTIONS = new Method( ""OPTIONS"", ""Requests for information about the communication options available on the request/response chain identified by the URI"", BASE_HTTP + ""#sec9.2""); + /** + * Requests that the origin server accepts the entity enclosed in the + * request as a new subordinate of the resource identified by the request + * URI. + * + * @see HTTP + * RFC - 9.5 POST + */ public static final Method POST = new Method( ""POST"", ""Requests that the origin server accepts the entity enclosed in the request as a new subordinate of the resource identified by the request URI"", BASE_HTTP + ""#sec9.5""); + /** + * Retrieves properties defined on the resource identified by the request + * URI. + * + * @see WEBDAV + * RFC - 8.1 PROPFIND + */ public static final Method PROPFIND = new Method( ""PROPFIND"", ""Retrieves properties defined on the resource identified by the request URI"", BASE_WEBDAV + ""#METHOD_PROPFIND""); + /** + * Processes instructions specified in the request body to set and/or remove + * properties defined on the resource identified by the request URI. + * + * @see WEBDAV + * RFC - 8.2 PROPPATCH + */ public static final Method PROPPATCH = new Method( ""PROPPATCH"", ""Processes instructions specified in the request body to set and/or remove properties defined on the resource identified by the request URI"", BASE_WEBDAV + ""#METHOD_PROPPATCH""); + /** + * Requests that the enclosed entity be stored under the supplied request + * URI. + * + * @see HTTP + * RFC - 9.6 PUT + */ public static final Method PUT = new Method( ""PUT"", ""Requests that the enclosed entity be stored under the supplied request URI"", BASE_HTTP + ""#sec9.6""); + /** + * Used to invoke a remote, application-layer loop-back of the request + * message. + * + * @see HTTP + * RFC - 9.8 TRACE + */ public static final Method TRACE = new Method( ""TRACE"", ""Used to invoke a remote, application-layer loop-back of the request message"", BASE_HTTP + ""#sec9.8""); + /** + * Removes the lock identified by the lock token from the request URI, and + * all other resources included in the lock. + * + * @see WEBDAV + * RFC - 8.11 UNLOCK Method + */ public static final Method UNLOCK = new Method( ""UNLOCK"", ""Removes the lock identified by the lock token from the request URI, and all other resources included in the lock""," b09e981f1e236c08194c5871214d5431c98eb260,drools,[BZ-1007977] when returning a cached KieModule from- the KieRepository referring to a snapshot release check if there is a newer- release on the maven repository--,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieScanner.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieScanner.java index 0b3a11e27eb..3194f75b493 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieScanner.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieScanner.java @@ -14,4 +14,6 @@ public interface InternalKieScanner extends KieScanner { KieModule loadArtifact(ReleaseId releaseId); KieModule loadArtifact(ReleaseId releaseId, InputStream pomXML); + + String getArtifactVersion(ReleaseId releaseId); } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java index 5c335a60843..708d0d1adf6 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieRepositoryImpl.java @@ -46,14 +46,19 @@ public class KieRepositoryImpl public static final KieRepository INSTANCE = new KieRepositoryImpl(); - private final KieModuleRepo kieModuleRepo = new KieModuleRepo(); + private final KieModuleRepo kieModuleRepo; + + private InternalKieScanner internalKieScanner; + + public KieRepositoryImpl() { + internalKieScanner = getInternalKieScanner(); + kieModuleRepo = new KieModuleRepo(internalKieScanner); + } private final AtomicReference defaultGAV = new AtomicReference(new ReleaseIdImpl(DEFAULT_GROUP, DEFAULT_ARTIFACT, DEFAULT_VERSION)); - private InternalKieScanner internalKieScanner; - public void setDefaultGAV(ReleaseId releaseId) { this.defaultGAV.set(releaseId); } @@ -122,10 +127,6 @@ private static class DummyKieScanner implements InternalKieScanner { - public KieModule loadArtifact(ReleaseId releaseId) { - return null; - } - public void start(long pollingInterval) { } @@ -138,9 +139,17 @@ public void scanNow() { public void setKieContainer(KieContainer kieContainer) { } + public KieModule loadArtifact(ReleaseId releaseId) { + return null; + } + public KieModule loadArtifact(ReleaseId releaseId, InputStream pomXML) { return null; } + + public String getArtifactVersion(ReleaseId releaseId) { + return null; + } } public KieModule addKieModule(Resource resource, Resource... dependencies) { @@ -195,9 +204,14 @@ public KieModule getKieModule(Resource resource) { private static class KieModuleRepo { + private final InternalKieScanner kieScanner; private final Map> kieModules = new HashMap>(); private final Map oldKieModules = new HashMap(); + private KieModuleRepo(InternalKieScanner kieScanner) { + this.kieScanner = kieScanner; + } + void store(KieModule kieModule) { ReleaseId releaseId = kieModule.getReleaseId(); String ga = releaseId.getGroupId() + "":"" + releaseId.getArtifactId(); @@ -225,12 +239,23 @@ KieModule load(ReleaseId releaseId) { KieModule load(ReleaseId releaseId, VersionRange versionRange) { String ga = releaseId.getGroupId() + "":"" + releaseId.getArtifactId(); TreeMap artifactMap = kieModules.get(ga); - if (artifactMap == null) { + if ( artifactMap == null ) { return null; } if (versionRange.fixed) { - return artifactMap.get(new ComparableVersion(releaseId.getVersion())); + KieModule kieModule = artifactMap.get(new ComparableVersion(releaseId.getVersion())); + if ( kieModule != null && releaseId.isSnapshot() ) { + String oldSnapshotVersion = ((ReleaseIdImpl)kieModule.getReleaseId()).getSnapshotVersion(); + String currentSnapshotVersion = kieScanner.getArtifactVersion(releaseId); + if ( oldSnapshotVersion != null && currentSnapshotVersion != null && + new ComparableVersion(currentSnapshotVersion).compareTo(new ComparableVersion(oldSnapshotVersion)) > 0) { + // if the snapshot currently available on the maven repo is newer than the cached one + // return null to enforce the building of this newer version + return null; + } + } + return kieModule; } if (versionRange.upperBound == null) { @@ -241,11 +266,11 @@ KieModule load(ReleaseId releaseId, VersionRange versionRange) { artifactMap.ceilingEntry(new ComparableVersion(versionRange.upperBound)) : artifactMap.lowerEntry(new ComparableVersion(versionRange.upperBound)); - if (entry == null) { + if ( entry == null ) { return null; } - if (versionRange.lowerBound == null) { + if ( versionRange.lowerBound == null ) { return entry.getValue(); } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kproject/ReleaseIdImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kproject/ReleaseIdImpl.java index 6777edbd6db..58f204c9625 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kproject/ReleaseIdImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kproject/ReleaseIdImpl.java @@ -12,6 +12,8 @@ public class ReleaseIdImpl implements ReleaseId { private final String artifactId; private final String version; + private String snapshotVersion; + public ReleaseIdImpl(String releaseId) { String[] split = releaseId.split("":""); this.groupId = split[0]; @@ -60,6 +62,10 @@ public String getCompilationCachePathPrefix() { //return ""META-INF/maven/"" + groupId + ""/"" + artifactId + ""/""; return ""META-INF/""; } + + public boolean isSnapshot() { + return version.endsWith(""-SNAPSHOT""); + } public static ReleaseId fromPropertiesString(String string) { Properties props = new Properties(); @@ -101,4 +107,12 @@ public int hashCode() { result = 31 * result + (version != null ? version.hashCode() : 0); return result; } + + public String getSnapshotVersion() { + return snapshotVersion; + } + + public void setSnapshotVersion(String snapshotVersion) { + this.snapshotVersion = snapshotVersion; + } } diff --git a/kie-ci/src/main/java/org/kie/scanner/KieRepositoryScannerImpl.java b/kie-ci/src/main/java/org/kie/scanner/KieRepositoryScannerImpl.java index 6eef4d1d340..b7917859b5b 100644 --- a/kie-ci/src/main/java/org/kie/scanner/KieRepositoryScannerImpl.java +++ b/kie-ci/src/main/java/org/kie/scanner/KieRepositoryScannerImpl.java @@ -1,5 +1,6 @@ package org.kie.scanner; +import org.drools.compiler.kproject.ReleaseIdImpl; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.KieModule; @@ -87,6 +88,14 @@ public KieModule loadArtifact(ReleaseId releaseId, InputStream pomXml) { Artifact artifact = resolver.resolveArtifact(artifactName); return artifact != null ? buildArtifact(releaseId, artifact, resolver) : loadPomArtifact(releaseId); } + + public String getArtifactVersion(ReleaseId releaseId) { + if (!releaseId.isSnapshot()) { + return releaseId.getVersion(); + } + Artifact artifact = getArtifactResolver().resolveArtifact(releaseId.toString()); + return artifact != null ? artifact.getVersion() : null; + } private KieModule loadPomArtifact(ReleaseId releaseId) { ArtifactResolver resolver = getResolverFor(releaseId, false); @@ -101,6 +110,9 @@ private KieModule loadPomArtifact(ReleaseId releaseId) { } private InternalKieModule buildArtifact(ReleaseId releaseId, Artifact artifact, ArtifactResolver resolver) { + if (releaseId.isSnapshot()) { + ((ReleaseIdImpl)releaseId).setSnapshotVersion(artifact.getVersion()); + } ZipKieModule kieModule = createZipKieModule(releaseId, artifact.getFile()); if (kieModule != null) { addDependencies(kieModule, resolver, resolver.getArtifactDependecies(new DependencyDescriptor(artifact).toString())); diff --git a/kie-ci/src/test/java/org/kie/scanner/KieModuleMavenTest.java b/kie-ci/src/test/java/org/kie/scanner/KieModuleMavenTest.java index 636c97cbaf7..3c09126fae0 100644 --- a/kie-ci/src/test/java/org/kie/scanner/KieModuleMavenTest.java +++ b/kie-ci/src/test/java/org/kie/scanner/KieModuleMavenTest.java @@ -24,8 +24,6 @@ import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.definition.KiePackage; -import org.kie.api.definition.process.*; -import org.kie.api.definition.process.Process; import org.kie.api.definition.rule.Rule; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; @@ -138,8 +136,9 @@ public void testKieModulePojoDependencies() throws Exception { assertEquals(1, list.size()); } - @Test @Ignore + @Test public void testKieContainerBeforeAndAfterDeployOfSnapshot() throws Exception { + // BZ-1007977 KieServices ks = KieServices.Factory.get(); String group = ""org.kie.test""; @@ -180,7 +179,6 @@ public void testKieContainerBeforeAndAfterDeployOfSnapshot() throws Exception { assertEquals(1, packages2.size()); Collection rules2 = packages2.iterator().next().getRules(); assertEquals(4, rules2.size()); - } public static String generatePomXml(ReleaseId releaseId, ReleaseId... dependencies) {" 96a1477d02e29b3002678f4da9ca55184888a54c,hadoop,HADOOP-6534. Trim whitespace from directory lists- initializing LocalDirAllocator. Contributed by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@909806 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index d42bd21c00c19..c02fbd20426ec 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -137,6 +137,9 @@ Trunk (unreleased changes) HADOOP-6552. Puts renewTGT=true and useTicketCache=true for the keytab kerberos options. (ddas) + HADOOP-6534. Trim whitespace from directory lists initializing + LocalDirAllocator. (Todd Lipcon via cdouglas) + OPTIMIZATIONS BUG FIXES diff --git a/src/java/org/apache/hadoop/fs/LocalDirAllocator.java b/src/java/org/apache/hadoop/fs/LocalDirAllocator.java index 1aa4663b15a25..d04bb56b27e53 100644 --- a/src/java/org/apache/hadoop/fs/LocalDirAllocator.java +++ b/src/java/org/apache/hadoop/fs/LocalDirAllocator.java @@ -213,7 +213,7 @@ public AllocatorPerContext(String contextCfgItemName) { private void confChanged(Configuration conf) throws IOException { String newLocalDirs = conf.get(contextCfgItemName); if (!newLocalDirs.equals(savedLocalDirs)) { - localDirs = conf.getStrings(contextCfgItemName); + localDirs = conf.getTrimmedStrings(contextCfgItemName); localFS = FileSystem.getLocal(conf); int numDirs = localDirs.length; ArrayList dirs = new ArrayList(numDirs);" d52a7d799c2ab73dbc38de272d173bbe9cf08797,orientdb,Fixed issue reported by Steven about TX- congruency with nested records. The bug was reported in rollback.--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java index 6f4d86d0df7..b873860ec1c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java @@ -795,11 +795,18 @@ public long createRecord(final ORecordId iRid, final byte[] iContent, final byte ORecordCallback iCallback) { checkOpeness(); - iRid.clusterPosition = createRecord(getClusterById(iRid.clusterId), iContent, iRecordType); + final OCluster cluster = getClusterById(iRid.clusterId); + + if (txManager.isCommitting()) + iRid.clusterPosition = txManager + .createRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iRecordType); + else + iRid.clusterPosition = createRecord(cluster, iContent, iRecordType); return iRid.clusterPosition; } - public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache, ORecordCallback iCallback) { + public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, boolean iIgnoreCache, + ORecordCallback iCallback) { checkOpeness(); return readRecord(getClusterById(iRid.clusterId), iRid, true); } @@ -807,12 +814,24 @@ public ORawBuffer readRecord(final ORecordId iRid, final String iFetchPlan, bool public int updateRecord(final ORecordId iRid, final byte[] iContent, final int iVersion, final byte iRecordType, final int iMode, ORecordCallback iCallback) { checkOpeness(); - return updateRecord(getClusterById(iRid.clusterId), iRid, iContent, iVersion, iRecordType); + + final OCluster cluster = getClusterById(iRid.clusterId); + + if (txManager.isCommitting()) + return txManager.updateRecord(txManager.getCurrentTransaction().getId(), cluster, iRid, iContent, iVersion, iRecordType); + else + return updateRecord(cluster, iRid, iContent, iVersion, iRecordType); } public boolean deleteRecord(final ORecordId iRid, final int iVersion, final int iMode, ORecordCallback iCallback) { checkOpeness(); - return deleteRecord(getClusterById(iRid.clusterId), iRid, iVersion); + + final OCluster cluster = getClusterById(iRid.clusterId); + + if (txManager.isCommitting()) + return txManager.deleteRecord(txManager.getCurrentTransaction().getId(), cluster, iRid.clusterPosition, iVersion); + else + return deleteRecord(cluster, iRid, iVersion); } public Set getClusterNames() { diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java index 79b7258e7d9..346cfa3307e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java @@ -37,6 +37,7 @@ public class OStorageLocalTxExecuter { private final OStorageLocal storage; private final OTxSegment txSegment; + private OTransaction currentTransaction; public OStorageLocalTxExecuter(final OStorageLocal iStorage, final OStorageTxConfiguration iConfig) throws IOException { storage = iStorage; @@ -59,7 +60,7 @@ public void close() throws IOException { } protected long createRecord(final int iTxId, final OCluster iClusterSegment, final ORecordId iRid, final byte[] iContent, - final byte iRecordType) throws IOException { + final byte iRecordType) { iRid.clusterPosition = -1; try { @@ -108,7 +109,7 @@ protected int updateRecord(final int iTxId, final OCluster iClusterSegment, fina return -1; } - protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { + protected boolean deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { try { final ORecordId rid = new ORecordId(iClusterSegment.getId(), iPosition); @@ -119,13 +120,14 @@ protected void deleteRecord(final int iTxId, final OCluster iClusterSegment, fin txSegment.addLog(OTxSegment.OPERATION_DELETE, iTxId, iClusterSegment.getId(), iPosition, buffer.recordType, buffer.version, buffer.buffer); - storage.deleteRecord(iClusterSegment, rid, iVersion); + return storage.deleteRecord(iClusterSegment, rid, iVersion); } catch (IOException e) { OLogManager.instance().error(this, ""Error on deleting entry #"" + iPosition + "" in log segment: "" + iClusterSegment, e, OTransactionException.class); } + return false; } public OTxSegment getTxSegment() { @@ -133,25 +135,30 @@ public OTxSegment getTxSegment() { } public void commitAllPendingRecords(final OTransaction iTx) throws IOException { - // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND - // CONCURRENT-EXCEPTION MAY OCCURS - final List tmpEntries = new ArrayList(); + currentTransaction = iTx; + try { + // COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND + // CONCURRENT-EXCEPTION MAY OCCURS + final List tmpEntries = new ArrayList(); - while (iTx.getCurrentRecordEntries().iterator().hasNext()) { - for (ORecordOperation txEntry : iTx.getCurrentRecordEntries()) - tmpEntries.add(txEntry); + while (iTx.getCurrentRecordEntries().iterator().hasNext()) { + for (ORecordOperation txEntry : iTx.getCurrentRecordEntries()) + tmpEntries.add(txEntry); - iTx.clearRecordEntries(); + iTx.clearRecordEntries(); - if (!tmpEntries.isEmpty()) { - for (ORecordOperation txEntry : tmpEntries) - // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE - commitEntry(iTx, txEntry, iTx.isUsingLog()); + if (!tmpEntries.isEmpty()) { + for (ORecordOperation txEntry : tmpEntries) + // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE + commitEntry(iTx, txEntry, iTx.isUsingLog()); + } } - } - // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT - OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true); + // UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT + OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true); + } finally { + currentTransaction = null; + } } public void clearLogEntries(final OTransaction iTx) throws IOException { @@ -273,4 +280,12 @@ private void commitEntry(final OTransaction iTx, final ORecordOperation txEntry, if (txEntry.getRecord() instanceof OTxListener) ((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.AFTER_COMMIT); } + + public boolean isCommitting() { + return currentTransaction != null; + } + + public OTransaction getCurrentTransaction() { + return currentTransaction; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java index 4d7f1c98259..0e88e90e161 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java @@ -151,8 +151,8 @@ private void addRecord(final ORecordInternal iRecord, final byte iStatus, fin // && iRecord.getIdentity().isValid() && allEntries.containsKey(iRecord.getIdentity())) { // if ((OStorage.CLUSTER_INDEX_NAME.equals(iClusterName) || iRecord.getIdentity().getClusterId() == database.getStorage() // .getClusterIdByName(OStorage.CLUSTER_INDEX_NAME)) && database.getStorage() instanceof OStorageEmbedded) { + // I'M COMMITTING: BYPASS LOCAL BUFFER - switch (iStatus) { case ORecordOperation.CREATED: case ORecordOperation.UPDATED: diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java index 0a88593ad2b..88786d54fd1 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionConsistencyTest.java @@ -21,6 +21,8 @@ import java.util.Vector; import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -32,6 +34,7 @@ import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE; @@ -53,10 +56,17 @@ public class TransactionConsistencyTest { // } @Parameters(value = ""url"") - public TransactionConsistencyTest(String iURL) throws IOException { + public TransactionConsistencyTest(@Optional(value = ""memory:test"") String iURL) throws IOException { url = iURL; } + @BeforeClass + public void init() { + ODatabaseDocumentTx database = new ODatabaseDocumentTx(url); + if (""memory:test"".equals(database.getURL())) + database.create(); + } + @Test public void test1RollbackOnConcurrentException() throws IOException { database1 = new ODatabaseDocumentTx(url).open(""admin"", ""admin""); @@ -625,6 +635,7 @@ public void deletesWithinTransactionArentWorking() throws IOException { db.close(); } } + // // @SuppressWarnings(""unchecked"") // @Test @@ -674,4 +685,109 @@ public void deletesWithinTransactionArentWorking() throws IOException { // db.close(); // System.out.println(""************ end testTransactionPopulatePartialDelete *******************""); // } + + public void TransactionRollbackConstistencyTest() { + System.out.println(""**************************TransactionRollbackConsistencyTest***************************************""); + ODatabaseDocumentTx db = new ODatabaseDocumentTx(url); + db.open(""admin"", ""admin""); + OClass vertexClass = db.getMetadata().getSchema().createClass(""TRVertex""); + OClass edgeClass = db.getMetadata().getSchema().createClass(""TREdge""); + vertexClass.createProperty(""in"", OType.LINKSET, edgeClass); + vertexClass.createProperty(""out"", OType.LINKSET, edgeClass); + edgeClass.createProperty(""in"", OType.LINK, vertexClass); + edgeClass.createProperty(""out"", OType.LINK, vertexClass); + + OClass personClass = db.getMetadata().getSchema().createClass(""TRPerson"", vertexClass); + personClass.createProperty(""name"", OType.STRING).createIndex(OClass.INDEX_TYPE.UNIQUE); + personClass.createProperty(""surname"", OType.STRING).createIndex(OClass.INDEX_TYPE.NOTUNIQUE); + personClass.createProperty(""version"", OType.INTEGER); + + db.getMetadata().getSchema().save(); + db.close(); + + final int cnt = 4; + + db.open(""admin"", ""admin""); + db.begin(); + Vector inserted = new Vector(); + + for (int i = 0; i < cnt; i++) { + ODocument person = new ODocument(""TRPerson""); + person.field(""name"", Character.toString((char) ('A' + i))); + person.field(""surname"", Character.toString((char) ('A' + (i % 3)))); + person.field(""myversion"", 0); + person.field(""in"", new HashSet()); + person.field(""out"", new HashSet()); + + if (i >= 1) { + ODocument edge = new ODocument(""TREdge""); + edge.field(""in"", person.getIdentity()); + edge.field(""out"", inserted.elementAt(i - 1)); + ((HashSet) person.field(""out"")).add(edge); + ((HashSet) ((ODocument) inserted.elementAt(i - 1)).field(""in"")).add(edge); + edge.save(); + } + inserted.add(person); + person.save(); + } + db.commit(); + + final List result1 = db.command(new OCommandSQL(""select from TRPerson"")).execute(); + Assert.assertNotNull(result1); + Assert.assertEquals(result1.size(), 4); + System.out.println(""Before transaction commit""); + for (ODocument d : result1) + System.out.println(d); + + try { + db.begin(); + Vector inserted2 = new Vector(); + + for (int i = 0; i < cnt; i++) { + ODocument person = new ODocument(""TRPerson""); + person.field(""name"", Character.toString((char) ('a' + i))); + person.field(""surname"", Character.toString((char) ('a' + (i % 3)))); + person.field(""myversion"", 0); + person.field(""in"", new HashSet()); + person.field(""out"", new HashSet()); + + if (i >= 1) { + ODocument edge = new ODocument(""TREdge""); + edge.field(""in"", person.getIdentity()); + edge.field(""out"", inserted2.elementAt(i - 1)); + ((HashSet) person.field(""out"")).add(edge); + ((HashSet) ((ODocument) inserted2.elementAt(i - 1)).field(""in"")).add(edge); + edge.save(); + } + inserted2.add(person); + person.save(); + } + + for (int i = 0; i < cnt; i++) { + if (i != cnt - 1) { + ((ODocument) inserted.elementAt(i)).field(""myversion"", 2); + ((ODocument) inserted.elementAt(i)).save(); + } + } + + ((ODocument) inserted.elementAt(cnt - 1)).delete(); + ((ODocument) inserted.elementAt(cnt - 2)).setVersion(0); + ((ODocument) inserted.elementAt(cnt - 2)).save(); + db.commit(); + Assert.assertTrue(false); + } catch (OConcurrentModificationException e) { + Assert.assertTrue(true); + db.rollback(); + } + + final List result2 = db.command(new OCommandSQL(""select from TRPerson"")).execute(); + Assert.assertNotNull(result2); + System.out.println(""After transaction commit failure/rollback""); + for (ODocument d : result2) + System.out.println(d); + Assert.assertEquals(result2.size(), 4); + + db.close(); + System.out.println(""**************************TransactionRollbackConstistencyTest***************************************""); + } }" 461d99af29e8c358ff80ff9ff58a8ea63fe7b670,spring-framework,"Fix package cycles in spring-test--Code introduced in conjunction with SPR-5243 introduced package cycles-between the ~.test.context and ~.test.context.web packages. This was-caused by the fact that ContextLoaderUtils worked directly with the-@WebAppConfiguration and WebMergedContextConfiguration types.--To address this, the following methods have been introduced in-ContextLoaderUtils. These methods use reflection to circumvent hard-dependencies on the @WebAppConfiguration and-WebMergedContextConfiguration types.-- - loadWebAppConfigurationClass()- - buildWebMergedContextConfiguration()--Issue: SPR-9924-",c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java index 5e2e2357076c..425878a543b1 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java @@ -19,6 +19,8 @@ import static org.springframework.beans.BeanUtils.*; import static org.springframework.core.annotation.AnnotationUtils.*; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -27,10 +29,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.context.web.WebMergedContextConfiguration; +import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -57,6 +59,9 @@ abstract class ContextLoaderUtils { private static final String DEFAULT_CONTEXT_LOADER_CLASS_NAME = ""org.springframework.test.context.support.DelegatingSmartContextLoader""; private static final String DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME = ""org.springframework.test.context.support.WebDelegatingSmartContextLoader""; + private static final String WEB_APP_CONFIGURATION_CLASS_NAME = ""org.springframework.test.context.web.WebAppConfiguration""; + private static final String WEB_MERGED_CONTEXT_CONFIGURATION_CLASS_NAME = ""org.springframework.test.context.web.WebMergedContextConfiguration""; + private ContextLoaderUtils() { /* no-op */ @@ -69,7 +74,8 @@ private ContextLoaderUtils() { * *

If the supplied defaultContextLoaderClassName is * {@code null} or empty, depending on the absence or presence - * of @{@link WebAppConfiguration} either {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} + * of {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration} + * either {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} * or {@value #DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME} will be used as the * default context loader class name. For details on the class resolution * process, see {@link #resolveContextLoaderClass()}. @@ -91,7 +97,9 @@ static ContextLoader resolveContextLoader(Class testClass, Assert.notEmpty(configAttributesList, ""ContextConfigurationAttributes list must not be empty""); if (!StringUtils.hasText(defaultContextLoaderClassName)) { - defaultContextLoaderClassName = testClass.isAnnotationPresent(WebAppConfiguration.class) ? DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME + Class webAppConfigClass = loadWebAppConfigurationClass(); + defaultContextLoaderClassName = webAppConfigClass != null + && testClass.isAnnotationPresent(webAppConfigClass) ? DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME : DEFAULT_CONTEXT_LOADER_CLASS_NAME; } @@ -385,16 +393,82 @@ static MergedContextConfiguration buildMergedContextConfiguration(Class testC Set>> initializerClasses = resolveInitializerClasses(configAttributesList); String[] activeProfiles = resolveActiveProfiles(testClass); - if (testClass.isAnnotationPresent(WebAppConfiguration.class)) { - WebAppConfiguration webAppConfig = testClass.getAnnotation(WebAppConfiguration.class); - String resourceBasePath = webAppConfig.value(); - return new WebMergedContextConfiguration(testClass, locations, classes, initializerClasses, activeProfiles, - resourceBasePath, contextLoader); + MergedContextConfiguration mergedConfig = buildWebMergedContextConfiguration(testClass, locations, classes, + initializerClasses, activeProfiles, contextLoader); + + if (mergedConfig == null) { + mergedConfig = new MergedContextConfiguration(testClass, locations, classes, initializerClasses, + activeProfiles, contextLoader); + } + + return mergedConfig; + } + + /** + * Load the {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration} + * class using reflection in order to avoid package cycles. + * + * @return the {@code @WebAppConfiguration} class or null if it + * cannot be loaded + */ + @SuppressWarnings(""unchecked"") + private static Class loadWebAppConfigurationClass() { + Class webAppConfigClass = null; + try { + webAppConfigClass = (Class) ClassUtils.forName(WEB_APP_CONFIGURATION_CLASS_NAME, + ContextLoaderUtils.class.getClassLoader()); + } + catch (Throwable t) { + if (logger.isDebugEnabled()) { + logger.debug(""Could not load @WebAppConfiguration class ["" + WEB_APP_CONFIGURATION_CLASS_NAME + ""]."", t); + } + } + return webAppConfigClass; + } + + /** + * Attempt to build a {@link org.springframework.test.context.web.WebMergedContextConfiguration + * WebMergedContextConfiguration} from the supplied arguments using reflection + * in order to avoid package cycles. + * + * @return the {@code WebMergedContextConfiguration} or null if + * it could not be built + */ + @SuppressWarnings(""unchecked"") + private static MergedContextConfiguration buildWebMergedContextConfiguration( + Class testClass, + String[] locations, + Class[] classes, + Set>> initializerClasses, + String[] activeProfiles, ContextLoader contextLoader) { + + Class webAppConfigClass = loadWebAppConfigurationClass(); + + if (webAppConfigClass != null && testClass.isAnnotationPresent(webAppConfigClass)) { + Annotation annotation = testClass.getAnnotation(webAppConfigClass); + String resourceBasePath = (String) AnnotationUtils.getValue(annotation); + + try { + Class webMergedConfigClass = (Class) ClassUtils.forName( + WEB_MERGED_CONTEXT_CONFIGURATION_CLASS_NAME, ContextLoaderUtils.class.getClassLoader()); + + Constructor constructor = ClassUtils.getConstructorIfAvailable( + webMergedConfigClass, Class.class, String[].class, Class[].class, Set.class, String[].class, + String.class, ContextLoader.class); + + if (constructor != null) { + return instantiateClass(constructor, testClass, locations, classes, initializerClasses, + activeProfiles, resourceBasePath, contextLoader); + } + } + catch (Throwable t) { + if (logger.isDebugEnabled()) { + logger.debug(""Could not instantiate ["" + WEB_MERGED_CONTEXT_CONFIGURATION_CLASS_NAME + ""]."", t); + } + } } - // else - return new MergedContextConfiguration(testClass, locations, classes, initializerClasses, activeProfiles, - contextLoader); + return null; } } diff --git a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java index 969234061edc..1e999d7e138f 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java @@ -48,7 +48,7 @@ public class ServletTestExecutionListener implements TestExecutionListener { * The default implementation is empty. Can be overridden by * subclasses as necessary. * - * @see org.springframework.test.context.TestExecutionListener#beforeTestClass(TestContext) + * @see TestExecutionListener#beforeTestClass(TestContext) */ public void beforeTestClass(TestContext testContext) throws Exception { /* no-op */ @@ -57,7 +57,7 @@ public void beforeTestClass(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden prepareTestInstance(). * - * @see org.springframework.test.context.TestExecutionListener#prepareTestInstance(TestContext) + * @see TestExecutionListener#prepareTestInstance(TestContext) */ public void prepareTestInstance(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); @@ -66,7 +66,7 @@ public void prepareTestInstance(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden beforeTestMethod(). * - * @see org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext) + * @see TestExecutionListener#beforeTestMethod(TestContext) */ public void beforeTestMethod(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); @@ -75,7 +75,7 @@ public void beforeTestMethod(TestContext testContext) throws Exception { /** * TODO [SPR-9864] Document overridden afterTestMethod(). * - * @see org.springframework.test.context.TestExecutionListener#afterTestMethod(TestContext) + * @see TestExecutionListener#afterTestMethod(TestContext) */ public void afterTestMethod(TestContext testContext) throws Exception { if (logger.isDebugEnabled()) { @@ -88,7 +88,7 @@ public void afterTestMethod(TestContext testContext) throws Exception { * The default implementation is empty. Can be overridden by * subclasses as necessary. * - * @see org.springframework.test.context.TestExecutionListener#afterTestClass(TestContext) + * @see TestExecutionListener#afterTestClass(TestContext) */ public void afterTestClass(TestContext testContext) throws Exception { /* no-op */" ef85412f98e97ff5471013eab59fd8cb3046c17a,elasticsearch,fix name--,p,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/json/JsonBoostFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/json/JsonBoostFieldMapper.java index 25e243cb91133..ff4061f6909b9 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/json/JsonBoostFieldMapper.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/json/JsonBoostFieldMapper.java @@ -126,7 +126,7 @@ protected JsonBoostFieldMapper(String name, String indexName, int precisionStep, @Override public void parse(JsonParseContext jsonContext) throws IOException { // we override parse since we want to handle cases where it is not indexed and not stored (the default) - float value = parsedFloatValue(jsonContext); + float value = parseFloatValue(jsonContext); if (!Float.isNaN(value)) { jsonContext.doc().setBoost(value); } @@ -134,7 +134,7 @@ protected JsonBoostFieldMapper(String name, String indexName, int precisionStep, } @Override protected Field parseCreateField(JsonParseContext jsonContext) throws IOException { - float value = parsedFloatValue(jsonContext); + float value = parseFloatValue(jsonContext); if (Float.isNaN(value)) { return null; } @@ -151,7 +151,7 @@ protected JsonBoostFieldMapper(String name, String indexName, int precisionStep, return field; } - private float parsedFloatValue(JsonParseContext jsonContext) throws IOException { + private float parseFloatValue(JsonParseContext jsonContext) throws IOException { float value; if (jsonContext.jp().getCurrentToken() == JsonToken.VALUE_NULL) { if (nullValue == null) {" e680208e4b24b1f5ea9522e04526ae572bb3b6e3,orientdb,Removed checks if db is open as a bug reported in- the ML by Stefan Ollinger--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java index 589f504912a..3a2ca0413bc 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java @@ -332,7 +332,6 @@ public T getUserObjectByRecord(final ORecordInternal iRecord, final String iF } public T getUserObjectByRecord(final ORecordInternal iRecord, final String iFetchPlan, final boolean iCreate) { - checkOpeness(); if (!(iRecord instanceof ODocument)) return null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java index 489f13de85e..3bb5ae10eb6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/object/ODatabaseObjectTx.java @@ -76,7 +76,6 @@ public T newInstance(final Class iType) { * @see #registerEntityClasses(String) */ public RET newInstance(final String iClassName) { - checkOpeness(); checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_CREATE, iClassName); try { diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java b/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java index 86c25ece009..e58aa388787 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/object/OLazyObjectIterator.java @@ -40,14 +40,14 @@ public class OLazyObjectIterator implements Iterator, Serializable { private final ODatabasePojoAbstract database; private final Iterator underlying; private String fetchPlan; - final private boolean convertToRecord; + final private boolean autoConvert2Object; public OLazyObjectIterator(final ODatabasePojoAbstract database, final ORecord iSourceRecord, final Iterator iIterator, final boolean iConvertToRecord) { this.database = database; this.sourceRecord = iSourceRecord; this.underlying = iIterator; - convertToRecord = iConvertToRecord; + autoConvert2Object = iConvertToRecord; } public TYPE next() { @@ -60,10 +60,10 @@ public TYPE next(final String iFetchPlan) { if (value == null) return null; - if (value instanceof ORID && convertToRecord) + if (value instanceof ORID && autoConvert2Object) return database.getUserObjectByRecord( (ORecordInternal) ((ODatabaseRecord) database.getUnderlying()).load((ORID) value, iFetchPlan), iFetchPlan); - else if (value instanceof ODocument && convertToRecord) + else if (value instanceof ODocument && autoConvert2Object) return database.getUserObjectByRecord((ODocument) value, iFetchPlan); return (TYPE) value; diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java index 270a55248f5..de2cb6d29d6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/OLazyRecordIterator.java @@ -31,14 +31,14 @@ public class OLazyRecordIterator implements Iterator { final private ODatabaseRecord sourceDatabase; final private ORecord sourceRecord; final private Iterator underlying; - final private boolean convertToRecord; + final private boolean autoConvert2Record; public OLazyRecordIterator(final ORecord iSourceRecord, final ODatabaseRecord iSourceDatabase, final byte iRecordType, final Iterator iIterator, final boolean iConvertToRecord) { this.sourceRecord = iSourceRecord; this.sourceDatabase = iSourceDatabase; this.underlying = iIterator; - this.convertToRecord = iConvertToRecord; + this.autoConvert2Record = iConvertToRecord; } public OIdentifiable next() { @@ -48,7 +48,7 @@ public OIdentifiable next() { return null; if (sourceDatabase != null) - if (value instanceof ORecordId && convertToRecord) + if (value instanceof ORecordId && autoConvert2Record) return (OIdentifiable) sourceDatabase.load((ORecordId) value); return value;" e8979daeaaae5cc34788ca5b04bf32826af491ae,intellij-community,code-dups cleanup--,p,https://github.com/JetBrains/intellij-community,"diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java index 750bae6c34237..fa5f8fd95740a 100644 --- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java +++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/MyTestInjector.java @@ -60,14 +60,14 @@ public void injectAll(Disposable parent) { injectVariousStuffEverywhere(parent, myPsiManager); Project project = myPsiManager.getProject(); - Language ql = findLanguageByID(""JPAQL""); - Language js = findLanguageByID(""JavaScript""); + Language ql = Language.findLanguageByID(""JPAQL""); + Language js = Language.findLanguageByID(""JavaScript""); registerForStringVarInitializer(parent, project, ql, ""ql"", null, null); registerForStringVarInitializer(parent, project, ql, ""qlPrefixed"", ""xxx"", null); registerForStringVarInitializer(parent, project, js, ""js"", null, null); registerForStringVarInitializer(parent, project, js, ""jsSeparated"", "" + "", "" + 'separator'""); registerForStringVarInitializer(parent, project, js, ""jsBrokenPrefix"", ""xx "", """"); - registerForParameterValue(parent, project, findLanguageByID(""Groovy""), ""groovy""); + registerForParameterValue(parent, project, Language.findLanguageByID(""Groovy""), ""groovy""); } private static void registerForParameterValue(Disposable parent, final Project project, final Language language, final String paramName) { @@ -149,19 +149,11 @@ public void dispose() { }); } - private static Language findLanguageByID(@NonNls String id) { - for (Language language : Language.getRegisteredLanguages()) { - if (language == Language.ANY) continue; - if (language.getID().equals(id)) return language; - } - return null; - } - private static void injectVariousStuffEverywhere(Disposable parent, final PsiManager psiManager) { - final Language ql = findLanguageByID(""JPAQL""); - final Language js = findLanguageByID(""JavaScript""); + final Language ql = Language.findLanguageByID(""JPAQL""); + final Language js = Language.findLanguageByID(""JavaScript""); if (ql == null || js == null) return; - final Language ecma4 = findLanguageByID(""ECMA Script Level 4""); + final Language ecma4 = Language.findLanguageByID(""ECMA Script Level 4""); final MultiHostInjector myMultiHostInjector = new MultiHostInjector() { public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) { @@ -265,7 +257,7 @@ public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNul paramList += parameter.getName(); } @NonNls String header = ""function "" + method.getName() + ""(""+paramList+"") {""; - Language gwt = findLanguageByID(""GWT JavaScript""); + Language gwt = Language.findLanguageByID(""GWT JavaScript""); placesToInject.addPlace(gwt, textRange, header, ""}""); return; } @@ -295,7 +287,7 @@ public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNul PsiClass aClass = PsiTreeUtil.getParentOfType(variable, PsiClass.class); aClass = aClass.findInnerClassByName(""Language"", false); String text = aClass.getInitializers()[0].getBody().getFirstBodyElement().getNextSibling().getText().substring(2); - Language language = findLanguageByID(text); + Language language = Language.findLanguageByID(text); if (language != null) { placesToInject.addPlace(language, textRangeToInject(host), """", """");" 03336a980d738426fb76202750befa48f3c1599e,ReactiveX-RxJava,Add marble diagrams for Single operators.--,p,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index d8fcf88b87..7f788583de 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -53,7 +53,7 @@ *

* The documentation for this class makes use of marble diagrams. The following legend explains these diagrams: *

- * + * *

* For more information see the ReactiveX documentation. * @@ -111,7 +111,7 @@ private Single(final Observable.OnSubscribe f) { /** * Returns a Single that will execute the specified function when a {@link SingleSubscriber} executes it or {@link Subscriber} subscribes to it. *

- * + * *

* Write the function you pass to {@code create} so that it behaves as a Single: It should invoke the * SingleSubscriber {@link SingleSubscriber#onSuccess onSuccess} and {@link SingleSubscriber#onError onError} methods appropriately. @@ -230,6 +230,9 @@ public static interface Transformer extends Func1, Single> { // cover for generics insanity } + /** + * + */ private static Observable toObservable(Single t) { // is this sufficient, or do I need to keep the outer Single and subscribe to it? return Observable.create(t.onSubscribe); @@ -241,7 +244,7 @@ private static Observable toObservable(Single t) { * Converts the source {@code Single} into an {@code Single>} that emits the * source Observable as its single emission. *

- * + * *

*
Scheduler:
*
{@code nest} does not operate by default on a particular {@link Scheduler}.
@@ -263,7 +266,7 @@ private final Single> nest() { * Returns an Observable that emits the items emitted by two Tasks, one after the other, without * interleaving them. *

- * + * *

*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -285,7 +288,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -309,7 +312,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -335,7 +338,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -363,7 +366,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -393,7 +396,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -425,7 +428,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -459,7 +462,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -495,7 +498,7 @@ public final static Observable concat(Single t1, Single - * + * *
*
Scheduler:
*
{@code error} does not operate by default on a particular {@link Scheduler}.
@@ -523,7 +526,7 @@ public void call(SingleSubscriber te) { /** * Converts a {@link Future} into an Observable. *

- * + * *

* You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method. @@ -549,7 +552,7 @@ public final static Single from(Future future) { /** * Converts a {@link Future} into an Observable, with a timeout on the Future. *

- * + * *

* You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method. @@ -579,7 +582,7 @@ public final static Single from(Future future, long timeout, /** * Converts a {@link Future}, operating on a specified {@link Scheduler}, into an Observable. *

- * + * *

* You can convert any object that supports the {@link Future} interface into an Observable that emits the * return value of the {@link Future#get} method of that object, by passing the object into the {@code from} method. @@ -605,7 +608,7 @@ public final static Single from(Future future, Scheduler sch /** * Returns an Observable that emits a single item and then completes. *

- * + * *

* To convert any object into an Observable that emits that object, pass that object into the {@code just} method. *

@@ -641,7 +644,7 @@ public void call(SingleSubscriber te) { * Flattens a Single that emits a Single into a single Single that emits the items emitted by * the nested Single, without any transformation. *

- * + * *

*

*
Scheduler:
@@ -678,7 +681,7 @@ public void onError(Throwable error) { /** * Flattens two Observables into a single Observable, without any transformation. *

- * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -701,7 +704,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -726,7 +729,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -753,7 +756,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -782,7 +785,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -813,7 +816,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -846,7 +849,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -881,7 +884,7 @@ public final static Observable merge(Single t1, Single - * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code merge} method. @@ -919,7 +922,7 @@ public final static Observable merge(Single t1, Single - * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1} and the first item * emitted by {@code o2}; the second item emitted by the new Observable will be the result of the function @@ -951,7 +954,7 @@ public final static Single zip(Single o1, Single - * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, and the first item emitted by {@code o3}; the second item emitted by the new @@ -986,7 +989,7 @@ public final static Single zip(Single o1, Singl * Returns an Observable that emits the results of a specified combiner function applied to combinations of * four items emitted, in sequence, by four other Observables. *

- * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, and the first item emitted by {@code 04}; @@ -1023,7 +1026,7 @@ public final static Single zip(Single o1, S * Returns an Observable that emits the results of a specified combiner function applied to combinations of * five items emitted, in sequence, by five other Observables. *

- * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, the first item emitted by {@code o4}, and @@ -1062,7 +1065,7 @@ public final static Single zip(Single o * Returns an Observable that emits the results of a specified combiner function applied to combinations of * six items emitted, in sequence, by six other Observables. *

- * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item @@ -1103,7 +1106,7 @@ public final static Single zip(Single - * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item @@ -1146,7 +1149,7 @@ public final static Single zip(Single - * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item @@ -1191,7 +1194,7 @@ public final static Single zip(Single - * + * *

{@code zip} applies this function in strict sequence, so the first item emitted by the new Observable * will be the result of the function applied to the first item emitted by each source Observable, the * second item emitted by the new Observable will be the result of the function applied to the second item @@ -1238,7 +1241,7 @@ public final static Single zip(Single * Returns an Observable that emits the items emitted from the current Observable, then the next, one after * the other, without interleaving them. *

- * + * *

*
Scheduler:
*
{@code concat} does not operate by default on a particular {@link Scheduler}.
@@ -1259,7 +1262,7 @@ public final Observable concatWith(Single t1) { * by the source Observable, where that function returns an Observable, and then merging those resulting * Observables and emitting the results of this merger. *

- * + * *

*
Scheduler:
*
{@code flatMap} does not operate by default on a particular {@link Scheduler}.
@@ -1282,7 +1285,7 @@ public final Single flatMap(final Func1 - * + * *
*
Scheduler:
*
{@code flatMap} does not operate by default on a particular {@link Scheduler}.
@@ -1304,7 +1307,7 @@ public final Observable flatMapObservable(Func1 - * + * *
*
Scheduler:
*
{@code map} does not operate by default on a particular {@link Scheduler}.
@@ -1322,7 +1325,7 @@ public final Single map(Func1 func) { /** * Flattens this and another Observable into a single Observable, without any transformation. *

- * + * *

* You can combine items emitted by multiple Observables so that they appear as a single Observable, by * using the {@code mergeWith} method. @@ -1344,7 +1347,7 @@ public final Observable mergeWith(Single t1) { * Modifies an Observable to perform its emissions and notifications on a specified {@link Scheduler}, * asynchronously with an unbounded buffer. *

- * + * *

*
Scheduler:
*
you specify which {@link Scheduler} this operator will use
@@ -1364,7 +1367,7 @@ public final Single observeOn(Scheduler scheduler) { /** * Instructs an Observable to emit an item (returned by a specified function) rather than invoking {@link Observer#onError onError} if it encounters an error. *

- * + * *

* By default, when an Observable encounters an error that prevents it from emitting the expected item to * its {@link Observer}, the Observable invokes its Observer's {@code onError} method, and then quits @@ -1707,7 +1710,7 @@ public void onNext(T t) { /** * Asynchronously subscribes Observers to this Observable on the specified {@link Scheduler}. *

- * + * *

*
Scheduler:
*
you specify which {@link Scheduler} this operator will use
@@ -1730,7 +1733,7 @@ public final Single subscribeOn(Scheduler scheduler) { * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable terminates and notifies observers of a {@code TimeoutException}. *

- * + * *

*
Scheduler:
*
This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.
@@ -1754,7 +1757,7 @@ public final Single timeout(long timeout, TimeUnit timeUnit) { * specified timeout duration starting from its predecessor, the resulting Observable terminates and * notifies observers of a {@code TimeoutException}. *

- * + * *

*
Scheduler:
*
you specify which {@link Scheduler} this operator will use
@@ -1779,7 +1782,7 @@ public final Single timeout(long timeout, TimeUnit timeUnit, Scheduler schedu * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, * the resulting Observable begins instead to mirror a fallback Observable. *

- * + * *

*
Scheduler:
*
This version of {@code timeout} operates by default on the {@code computation} {@link Scheduler}.
@@ -1803,7 +1806,7 @@ public final Single timeout(long timeout, TimeUnit timeUnit, Single - * + * *
*
Scheduler:
*
you specify which {@link Scheduler} this operator will use
@@ -1832,7 +1835,7 @@ public final Single timeout(long timeout, TimeUnit timeUnit, Single - * + * *
*
Scheduler:
*
{@code zipWith} does not operate by default on a particular {@link Scheduler}.
" 08d6538b3f9f611065682d08190747a7a93181fd,drools,[DROOLS-1026] improve equals/hashCode performances- for all rete nodes--,p,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/AccumulateTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/AccumulateTest.java index 5a299d99af6..efd46459257 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/AccumulateTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/AccumulateTest.java @@ -889,7 +889,7 @@ public void testAccumulateWithAndOrCombinations() throws Exception { wm.insert( new Person( ""Bob"", ""stilton"" ) ); } - @Test(timeout = 10000) + @Test//(timeout = 10000) public void testAccumulateWithSameSubnetwork() throws Exception { String rule = ""package org.drools.compiler.test;\n"" + ""import org.drools.compiler.Cheese;\n"" + diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/SharingTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/SharingTest.java index 763a2bac26f..112c84215f3 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/SharingTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/SharingTest.java @@ -184,8 +184,6 @@ public void testJoinNodeSharing() throws Exception { MethodCountingObjectTypeNode betaOTN = (MethodCountingObjectTypeNode) joinNode.getRightInput(); Map countingMap = betaOTN.getMethodCountMap(); - assertNotNull(countingMap); - assertEquals(1,countingMap.get(""thisNodeEquals"").intValue()); - assertNull (countingMap.get(""equals"")); //Make sure we are not using recursive ""equals"" method + assertNull(countingMap); } } diff --git a/drools-compiler/src/test/java/org/drools/compiler/reteoo/MockLeftTupleSink.java b/drools-compiler/src/test/java/org/drools/compiler/reteoo/MockLeftTupleSink.java index f2dcc4af914..6d5c68d0626 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/reteoo/MockLeftTupleSink.java +++ b/drools-compiler/src/test/java/org/drools/compiler/reteoo/MockLeftTupleSink.java @@ -219,4 +219,8 @@ public LeftTuple createPeer(LeftTuple original) { return null; } + @Override + protected boolean internalEquals( Object object ) { + return false; + } } diff --git a/drools-core/src/main/java/org/drools/core/base/dataproviders/MVELDataProvider.java b/drools-core/src/main/java/org/drools/core/base/dataproviders/MVELDataProvider.java index 485a0c67cc9..61692a42d14 100644 --- a/drools-core/src/main/java/org/drools/core/base/dataproviders/MVELDataProvider.java +++ b/drools-core/src/main/java/org/drools/core/base/dataproviders/MVELDataProvider.java @@ -70,13 +70,17 @@ public boolean equals( Object obj ) { if (this == obj) { return true; } + if (obj == null || !(obj instanceof MVELDataProvider)) { return false; } - MVELDataProvider other = (MVELDataProvider) obj; + return unit.equals( ((MVELDataProvider) obj).unit ); + } - return unit.equals( other.unit ); + @Override + public int hashCode() { + return unit.hashCode(); } public void readExternal( ObjectInput in ) throws IOException, diff --git a/drools-core/src/main/java/org/drools/core/base/mvel/MVELCompilationUnit.java b/drools-core/src/main/java/org/drools/core/base/mvel/MVELCompilationUnit.java index 77e3893897f..10c27bd0fe7 100644 --- a/drools-core/src/main/java/org/drools/core/base/mvel/MVELCompilationUnit.java +++ b/drools-core/src/main/java/org/drools/core/base/mvel/MVELCompilationUnit.java @@ -181,6 +181,13 @@ public boolean equals( Object obj ) { Arrays.equals(localDeclarations, other.localDeclarations); } + @Override + public int hashCode() { + return 23 * expression.hashCode() + + 29 * Arrays.hashCode( previousDeclarations ) + + 31 * Arrays.hashCode( localDeclarations ); + } + public void writeExternal( ObjectOutput out ) throws IOException { out.writeUTF( name ); diff --git a/drools-core/src/main/java/org/drools/core/common/BaseNode.java b/drools-core/src/main/java/org/drools/core/common/BaseNode.java index ebdaf46a7c2..9144eeeb67d 100644 --- a/drools-core/src/main/java/org/drools/core/common/BaseNode.java +++ b/drools-core/src/main/java/org/drools/core/common/BaseNode.java @@ -41,6 +41,8 @@ public abstract class BaseNode protected Bag associations; private boolean streamMode; + protected int hashcode; + public BaseNode() { } @@ -69,6 +71,7 @@ public void readExternal(ObjectInput in) throws IOException, partitionsEnabled = in.readBoolean(); associations = (Bag) in.readObject(); streamMode = in.readBoolean(); + hashcode = in.readInt(); } public void writeExternal(ObjectOutput out) throws IOException { @@ -77,6 +80,7 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean( partitionsEnabled ); out.writeObject( associations ); out.writeBoolean( streamMode ); + out.writeInt(hashcode); } /* (non-Javadoc) @@ -133,13 +137,6 @@ protected abstract boolean doRemove(RuleRemovalContext context, */ public abstract boolean isInUse(); - /** - * The hashCode return is simply the unique id of the node. It is expected that base classes will also implement equals(Object object). - */ - public int hashCode() { - return this.id; - } - public String toString() { return ""["" + this.getClass().getSimpleName() + ""("" + this.id + "")]""; } @@ -193,8 +190,14 @@ public boolean isAssociatedWith( Rule rule ) { return this.associations.contains( rule ); } - //Default implementation public boolean thisNodeEquals(final Object object) { - return this.equals( object ); + return this == object || internalEquals( object ); + } + + protected abstract boolean internalEquals( Object object ); + + @Override + public final int hashCode() { + return hashcode; } } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java b/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java index 855c0984d5b..3a665ef64a0 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java @@ -81,6 +81,12 @@ public AccumulateNode(final int id, this.accumulate = accumulate; this.unwrapRightObject = unwrapRightObject; this.tupleMemoryEnabled = context.isTupleMemoryEnabled(); + + hashcode = this.leftInput.hashCode() ^ + this.rightInput.hashCode() ^ + this.accumulate.hashCode() ^ + this.resultBinder.hashCode() ^ + Arrays.hashCode( this.resultConstraints ); } public void readExternal( ObjectInput in ) throws IOException, @@ -158,37 +164,29 @@ public void attach( BuildContext context ) { super.attach( context ); } - /* (non-Javadoc) - * @see org.kie.reteoo.BaseNode#hashCode() - */ - public int hashCode() { - return this.leftInput.hashCode() ^ this.rightInput.hashCode() ^ this.accumulate.hashCode() ^ this.resultBinder.hashCode() ^ Arrays.hashCode( this.resultConstraints ); + protected int calculateHashCode() { + return 0; } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ + @Override public boolean equals( final Object object ) { - if ( this == object ) { - return true; - } - - if ( object == null || !(object instanceof AccumulateNode) ) { - return false; - } - - final AccumulateNode other = (AccumulateNode) object; + return this == object || + ( internalEquals( object ) && + this.leftInput.thisNodeEquals( ((AccumulateNode) object).leftInput ) && + this.rightInput.thisNodeEquals( ((AccumulateNode) object).rightInput ) ); + } - if ( this.getClass() != other.getClass() || (!this.leftInput.equals( other.leftInput )) || (!this.rightInput.equals( other.rightInput )) || (!this.constraints.equals( other.constraints )) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof AccumulateNode ) || this.hashCode() != object.hashCode() ) { return false; } - return this.accumulate.equals( other.accumulate ) && resultBinder.equals( other.resultBinder ) && Arrays.equals( this.resultConstraints, - other.resultConstraints ); - } - - public boolean thisNodeEquals(final Object object) { - return equals( object ); + AccumulateNode other = (AccumulateNode) object; + return this.constraints.equals( other.constraints ) && + this.accumulate.equals( other.accumulate ) && + resultBinder.equals( other.resultBinder ) && + Arrays.equals( this.resultConstraints, other.resultConstraints ); } /** diff --git a/drools-core/src/main/java/org/drools/core/reteoo/AlphaNode.java b/drools-core/src/main/java/org/drools/core/reteoo/AlphaNode.java index 3f859c0fd8e..f723c2b0771 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/AlphaNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/AlphaNode.java @@ -58,8 +58,6 @@ public class AlphaNode extends ObjectSource private ObjectSinkNode previousRightTupleSinkNode; private ObjectSinkNode nextRightTupleSinkNode; - private int hashcode; - public AlphaNode() { } @@ -101,7 +99,6 @@ public void readExternal(ObjectInput in) throws IOException, constraint = (AlphaNodeFieldConstraint) in.readObject(); declaredMask = (BitMask) in.readObject(); inferredMask = (BitMask) in.readObject(); - hashcode = in.readInt(); } public void writeExternal(ObjectOutput out) throws IOException { @@ -109,7 +106,6 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(constraint); out.writeObject(declaredMask); out.writeObject(inferredMask); - out.writeInt(hashcode); } /** @@ -181,26 +177,26 @@ public String toString() { return ""[AlphaNode("" + this.id + "") constraint="" + this.constraint + ""]""; } - public int hashCode() { - return hashcode; - } - private int calculateHashCode() { return (this.source != null ? this.source.hashCode() : 0) * 37 + (this.constraint != null ? this.constraint.hashCode() : 0) * 31; } - public boolean equals(final Object object) { - return thisNodeEquals(object) && (this.source != null ? this.source.equals(((AlphaNode) object).source) : ((AlphaNode) object).source == null); + @Override + public boolean equals(Object object) { + return this == object || + (internalEquals((AlphaNode)object) && + (this.source != null ? + this.source.thisNodeEquals(((AlphaNode) object).source) : + ((AlphaNode) object).source == null) ); } - public boolean thisNodeEquals(final Object object) { - if (this == object) { - return true; + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof AlphaNode) || this.hashCode() != object.hashCode() ) { + return false; } - return object instanceof AlphaNode && - this.hashCode() == object.hashCode() && - (constraint instanceof MvelConstraint ? + return (constraint instanceof MvelConstraint ? ((MvelConstraint) constraint).equals(((AlphaNode)object).constraint, getKnowledgeBase()) : constraint.equals(((AlphaNode)object).constraint)); } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java b/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java index ba474e1f245..569b58e3520 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java @@ -100,8 +100,6 @@ public abstract class BetaNode extends LeftTupleSource private boolean rightInputIsPassive; - private int hashcode; - // ------------------------------------------------------------ // Constructors // ------------------------------------------------------------ @@ -139,6 +137,8 @@ public BetaNode() { initMasks(context, leftInput); setStreamMode( context.isStreamMode() && getObjectTypeNode(context).getObjectType().isEvent() ); + + hashcode = calculateHashCode(); } private ObjectTypeNode getObjectTypeNode(BuildContext context) { @@ -308,7 +308,7 @@ public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples mod // we skipped this node, due to alpha hashing, so retract now rightTuple.setPropagationContext( context ); - BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getTupleSink(), wm ); + BetaMemory bm = getBetaMemory( rightTuple.getTupleSink(), wm ); (( BetaNode ) rightTuple.getTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); rightTuple = modifyPreviousTuples.peekRightTuple(); } @@ -543,10 +543,7 @@ public LeftTupleSource getLeftTupleSource() { return this.leftInput; } - /* (non-Javadoc) - * @see org.kie.reteoo.BaseNode#hashCode() - */ - public int hashCode() { + protected int calculateHashCode() { int hash = ( 23 * leftInput.hashCode() ) + ( 29 * rightInput.hashCode() ) + ( 31 * constraints.hashCode() ); if (leftListenedProperties != null) { hash += 37 * leftListenedProperties.hashCode(); @@ -557,31 +554,26 @@ public int hashCode() { return hash + (rightInputIsPassive ? 43 : 0); } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(final Object object) { - return thisNodeEquals(object); + @Override + public boolean equals(Object object) { + return this == object || + ( internalEquals(object) && + this.leftInput.thisNodeEquals( ((BetaNode) object).leftInput ) && + this.rightInput.thisNodeEquals( ((BetaNode) object).rightInput ) ); } - public boolean thisNodeEquals(final Object object) { - if ( this == object ) { - return true; - } - - if ( object == null || !(object instanceof BetaNode) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof BetaNode) || this.hashCode() != object.hashCode() ) { return false; } - final BetaNode other = (BetaNode) object; - + BetaNode other = (BetaNode) object; return this.getClass() == other.getClass() && - this.leftInput.thisNodeEquals( other.leftInput ) && - this.rightInput.thisNodeEquals( other.rightInput ) && - this.constraints.equals( other.constraints ) && - this.rightInputIsPassive == other.rightInputIsPassive && - areNullSafeEquals(this.leftListenedProperties, other.leftListenedProperties) && - areNullSafeEquals(this.rightListenedProperties, other.rightListenedProperties); + this.constraints.equals( other.constraints ) && + this.rightInputIsPassive == other.rightInputIsPassive && + areNullSafeEquals(this.leftListenedProperties, other.leftListenedProperties) && + areNullSafeEquals(this.rightListenedProperties, other.rightListenedProperties); } /** diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ConditionalBranchNode.java b/drools-core/src/main/java/org/drools/core/reteoo/ConditionalBranchNode.java index 8ffeffb2a6d..3b7d3cce13d 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/ConditionalBranchNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/ConditionalBranchNode.java @@ -57,6 +57,8 @@ public ConditionalBranchNode( int id, this.branchEvaluator = branchEvaluator; initMasks(context, tupleSource); + + hashcode = calculateHashCode(); } @Override @@ -101,22 +103,23 @@ public String toString() { return ""[ConditionalBranchNode: cond="" + this.branchEvaluator + ""]""; } - public int hashCode() { + private int calculateHashCode() { return this.tupleSource.hashCode() ^ this.branchEvaluator.hashCode(); } - public boolean equals(final Object object) { - if ( this == object ) { - return true; - } + @Override + public boolean equals(Object object) { + return this == object || + ( internalEquals( object ) && this.tupleSource.thisNodeEquals( ((ConditionalBranchNode)object).tupleSource ) ); + } - if ( object == null || object.getClass() != ConditionalBranchNode.class ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof ConditionalBranchNode) || this.hashCode() != object.hashCode() ) { return false; } - final ConditionalBranchNode other = (ConditionalBranchNode) object; - - return this.tupleSource.equals( other.tupleSource ) && this.branchEvaluator.equals( other.branchEvaluator ); + return this.branchEvaluator.equals( ((ConditionalBranchNode)object).branchEvaluator ); } public ConditionalBranchMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { diff --git a/drools-core/src/main/java/org/drools/core/reteoo/EntryPointNode.java b/drools-core/src/main/java/org/drools/core/reteoo/EntryPointNode.java index 82fea528e77..9a6347ad456 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/EntryPointNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/EntryPointNode.java @@ -108,6 +108,8 @@ public EntryPointNode(final int id, 999 ); // irrelevant for this node, since it overrides sink management this.entryPoint = entryPoint; this.objectTypeNodes = new ConcurrentHashMap(); + + hashcode = calculateHashCode(); } // ------------------------------------------------------------ @@ -421,21 +423,22 @@ public Map getObjectTypeNodes() { return this.objectTypeNodes; } - public int hashCode() { + private int calculateHashCode() { return this.entryPoint.hashCode(); } + @Override public boolean equals(final Object object) { - if ( object == this ) { - return true; - } + return this == object || internalEquals( object ); + } - if ( object == null || !(object instanceof EntryPointNode) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof EntryPointNode) || this.hashCode() != object.hashCode() ) { return false; } - final EntryPointNode other = (EntryPointNode) object; - return this.entryPoint.equals( other.entryPoint ); + return this.entryPoint.equals( ((EntryPointNode)object).entryPoint ); } public void updateSink(final ObjectSink sink, diff --git a/drools-core/src/main/java/org/drools/core/reteoo/EvalConditionNode.java b/drools-core/src/main/java/org/drools/core/reteoo/EvalConditionNode.java index 606f176a2fc..9db6baba2c1 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/EvalConditionNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/EvalConditionNode.java @@ -70,6 +70,8 @@ public EvalConditionNode(final int id, this.tupleMemoryEnabled = context.isTupleMemoryEnabled(); initMasks(context, tupleSource); + + hashcode = calculateHashCode(); } public void readExternal(ObjectInput in) throws IOException, @@ -127,22 +129,23 @@ public String toString() { return ""[EvalConditionNode: cond="" + this.condition + ""]""; } - public int hashCode() { + private int calculateHashCode() { return this.leftInput.hashCode() ^ this.condition.hashCode(); } + @Override public boolean equals(final Object object) { - if ( this == object ) { - return true; - } + return this == object || + ( internalEquals( object ) && this.leftInput.thisNodeEquals( ((EvalConditionNode)object).leftInput ) ); + } - if ( object == null || object.getClass() != EvalConditionNode.class ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof EvalConditionNode) || this.hashCode() != object.hashCode() ) { return false; } - final EvalConditionNode other = (EvalConditionNode) object; - - return this.leftInput.equals( other.leftInput ) && this.condition.equals( other.condition ); + return this.condition.equals( ((EvalConditionNode)object).condition ); } public EvalMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { diff --git a/drools-core/src/main/java/org/drools/core/reteoo/FromNode.java b/drools-core/src/main/java/org/drools/core/reteoo/FromNode.java index 9e96a2f4236..16bd9a8f4d2 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/FromNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/FromNode.java @@ -87,6 +87,8 @@ public FromNode(final int id, resultClass = this.from.getResultClass(); initMasks(context, tupleSource); + + hashcode = calculateHashCode(); } public void readExternal(ObjectInput in) throws IOException, @@ -109,19 +111,34 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( from ); } - @Override - public boolean equals( Object obj ) { - if (this == obj) { - return true; + private int calculateHashCode() { + int hash = ( 23 * leftInput.hashCode() ) + ( 29 * dataProvider.hashCode() ); + if (from.getResultPattern() != null) { + hash += 31 * from.getResultPattern().hashCode(); } - if (obj == null || !(obj instanceof FromNode)) { + if (alphaConstraints != null) { + hash += 37 * Arrays.hashCode( alphaConstraints ); + } + if (betaConstraints != null) { + hash += 41 * betaConstraints.hashCode(); + } + return hash; + } + + @Override + public boolean equals( Object object ) { + return this == object || (internalEquals( object ) && leftInput.thisNodeEquals( ((FromNode) object).leftInput ) ); + } + + @Override + protected boolean internalEquals( Object obj ) { + if (obj == null || !(obj instanceof FromNode ) || this.hashCode() != obj.hashCode() ) { return false; } FromNode other = (FromNode) obj; - return leftInput.equals( other.leftInput ) && - dataProvider.equals( other.dataProvider ) && + return dataProvider.equals( other.dataProvider ) && areNullSafeEquals(from.getResultPattern(), other.from.getResultPattern() ) && Arrays.equals( alphaConstraints, other.alphaConstraints ) && betaConstraints.equals( other.betaConstraints ); @@ -220,8 +237,7 @@ public T createMemory(final RuleBaseConfiguration config, InternalWorkingMemory this.betaConstraints.createContext(), NodeTypeEnums.FromNode ); return (T) new FromMemory( beta, - this.dataProvider, - this.alphaConstraints ); + this.dataProvider ); } @@ -293,8 +309,7 @@ public static class FromMemory extends AbstractBaseLinkedListNode public Object providerContext; public FromMemory(BetaMemory betaMemory, - DataProvider dataProvider, - AlphaNodeFieldConstraint[] constraints) { + DataProvider dataProvider) { this.betaMemory = betaMemory; this.dataProvider = dataProvider; this.providerContext = dataProvider.createContext(); diff --git a/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java b/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java index e987463b5dc..b004f42326c 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java @@ -70,8 +70,6 @@ public class LeftInputAdapterNode extends LeftTupleSource private BitMask sinkMask; - private int hashcode; - public LeftInputAdapterNode() { } @@ -126,7 +124,6 @@ public void readExternal(ObjectInput in) throws IOException, objectSource = (ObjectSource) in.readObject(); leftTupleMemoryEnabled = in.readBoolean(); sinkMask = (BitMask) in.readObject(); - hashcode = in.readInt(); } public void writeExternal(ObjectOutput out) throws IOException { @@ -134,7 +131,6 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(objectSource); out.writeBoolean(leftTupleMemoryEnabled); out.writeObject(sinkMask); - out.writeInt(hashcode); } public ObjectSource getObjectSource() { @@ -475,27 +471,23 @@ public void setPreviousObjectSinkNode(final ObjectSinkNode previous) { this.previousRightTupleSinkNode = previous; } - public int hashCode() { - return hashcode; - } - private int calculateHashCode() { return 31 * this.objectSource.hashCode() + 37 * sinkMask.hashCode(); } + @Override public boolean equals(final Object object) { - return thisNodeEquals(object) && - this.objectSource.equals(((LeftInputAdapterNode)object).objectSource); + return this == object || + ( internalEquals(object) && + this.objectSource.equals(((LeftInputAdapterNode)object).objectSource) ); } - public boolean thisNodeEquals(final Object object) { - if ( object == this ) { - return true; + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof LeftInputAdapterNode) || this.hashCode() != object.hashCode() ) { + return false; } - - return object instanceof LeftInputAdapterNode && - this.hashCode() == object.hashCode() && - this.sinkMask.equals( ((LeftInputAdapterNode) object).sinkMask ); + return this.sinkMask.equals( ((LeftInputAdapterNode) object).sinkMask ); } protected ObjectTypeNode getObjectTypeNode() { diff --git a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingAlphaNode.java b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingAlphaNode.java index 61861305c1b..3446277154c 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingAlphaNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingAlphaNode.java @@ -28,7 +28,7 @@ public boolean thisNodeEquals(final Object object) { private void incrementCount(String key) { if ( this.methodCount== null ) { - this.methodCount = new HashMap<>(); + this.methodCount = new HashMap(); } int count = methodCount.containsKey(key) ? methodCount.get(key) : 0; methodCount.put(key, count + 1); diff --git a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingLeftInputAdapterNode.java b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingLeftInputAdapterNode.java index 81221555432..ccbae0a34db 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingLeftInputAdapterNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingLeftInputAdapterNode.java @@ -26,7 +26,7 @@ public boolean thisNodeEquals(final Object object) { private void incrementCount(String key) { if ( this.methodCount== null ) { - this.methodCount = new HashMap<>(); + this.methodCount = new HashMap(); } int count = methodCount.containsKey(key) ? methodCount.get(key) : 0; methodCount.put(key, count + 1); diff --git a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingObjectTypeNode.java b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingObjectTypeNode.java index 6cd8a8d6f88..0a8dacecb64 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingObjectTypeNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/MethodCountingObjectTypeNode.java @@ -28,7 +28,7 @@ public boolean thisNodeEquals(final Object object) { private void incrementCount(String key) { if ( this.methodCount== null ) { - this.methodCount = new HashMap<>(); + this.methodCount = new HashMap(); } int count = methodCount.containsKey(key) ? methodCount.get(key) : 0; methodCount.put(key, count + 1); diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java b/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java index d275ab5e9a6..aa492b593d2 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/ObjectTypeNode.java @@ -111,8 +111,6 @@ public int getOtnIdCounter() { return idGenerator.otnIdCounter; } - private int hashcode; - public ObjectTypeNode() { } @@ -220,7 +218,6 @@ public void readExternal(ObjectInput in) throws IOException, queryNode = in.readBoolean(); dirty = true; idGenerator = new IdGenerator(id); - hashcode = in.readInt(); } public void writeExternal(ObjectOutput out) throws IOException { @@ -229,7 +226,6 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(objectMemoryEnabled); out.writeLong(expirationOffset); out.writeBoolean(queryNode); - out.writeInt(hashcode); } public short getType() { @@ -488,29 +484,21 @@ public String toString() { return ""[ObjectTypeNode("" + this.id + "")::"" + ((EntryPointNode) this.source).getEntryPoint() + "" objectType="" + this.objectType + "" expiration="" + this.getExpirationOffset() + ""ms ]""; } - /** - * Uses he hashCode() of the underlying ObjectType implementation. - */ - public int hashCode() { - return hashcode; - } - private int calculateHashCode() { return (this.objectType != null ? this.objectType.hashCode() : 0) * 37 + (this.source != null ? this.source.hashCode() : 0) * 31; } public boolean equals(final Object object) { - return thisNodeEquals(object) && this.source.equals(((ObjectTypeNode) object).source); + return this == object || + (internalEquals(object) && this.source.thisNodeEquals(((ObjectTypeNode) object).source)); } - public boolean thisNodeEquals(final Object object) { - if (this == object) { - return true; + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof ObjectTypeNode) || this.hashCode() != object.hashCode() ) { + return false; } - - return object instanceof ObjectTypeNode && - this.hashCode() == object.hashCode() && - this.objectType.equals(((ObjectTypeNode) object).objectType); + return this.objectType.equals( ((ObjectTypeNode)object).objectType ); } /** diff --git a/drools-core/src/main/java/org/drools/core/reteoo/PropagationQueuingNode.java b/drools-core/src/main/java/org/drools/core/reteoo/PropagationQueuingNode.java index fd4d55769de..9aca81d0954 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/PropagationQueuingNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/PropagationQueuingNode.java @@ -76,6 +76,8 @@ public PropagationQueuingNode(final int id, context.getKnowledgeBase().getConfiguration().getAlphaNodeHashingThreshold() ); this.action = new PropagateAction( this ); initDeclaredMask(context); + + hashcode = calculateHashCode(); } @Override @@ -259,31 +261,24 @@ public PropagationQueueingNodeMemory createMemory(RuleBaseConfiguration config, return new PropagationQueueingNodeMemory(); } - public int hashCode() { + public int calculateHashCode() { return this.source.hashCode(); } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ + @Override public boolean equals(final Object object) { - if ( this == object ) { - return true; - } + return this == object || + ( internalEquals( object ) && this.source.thisNodeEquals( ((PropagationQueuingNode)object).source ) ); + } - if ( object == null || !(object instanceof PropagationQueuingNode) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof PropagationQueuingNode) || this.hashCode() != object.hashCode() ) { return false; } - - final PropagationQueuingNode other = (PropagationQueuingNode) object; - - return this.source.equals( other.source ); + return true; } - - /** * Memory implementation for the node */ diff --git a/drools-core/src/main/java/org/drools/core/reteoo/QueryElementNode.java b/drools-core/src/main/java/org/drools/core/reteoo/QueryElementNode.java index 19b4c9ce137..bc4f9ae28ad 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/QueryElementNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/QueryElementNode.java @@ -92,6 +92,8 @@ public QueryElementNode(final int id, this.dataDriven = context != null && context.getRule().isDataDriven(); initMasks( context, tupleSource ); initArgsTemplate( context ); + + hashcode = calculateHashCode(); } private void initArgsTemplate(BuildContext context) { @@ -603,8 +605,7 @@ public LeftTuple createLeftTuple(LeftTuple leftTuple, leftTupleMemoryEnabled ); } - @Override - public int hashCode() { + private int calculateHashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (openQuery ? 1231 : 1237); @@ -614,19 +615,23 @@ public int hashCode() { } @Override - public boolean equals(Object obj) { - if ( this == obj ) return true; - if ( obj == null ) return false; - if ( getClass() != obj.getClass() ) return false; - QueryElementNode other = (QueryElementNode) obj; + public boolean equals(Object object) { + return this == object || + ( internalEquals( object ) && this.leftInput.thisNodeEquals( ((QueryElementNode)object).leftInput ) ); + } + + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof QueryElementNode) || this.hashCode() != object.hashCode() ) { + return false; + } + + QueryElementNode other = (QueryElementNode) object; if ( openQuery != other.openQuery ) return false; if ( !openQuery && dataDriven != other.dataDriven ) return false; if ( queryElement == null ) { if ( other.queryElement != null ) return false; } else if ( !queryElement.equals( other.queryElement ) ) return false; - if ( leftInput == null ) { - if ( other.leftInput != null ) return false; - } else if ( !leftInput.equals( other.leftInput ) ) return false; return true; } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/QueryRiaFixerNode.java b/drools-core/src/main/java/org/drools/core/reteoo/QueryRiaFixerNode.java index ce7ff9bcd04..8ad19b264b5 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/QueryRiaFixerNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/QueryRiaFixerNode.java @@ -70,6 +70,8 @@ public QueryRiaFixerNode(final int id, super(id, context); setLeftTupleSource(tupleSource); this.tupleMemoryEnabled = context.isTupleMemoryEnabled(); + + hashcode = calculateHashCode(); } public void readExternal(ObjectInput in) throws IOException, @@ -148,15 +150,22 @@ public String toString() { return ""[RiaQueryFixerNode: ]""; } - public int hashCode() { + public int calculateHashCode() { return this.leftInput.hashCode(); } + @Override public boolean equals(final Object object) { // we never node share, so only return true if we are instance equal return this == object; } + @Override + protected boolean internalEquals(final Object object) { + // we never node share, so only return true if we are instance equal + return this == object; + } + public void updateSink(final LeftTupleSink sink, final PropagationContext context, final InternalWorkingMemory workingMemory) { diff --git a/drools-core/src/main/java/org/drools/core/reteoo/QueryTerminalNode.java b/drools-core/src/main/java/org/drools/core/reteoo/QueryTerminalNode.java index bce044c86de..73bf10cb8ce 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/QueryTerminalNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/QueryTerminalNode.java @@ -91,6 +91,8 @@ public QueryTerminalNode(final int id, initDeclaredMask(context); initInferredMask(); initDeclarations(); + + hashcode = calculateHashCode(); } // ------------------------------------------------------------ @@ -120,13 +122,27 @@ public RuleImpl getRule() { return this.query; } + private int calculateHashCode() { + return this.query.hashCode(); + } + @Override + public boolean equals(final Object object) { + return this == object || internalEquals( (Rete) object ); + } + + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof QueryTerminalNode) || this.hashCode() != object.hashCode() ) { + return false; + } + return query.equals(((QueryTerminalNode) object).query); + } public String toString() { return ""[QueryTerminalNode("" + this.getId() + ""): query="" + this.query.getName() + ""]""; } - /** * @return the subrule */ diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ReactiveFromNode.java b/drools-core/src/main/java/org/drools/core/reteoo/ReactiveFromNode.java index 3fb1c4cbea3..00f6e08be9f 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/ReactiveFromNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/ReactiveFromNode.java @@ -47,8 +47,7 @@ public ReactiveFromMemory createMemory(final RuleBaseConfiguration config, Inter this.betaConstraints.createContext(), NodeTypeEnums.FromNode ); return new ReactiveFromMemory( beta, - this.dataProvider, - this.alphaConstraints ); + this.dataProvider ); } public short getType() { @@ -62,9 +61,8 @@ public static class ReactiveFromMemory extends FromNode.FromMemory { private final TupleSets stagedLeftTuples; public ReactiveFromMemory(BetaMemory betaMemory, - DataProvider dataProvider, - AlphaNodeFieldConstraint[] constraints) { - super(betaMemory, dataProvider, constraints); + DataProvider dataProvider) { + super(betaMemory, dataProvider); stagedLeftTuples = new TupleSetsImpl(); } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/Rete.java b/drools-core/src/main/java/org/drools/core/reteoo/Rete.java index f7d33ef6405..4babb8d4187 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/Rete.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/Rete.java @@ -81,6 +81,8 @@ public Rete(InternalKnowledgeBase kBase) { super( 0, RuleBasePartitionId.MAIN_PARTITION, kBase != null && kBase.getConfiguration().isMultithreadEvaluation() ); this.entryPoints = Collections.synchronizedMap( new HashMap() ); this.kBase = kBase; + + hashcode = calculateHashCode(); } public short getType() { @@ -199,21 +201,20 @@ public InternalKnowledgeBase getKnowledgeBase() { return this.kBase; } - public int hashCode() { + private int calculateHashCode() { return this.entryPoints.hashCode(); } public boolean equals(final Object object) { - if ( object == this ) { - return true; - } + return this == object || internalEquals( object ); + } - if ( object == null || !(object instanceof Rete) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof Rete) || this.hashCode() != object.hashCode() ) { return false; } - - final Rete other = (Rete) object; - return this.entryPoints.equals( other.entryPoints ); + return this.entryPoints.equals( ((Rete)object).entryPoints ); } public void updateSink(final ObjectSink sink, diff --git a/drools-core/src/main/java/org/drools/core/reteoo/RightInputAdapterNode.java b/drools-core/src/main/java/org/drools/core/reteoo/RightInputAdapterNode.java index 0712342e9e5..2ba182c0aa8 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/RightInputAdapterNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/RightInputAdapterNode.java @@ -86,6 +86,8 @@ public RightInputAdapterNode(final int id, this.tupleMemoryEnabled = context.isTupleMemoryEnabled(); this.startTupleSource = startTupleSource; context.getPathEndNodes().add(this); + + hashcode = calculateHashCode(); } public void readExternal(ObjectInput in) throws IOException, @@ -255,27 +257,23 @@ public short getType() { return NodeTypeEnums.RightInputAdaterNode; } - public int hashCode() { + private int calculateHashCode() { return this.tupleSource.hashCode() * 17 + ((this.tupleMemoryEnabled) ? 1234 : 4321); } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(final Object object) { - if ( this == object ) { - return true; - } + @Override + public boolean equals(Object object) { + return this == object || + ( internalEquals( object ) && this.tupleSource.thisNodeEquals( ((RightInputAdapterNode)object).tupleSource ) ); + } - if ( object == null || !(object instanceof RightInputAdapterNode) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof RightInputAdapterNode) || this.hashCode() != object.hashCode() ) { return false; } - final RightInputAdapterNode other = (RightInputAdapterNode) object; - - return this.tupleMemoryEnabled == other.tupleMemoryEnabled && this.tupleSource.equals( other.tupleSource ); + return this.tupleMemoryEnabled == ((RightInputAdapterNode)object).tupleMemoryEnabled; } @Override diff --git a/drools-core/src/main/java/org/drools/core/reteoo/RuleTerminalNode.java b/drools-core/src/main/java/org/drools/core/reteoo/RuleTerminalNode.java index a869396ded9..a8c4839304c 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/RuleTerminalNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/RuleTerminalNode.java @@ -115,6 +115,8 @@ public RuleTerminalNode(final int id, initDeclaredMask(context); initInferredMask(); + + hashcode = calculateHashCode(); } public void setDeclarations(Map decls) { @@ -330,19 +332,20 @@ public void setPreviousLeftTupleSinkNode(final LeftTupleSinkNode previous) { this.previousTupleSinkNode = previous; } - public int hashCode() { - return this.rule.hashCode(); + private int calculateHashCode() { + return 31 * this.rule.hashCode() + (consequenceName == null ? 0 : 37 * consequenceName.hashCode()); } + @Override public boolean equals(final Object object) { - if ( object == this ) { - return true; - } + return this == object || internalEquals( object ); + } - if ( !(object instanceof RuleTerminalNode) ) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof RuleTerminalNode) || this.hashCode() != object.hashCode() ) { return false; } - final RuleTerminalNode other = (RuleTerminalNode) object; return rule.equals(other.rule) && (consequenceName == null ? other.consequenceName == null : consequenceName.equals(other.consequenceName)); } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java index 8fd1a063c79..d71c8bded91 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/TimerNode.java @@ -68,6 +68,8 @@ public TimerNode(final int id, this.tupleMemoryEnabled = context.isTupleMemoryEnabled(); initMasks(context, tupleSource); + + hashcode = calculateHashCode(); } public void readExternal(ObjectInput in) throws IOException, @@ -125,7 +127,7 @@ public String toString() { return ""[TimerNode("" + this.id + ""): cond="" + this.timer + "" calendars="" + ((calendarNames == null) ? ""null"" : Arrays.asList(calendarNames)) + ""]""; } - public int hashCode() { + private int calculateHashCode() { int hash = this.leftInput.hashCode() ^ this.timer.hashCode(); if (calendarNames != null) { for ( String calendarName : calendarNames ) { @@ -136,16 +138,17 @@ public int hashCode() { } public boolean equals(final Object object) { - if (this == object) { - return true; - } + return this == object || + ( internalEquals( object ) && this.leftInput.thisNodeEquals(((TimerNode)object).leftInput) ); + } - if (object == null || object.getClass() != TimerNode.class) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof TimerNode) || this.hashCode() != object.hashCode() ) { return false; } - final TimerNode other = (TimerNode) object; - + TimerNode other = (TimerNode) object; if (calendarNames != null) { if (other.getCalendarNames() == null || other.getCalendarNames().length != calendarNames.length) { return false; @@ -158,8 +161,8 @@ public boolean equals(final Object object) { } } - return Arrays.deepEquals(declarations, other.declarations) && - this.timer.equals(other.timer) && this.leftInput.equals(other.leftInput); + return Arrays.deepEquals( declarations, other.declarations ) && + this.timer.equals(other.timer); } public TimerNodeMemory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) { diff --git a/drools-core/src/main/java/org/drools/core/reteoo/WindowNode.java b/drools-core/src/main/java/org/drools/core/reteoo/WindowNode.java index 966f5a7ca3b..5e24b02eddc 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/WindowNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/WindowNode.java @@ -97,6 +97,8 @@ public WindowNode(final int id, } } epNode = (EntryPointNode) getObjectTypeNode().getParentObjectSource(); + + hashcode = calculateHashCode(); } @SuppressWarnings(""unchecked"") @@ -283,27 +285,23 @@ public String toString() { return ""[WindowNode("" + this.id + "") constraints="" + this.constraints + ""]""; } - public int hashCode() { + private int calculateHashCode() { return this.source.hashCode() * 17 + ((this.constraints != null) ? this.constraints.hashCode() : 0); } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ + @Override public boolean equals(final Object object) { - if (this == object) { - return true; - } + return this == object || + ( internalEquals( object ) && this.source.thisNodeEquals(((WindowNode) object).source) ); + } - if (object == null || !(object instanceof WindowNode)) { + @Override + protected boolean internalEquals( Object object ) { + if ( object == null || !(object instanceof WindowNode) || this.hashCode() != object.hashCode() ) { return false; } - - final WindowNode other = (WindowNode) object; - - return this.source.equals(other.source) && this.constraints.equals(other.constraints) && behavior.equals(other.behavior); + WindowNode other = (WindowNode) object; + return this.constraints.equals(other.constraints) && behavior.equals(other.behavior); } /** diff --git a/drools-core/src/main/java/org/drools/core/rule/From.java b/drools-core/src/main/java/org/drools/core/rule/From.java index 6da1d705294..1453b82ad89 100644 --- a/drools-core/src/main/java/org/drools/core/rule/From.java +++ b/drools-core/src/main/java/org/drools/core/rule/From.java @@ -81,7 +81,12 @@ public boolean equals( Object obj ) { return dataProvider.equals( ((From) obj).dataProvider ); } - public void wire(Object object) { + @Override + public int hashCode() { + return dataProvider.hashCode(); + } + + public void wire( Object object ) { this.dataProvider = KiePolicyHelper.isPolicyEnabled() ? new SafeDataProvider(( DataProvider ) object) : ( DataProvider ) object; } @@ -176,6 +181,16 @@ public void replaceDeclaration(Declaration declaration, Declaration resolved) { public SafeDataProvider clone() { return new SafeDataProvider( delegate.clone() ); } + + @Override + public boolean equals( Object obj ) { + return delegate.equals( obj ); + } + + @Override + public int hashCode() { + return delegate.hashCode(); + } } @Override diff --git a/drools-core/src/main/java/org/drools/core/rule/constraint/XpathConstraint.java b/drools-core/src/main/java/org/drools/core/rule/constraint/XpathConstraint.java index 452cef98ad6..3a877242998 100644 --- a/drools-core/src/main/java/org/drools/core/rule/constraint/XpathConstraint.java +++ b/drools-core/src/main/java/org/drools/core/rule/constraint/XpathConstraint.java @@ -225,6 +225,11 @@ public boolean equals( Object obj ) { return chunk.equals( other.chunk ); } + + @Override + public int hashCode() { + return chunk.hashCode(); + } } public static class XpathChunk implements AcceptsClassObjectType { @@ -422,6 +427,24 @@ public boolean equals( Object obj ) { array == other.array && areNullSafeEquals(declaration, other.declaration); } + + @Override + public int hashCode() { + int hash = 23 * field.hashCode() + 29 * index; + if (declaration != null) { + hash += 31 * declaration.hashCode(); + } + if (iterate) { + hash += 37; + } + if (lazy) { + hash += 41; + } + if (array) { + hash += 43; + } + return hash; + } } public static class XpathDataProvider implements DataProvider { @@ -485,5 +508,14 @@ public boolean equals( Object obj ) { return xpathEvaluator.equals( other.xpathEvaluator ) && areNullSafeEquals(declaration, other.declaration); } + + @Override + public int hashCode() { + int hash = 31 * xpathEvaluator.hashCode(); + if (declaration != null) { + hash += 37 * declaration.hashCode(); + } + return hash; + } } } diff --git a/drools-core/src/main/java/org/drools/core/spi/DataProvider.java b/drools-core/src/main/java/org/drools/core/spi/DataProvider.java index b976b4c2199..8cb11a2c1a5 100644 --- a/drools-core/src/main/java/org/drools/core/spi/DataProvider.java +++ b/drools-core/src/main/java/org/drools/core/spi/DataProvider.java @@ -27,18 +27,18 @@ public interface DataProvider Serializable, Cloneable { - public Declaration[] getRequiredDeclarations(); + Declaration[] getRequiredDeclarations(); - public Object createContext(); + Object createContext(); - public Iterator getResults(Tuple tuple, - InternalWorkingMemory wm, - PropagationContext ctx, - Object providerContext); + Iterator getResults(Tuple tuple, + InternalWorkingMemory wm, + PropagationContext ctx, + Object providerContext); - public DataProvider clone(); + DataProvider clone(); - public void replaceDeclaration(Declaration declaration, - Declaration resolved); + void replaceDeclaration(Declaration declaration, + Declaration resolved); } diff --git a/drools-core/src/main/java/org/drools/core/spi/EvalExpression.java b/drools-core/src/main/java/org/drools/core/spi/EvalExpression.java index bbc78706887..9ce6cc8091a 100644 --- a/drools-core/src/main/java/org/drools/core/spi/EvalExpression.java +++ b/drools-core/src/main/java/org/drools/core/spi/EvalExpression.java @@ -24,15 +24,15 @@ public interface EvalExpression Invoker, Cloneable { - public Object createContext(); + Object createContext(); - public boolean evaluate(Tuple tuple, - Declaration[] requiredDeclarations, - WorkingMemory workingMemory, - Object context ) throws Exception; + boolean evaluate(Tuple tuple, + Declaration[] requiredDeclarations, + WorkingMemory workingMemory, + Object context ) throws Exception; - public void replaceDeclaration(Declaration declaration, - Declaration resolved); - - public EvalExpression clone(); + void replaceDeclaration(Declaration declaration, + Declaration resolved); + + EvalExpression clone(); } diff --git a/drools-core/src/test/java/org/drools/core/reteoo/BaseNodeTest.java b/drools-core/src/test/java/org/drools/core/reteoo/BaseNodeTest.java index 884d1357a1b..d638e1e1af4 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/BaseNodeTest.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/BaseNodeTest.java @@ -78,6 +78,9 @@ public short getType() { return 0; } + @Override + protected boolean internalEquals( Object object ) { + return false; + } } - } diff --git a/drools-core/src/test/java/org/drools/core/reteoo/MockLeftTupleSink.java b/drools-core/src/test/java/org/drools/core/reteoo/MockLeftTupleSink.java index 6c6fd19e4b8..6f4cccb4a54 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/MockLeftTupleSink.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/MockLeftTupleSink.java @@ -207,4 +207,8 @@ public LeftTuple createPeer(LeftTuple original) { return null; } + @Override + protected boolean internalEquals( Object object ) { + return false; + } } diff --git a/drools-core/src/test/java/org/drools/core/reteoo/MockObjectSource.java b/drools-core/src/test/java/org/drools/core/reteoo/MockObjectSource.java index 4ce7aaad652..191708d0a12 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/MockObjectSource.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/MockObjectSource.java @@ -105,6 +105,10 @@ public short getType() { @Override public BitMask calculateDeclaredMask(List settableProperties) { throw new UnsupportedOperationException(); - } + } + @Override + protected boolean internalEquals( Object object ) { + return false; + } } diff --git a/drools-core/src/test/java/org/drools/core/reteoo/MockTupleSource.java b/drools-core/src/test/java/org/drools/core/reteoo/MockTupleSource.java index a084a529a81..c117b1d3a14 100644 --- a/drools-core/src/test/java/org/drools/core/reteoo/MockTupleSource.java +++ b/drools-core/src/test/java/org/drools/core/reteoo/MockTupleSource.java @@ -82,4 +82,8 @@ public LeftTuple createPeer(LeftTuple original) { return null; } + @Override + protected boolean internalEquals( Object object ) { + return false; + } }" ea3cbbfc7cebb2adc6edd8c9aaefd786c7cd05df,ReactiveX-RxJava,ObserveOn and SubscribeOn concurrency unit tests--- these are very rudimentary and may have a determinism problem due to the Thread.sleep-,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java index 59edfade39..119b2ce96e 100644 --- a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java +++ b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java @@ -23,6 +23,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; @@ -395,4 +396,137 @@ public Subscription call(Scheduler scheduler, String state) { } } + @Test + public void testConcurrentOnNextFailsValidation() throws InterruptedException { + + final int count = 10; + final CountDownLatch latch = new CountDownLatch(count); + Observable o = Observable.create(new Func1, Subscription>() { + + @Override + public Subscription call(final Observer observer) { + for (int i = 0; i < count; i++) { + final int v = i; + new Thread(new Runnable() { + + @Override + public void run() { + observer.onNext(""v: "" + v); + + latch.countDown(); + } + }).start(); + } + return Subscriptions.empty(); + } + }); + + ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); + // this should call onNext concurrently + o.subscribe(observer); + + if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { + fail(""timed out""); + } + + if (observer.error.get() == null) { + fail(""We expected error messages due to concurrency""); + } + } + + @Test + public void testObserveOn() throws InterruptedException { + + Observable o = Observable.from(""one"", ""two"", ""three"", ""four"", ""five"", ""six"", ""seven"", ""eight"", ""nine"", ""ten""); + + ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); + + o.observeOn(Schedulers.threadPoolForComputation()).subscribe(observer); + + if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { + fail(""timed out""); + } + + if (observer.error.get() != null) { + observer.error.get().printStackTrace(); + fail(""Error: "" + observer.error.get().getMessage()); + } + } + + @Test + public void testSubscribeOnNestedConcurrency() throws InterruptedException { + + Observable o = Observable.from(""one"", ""two"", ""three"", ""four"", ""five"", ""six"", ""seven"", ""eight"", ""nine"", ""ten"") + .mapMany(new Func1>() { + + @Override + public Observable call(final String v) { + return Observable.create(new Func1, Subscription>() { + + @Override + public Subscription call(final Observer observer) { + observer.onNext(""value_after_map-"" + v); + observer.onCompleted(); + return Subscriptions.empty(); + } + }).subscribeOn(Schedulers.newThread()); // subscribe on a new thread + } + }); + + ConcurrentObserverValidator observer = new ConcurrentObserverValidator(); + + o.subscribe(observer); + + if (!observer.completed.await(3000, TimeUnit.MILLISECONDS)) { + fail(""timed out""); + } + + if (observer.error.get() != null) { + observer.error.get().printStackTrace(); + fail(""Error: "" + observer.error.get().getMessage()); + } + } + + /** + * Used to determine if onNext is being invoked concurrently. + * + * @param + */ + private static class ConcurrentObserverValidator implements Observer { + + final AtomicInteger concurrentCounter = new AtomicInteger(); + final AtomicReference error = new AtomicReference(); + final CountDownLatch completed = new CountDownLatch(1); + + @Override + public void onCompleted() { + completed.countDown(); + } + + @Override + public void onError(Exception e) { + completed.countDown(); + error.set(e); + } + + @Override + public void onNext(T args) { + int count = concurrentCounter.incrementAndGet(); + System.out.println(""ConcurrentObserverValidator.onNext: "" + args); + if (count > 1) { + onError(new RuntimeException(""we should not have concurrent execution of onNext"")); + } + try { + try { + // take some time so other onNext calls could pile up (I haven't yet thought of a way to do this without sleeping) + Thread.sleep(50); + } catch (InterruptedException e) { + // ignore + } + } finally { + concurrentCounter.decrementAndGet(); + } + } + + } }" c04110620c6337b9bf45b6d1d55042630d95f8a5,camel,CAMEL-2930 clean up the codes for wiki--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@962786 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-spring-security/src/test/java/org/apache/camel/component/spring/security/SpringSecurityAuthorizationPolicyTest.java b/components/camel-spring-security/src/test/java/org/apache/camel/component/spring/security/SpringSecurityAuthorizationPolicyTest.java index 2da5530731a56..45a61b700dec5 100644 --- a/components/camel-spring-security/src/test/java/org/apache/camel/component/spring/security/SpringSecurityAuthorizationPolicyTest.java +++ b/components/camel-spring-security/src/test/java/org/apache/camel/component/spring/security/SpringSecurityAuthorizationPolicyTest.java @@ -53,7 +53,6 @@ public void testAuthorizationFailed() throws Exception { sendMessageWithAuthentication(""bob"", ""bobspassword"", ""ROLE_USER""); fail(""we should get the access deny exception here""); } catch (Exception exception) { - exception.printStackTrace(); // the exception should be caused by CamelAuthorizationException assertTrue(""Expect CamelAuthorizationException here"", exception.getCause() instanceof CamelAuthorizationException); } diff --git a/components/camel-spring-security/src/test/resources/org/apache/camel/component/spring/security/commonSecurity.xml b/components/camel-spring-security/src/test/resources/org/apache/camel/component/spring/security/commonSecurity.xml index 7caada7ac0ea2..75dafa6dffadc 100644 --- a/components/camel-spring-security/src/test/resources/org/apache/camel/component/spring/security/commonSecurity.xml +++ b/components/camel-spring-security/src/test/resources/org/apache/camel/component/spring/security/commonSecurity.xml @@ -22,11 +22,7 @@ xsi:schemaLocation=""http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-3.0.3.xsd""> - - - - + http://www.springframework.org/schema/security/spring-security.xsd""> diff --git a/tests/camel-itest/src/test/resources/org/apache/camel/itest/security/commonSecurity.xml b/tests/camel-itest/src/test/resources/org/apache/camel/itest/security/commonSecurity.xml index 3416154b4b678..db549851fcc8b 100644 --- a/tests/camel-itest/src/test/resources/org/apache/camel/itest/security/commonSecurity.xml +++ b/tests/camel-itest/src/test/resources/org/apache/camel/itest/security/commonSecurity.xml @@ -37,8 +37,6 @@ - - " 69c6e80acd16d0073400d78bd0e52caf44ef8f40,ReactiveX-RxJava,"added variance to Action*, too--",p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java index a688d03792..c24a7143f8 100644 --- a/rxjava-core/src/main/java/rx/Observable.java +++ b/rxjava-core/src/main/java/rx/Observable.java @@ -247,7 +247,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer o) { return subscription.wrap(subscribe(new SafeObserver(subscription, o))); } - public Subscription subscribe(final Action1 onNext) { + public Subscription subscribe(final Action1 onNext) { if (onNext == null) { throw new IllegalArgumentException(""onNext can not be null""); } @@ -278,11 +278,11 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1 onNext, Scheduler scheduler) { + public Subscription subscribe(final Action1 onNext, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext); } - public Subscription subscribe(final Action1 onNext, final Action1 onError) { + public Subscription subscribe(final Action1 onNext, final Action1 onError) { if (onNext == null) { throw new IllegalArgumentException(""onNext can not be null""); } @@ -316,11 +316,11 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1 onNext, final Action1 onError, Scheduler scheduler) { + public Subscription subscribe(final Action1 onNext, final Action1 onError, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext, onError); } - public Subscription subscribe(final Action1 onNext, final Action1 onError, final Action0 onComplete) { + public Subscription subscribe(final Action1 onNext, final Action1 onError, final Action0 onComplete) { if (onNext == null) { throw new IllegalArgumentException(""onNext can not be null""); } @@ -357,7 +357,7 @@ public void onNext(T args) { }); } - public Subscription subscribe(final Action1 onNext, final Action1 onError, final Action0 onComplete, Scheduler scheduler) { + public Subscription subscribe(final Action1 onNext, final Action1 onError, final Action0 onComplete, Scheduler scheduler) { return subscribeOn(scheduler).subscribe(onNext, onError, onComplete); } diff --git a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java index 299c2fdc17..fa502843a4 100644 --- a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java +++ b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java @@ -355,7 +355,7 @@ private Subscription protectivelyWrapAndSubscribe(Observer o) { * @throws RuntimeException * if an error occurs */ - public void forEach(final Action1 onNext) { + public void forEach(final Action1 onNext) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference exceptionFromOnError = new AtomicReference(); diff --git a/rxjava-core/src/main/java/rx/util/functions/Functions.java b/rxjava-core/src/main/java/rx/util/functions/Functions.java index 867b47d114..7809b3240d 100644 --- a/rxjava-core/src/main/java/rx/util/functions/Functions.java +++ b/rxjava-core/src/main/java/rx/util/functions/Functions.java @@ -253,7 +253,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static FuncN fromAction(final Action1 f) { + public static FuncN fromAction(final Action1 f) { return new FuncN() { @SuppressWarnings(""unchecked"") @@ -275,7 +275,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static FuncN fromAction(final Action2 f) { + public static FuncN fromAction(final Action2 f) { return new FuncN() { @SuppressWarnings(""unchecked"") @@ -297,7 +297,7 @@ public Void call(Object... args) { * @param f * @return {@link FuncN} */ - public static FuncN fromAction(final Action3 f) { + public static FuncN fromAction(final Action3 f) { return new FuncN() { @SuppressWarnings(""unchecked"")" 4a29e164a8ca222fd8b0d2043e1d44494e84544e,spring-framework,Allow binary messages in StompSubProtocolHandler--Issue: SPR-12301-,a,https://github.com/spring-projects/spring-framework,"diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java index e50637e0f013..d90328715398 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java @@ -49,6 +49,7 @@ import org.springframework.messaging.support.MessageHeaderAccessor; import org.springframework.messaging.support.MessageHeaderInitializer; import org.springframework.util.Assert; +import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketMessage; @@ -186,9 +187,16 @@ public void handleMessageFromClient(WebSocketSession session, List> messages; try { - Assert.isInstanceOf(TextMessage.class, webSocketMessage); - TextMessage textMessage = (TextMessage) webSocketMessage; - ByteBuffer byteBuffer = ByteBuffer.wrap(textMessage.asBytes()); + ByteBuffer byteBuffer; + if (webSocketMessage instanceof TextMessage) { + byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes()); + } + else if (webSocketMessage instanceof BinaryMessage) { + byteBuffer = ((BinaryMessage) webSocketMessage).getPayload(); + } + else { + throw new IllegalArgumentException(""Unexpected WebSocket message type: "" + webSocketMessage); + } BufferingStompDecoder decoder = this.decoders.get(session.getId()); if (decoder == null) {" 96d1fe8096874e6d5b7a0ad85e918756b5cf046a,intellij-community,annotation default value parsing fixed--,c,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java index 13e6715851dc9..6af96063c0ff9 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java @@ -100,11 +100,11 @@ public static GroovyElementType parseDefinitions(PsiBuilder builder, ParserUtils.getToken(builder, GroovyTokenTypes.kDEFAULT); ParserUtils.getToken(builder, GroovyTokenTypes.mNLS); - if (AnnotationArguments.parseAnnotationMemberValueInitializer(builder)) { - defaultValueMarker.done(DEFAULT_ANNOTATION_VALUE); - } else { - defaultValueMarker.error(GroovyBundle.message(""annotation.initializer.expected"")); + if (!AnnotationArguments.parseAnnotationMemberValueInitializer(builder)) { + builder.error(GroovyBundle.message(""annotation.initializer.expected"")); } + + defaultValueMarker.done(DEFAULT_ANNOTATION_VALUE); return DEFAULT_ANNOTATION_MEMBER; }" 261810ebd1015358a2c22376596db450f1b6cbba,camel,CAMEL-3447: Camel uses same media size names as- Java Printer API. Thanks to Torsten for patch.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1051120 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-printer/src/main/java/org/apache/camel/component/printer/MediaSizeAssigner.java b/components/camel-printer/src/main/java/org/apache/camel/component/printer/MediaSizeAssigner.java index a0713902c0e44..b365510dd999e 100644 --- a/components/camel-printer/src/main/java/org/apache/camel/component/printer/MediaSizeAssigner.java +++ b/components/camel-printer/src/main/java/org/apache/camel/component/printer/MediaSizeAssigner.java @@ -22,63 +22,63 @@ public class MediaSizeAssigner { private MediaSizeName mediaSizeName; public MediaSizeName selectMediaSizeNameISO(String size) { - if (size.equalsIgnoreCase(""iso-a0"")) { + if (size.equalsIgnoreCase(""iso_a0"")) { mediaSizeName = MediaSizeName.ISO_A0; - } else if (size.equalsIgnoreCase(""iso-a1"")) { + } else if (size.equalsIgnoreCase(""iso_a1"")) { mediaSizeName = MediaSizeName.ISO_A1; - } else if (size.equalsIgnoreCase(""iso-a2"")) { + } else if (size.equalsIgnoreCase(""iso_a2"")) { mediaSizeName = MediaSizeName.ISO_A2; - } else if (size.equalsIgnoreCase(""iso-a3"")) { + } else if (size.equalsIgnoreCase(""iso_a3"")) { mediaSizeName = MediaSizeName.ISO_A3; - } else if (size.equalsIgnoreCase(""iso-a4"")) { + } else if (size.equalsIgnoreCase(""iso_a4"")) { mediaSizeName = MediaSizeName.ISO_A4; - } else if (size.equalsIgnoreCase(""iso-a5"")) { + } else if (size.equalsIgnoreCase(""iso_a5"")) { mediaSizeName = MediaSizeName.ISO_A5; - } else if (size.equalsIgnoreCase(""iso-a6"")) { + } else if (size.equalsIgnoreCase(""iso_a6"")) { mediaSizeName = MediaSizeName.ISO_A6; - } else if (size.equalsIgnoreCase(""iso-a7"")) { + } else if (size.equalsIgnoreCase(""iso_a7"")) { mediaSizeName = MediaSizeName.ISO_A7; - } else if (size.equalsIgnoreCase(""iso-a8"")) { + } else if (size.equalsIgnoreCase(""iso_a8"")) { mediaSizeName = MediaSizeName.ISO_A8; - } else if (size.equalsIgnoreCase(""iso-a9"")) { + } else if (size.equalsIgnoreCase(""iso_a9"")) { mediaSizeName = MediaSizeName.ISO_A9; - } else if (size.equalsIgnoreCase(""iso-a10"")) { + } else if (size.equalsIgnoreCase(""iso_a10"")) { mediaSizeName = MediaSizeName.ISO_A10; - } else if (size.equalsIgnoreCase(""iso-b0"")) { + } else if (size.equalsIgnoreCase(""iso_b0"")) { mediaSizeName = MediaSizeName.ISO_B0; - } else if (size.equalsIgnoreCase(""iso-b1"")) { + } else if (size.equalsIgnoreCase(""iso_b1"")) { mediaSizeName = MediaSizeName.ISO_B1; - } else if (size.equalsIgnoreCase(""iso-b2"")) { + } else if (size.equalsIgnoreCase(""iso_b2"")) { mediaSizeName = MediaSizeName.ISO_B2; - } else if (size.equalsIgnoreCase(""iso-b3"")) { + } else if (size.equalsIgnoreCase(""iso_b3"")) { mediaSizeName = MediaSizeName.ISO_B3; - } else if (size.equalsIgnoreCase(""iso-b4"")) { + } else if (size.equalsIgnoreCase(""iso_b4"")) { mediaSizeName = MediaSizeName.ISO_B4; - } else if (size.equalsIgnoreCase(""iso-b5"")) { + } else if (size.equalsIgnoreCase(""iso_b5"")) { mediaSizeName = MediaSizeName.ISO_B5; - } else if (size.equalsIgnoreCase(""iso-b6"")) { + } else if (size.equalsIgnoreCase(""iso_b6"")) { mediaSizeName = MediaSizeName.ISO_B6; - } else if (size.equalsIgnoreCase(""iso-b7"")) { + } else if (size.equalsIgnoreCase(""iso_b7"")) { mediaSizeName = MediaSizeName.ISO_B7; - } else if (size.equalsIgnoreCase(""iso-b8"")) { + } else if (size.equalsIgnoreCase(""iso_b8"")) { mediaSizeName = MediaSizeName.ISO_B8; - } else if (size.equalsIgnoreCase(""iso-b9"")) { + } else if (size.equalsIgnoreCase(""iso_b9"")) { mediaSizeName = MediaSizeName.ISO_B9; - } else if (size.equalsIgnoreCase(""iso-b10"")) { + } else if (size.equalsIgnoreCase(""iso_b10"")) { mediaSizeName = MediaSizeName.ISO_B10; - } else if (size.equalsIgnoreCase(""iso-c0"")) { + } else if (size.equalsIgnoreCase(""iso_c0"")) { mediaSizeName = MediaSizeName.ISO_C0; - } else if (size.equalsIgnoreCase(""iso-c1"")) { + } else if (size.equalsIgnoreCase(""iso_c1"")) { mediaSizeName = MediaSizeName.ISO_C1; - } else if (size.equalsIgnoreCase(""iso-c2"")) { + } else if (size.equalsIgnoreCase(""iso_c2"")) { mediaSizeName = MediaSizeName.ISO_C2; - } else if (size.equalsIgnoreCase(""iso-c3"")) { + } else if (size.equalsIgnoreCase(""iso_c3"")) { mediaSizeName = MediaSizeName.ISO_C3; - } else if (size.equalsIgnoreCase(""iso-c4"")) { + } else if (size.equalsIgnoreCase(""iso_c4"")) { mediaSizeName = MediaSizeName.ISO_C4; - } else if (size.equalsIgnoreCase(""iso-c5"")) { + } else if (size.equalsIgnoreCase(""iso_c5"")) { mediaSizeName = MediaSizeName.ISO_C5; - } else if (size.equalsIgnoreCase(""iso-c6"")) { + } else if (size.equalsIgnoreCase(""iso_c6"")) { mediaSizeName = MediaSizeName.ISO_C6; } return mediaSizeName; @@ -86,27 +86,27 @@ public MediaSizeName selectMediaSizeNameISO(String size) { public MediaSizeName selectMediaSizeNameJIS(String size) { - if (size.equalsIgnoreCase(""jis-b0"")) { + if (size.equalsIgnoreCase(""jis_b0"")) { mediaSizeName = MediaSizeName.JIS_B0; - } else if (size.equalsIgnoreCase(""jis-b1"")) { + } else if (size.equalsIgnoreCase(""jis_b1"")) { mediaSizeName = MediaSizeName.JIS_B1; - } else if (size.equalsIgnoreCase(""jis-b2"")) { + } else if (size.equalsIgnoreCase(""jis_b2"")) { mediaSizeName = MediaSizeName.JIS_B2; - } else if (size.equalsIgnoreCase(""jis-b3"")) { + } else if (size.equalsIgnoreCase(""jis_b3"")) { mediaSizeName = MediaSizeName.JIS_B3; - } else if (size.equalsIgnoreCase(""jis-b4"")) { + } else if (size.equalsIgnoreCase(""jis_b4"")) { mediaSizeName = MediaSizeName.JIS_B4; - } else if (size.equalsIgnoreCase(""jis-b5"")) { + } else if (size.equalsIgnoreCase(""jis_b5"")) { mediaSizeName = MediaSizeName.JIS_B5; - } else if (size.equalsIgnoreCase(""jis-b6"")) { + } else if (size.equalsIgnoreCase(""jis_b6"")) { mediaSizeName = MediaSizeName.JIS_B6; - } else if (size.equalsIgnoreCase(""jis-b7"")) { + } else if (size.equalsIgnoreCase(""jis_b7"")) { mediaSizeName = MediaSizeName.JIS_B7; - } else if (size.equalsIgnoreCase(""jis-b8"")) { + } else if (size.equalsIgnoreCase(""jis_b8"")) { mediaSizeName = MediaSizeName.JIS_B8; - } else if (size.equalsIgnoreCase(""jis-b9"")) { + } else if (size.equalsIgnoreCase(""jis_b9"")) { mediaSizeName = MediaSizeName.JIS_B9; - } else if (size.equalsIgnoreCase(""jis-b10"")) { + } else if (size.equalsIgnoreCase(""jis_b10"")) { mediaSizeName = MediaSizeName.JIS_B10; } @@ -114,9 +114,9 @@ public MediaSizeName selectMediaSizeNameJIS(String size) { } public MediaSizeName selectMediaSizeNameNA(String size) { - if (size.equalsIgnoreCase(""na-letter"")) { + if (size.equalsIgnoreCase(""na_letter"")) { mediaSizeName = MediaSizeName.NA_LETTER; - } else if (size.equalsIgnoreCase(""na-legal"")) { + } else if (size.equalsIgnoreCase(""na_legal"")) { mediaSizeName = MediaSizeName.NA_LEGAL; } else if (size.equalsIgnoreCase(""executive"")) { mediaSizeName = MediaSizeName.EXECUTIVE; @@ -130,9 +130,9 @@ public MediaSizeName selectMediaSizeNameNA(String size) { mediaSizeName = MediaSizeName.FOLIO; } else if (size.equalsIgnoreCase(""quarto"")) { mediaSizeName = MediaSizeName.QUARTO; - } else if (size.equalsIgnoreCase(""japanese-postcard"")) { + } else if (size.equalsIgnoreCase(""japanese_postcard"")) { mediaSizeName = MediaSizeName.JAPANESE_POSTCARD; - } else if (size.equalsIgnoreCase(""oufuko-postcard"")) { + } else if (size.equalsIgnoreCase(""oufuko_postcard"")) { mediaSizeName = MediaSizeName.JAPANESE_DOUBLE_POSTCARD; } else if (size.equalsIgnoreCase(""a"")) { mediaSizeName = MediaSizeName.A; @@ -144,41 +144,41 @@ public MediaSizeName selectMediaSizeNameNA(String size) { mediaSizeName = MediaSizeName.D; } else if (size.equalsIgnoreCase(""e"")) { mediaSizeName = MediaSizeName.E; - } else if (size.equalsIgnoreCase(""iso-designated-long"")) { + } else if (size.equalsIgnoreCase(""iso_designated_long"")) { mediaSizeName = MediaSizeName.ISO_DESIGNATED_LONG; - } else if (size.equalsIgnoreCase(""italian-envelope"")) { + } else if (size.equalsIgnoreCase(""italian_envelope"")) { mediaSizeName = MediaSizeName.ITALY_ENVELOPE; - } else if (size.equalsIgnoreCase(""monarch-envelope"")) { + } else if (size.equalsIgnoreCase(""monarch_envelope"")) { mediaSizeName = MediaSizeName.MONARCH_ENVELOPE; - } else if (size.equalsIgnoreCase(""personal-envelope"")) { + } else if (size.equalsIgnoreCase(""personal_envelope"")) { mediaSizeName = MediaSizeName.PERSONAL_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-number-9-envelope"")) { + } else if (size.equalsIgnoreCase(""na_number_9_envelope"")) { mediaSizeName = MediaSizeName.NA_NUMBER_9_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-number-10-envelope"")) { + } else if (size.equalsIgnoreCase(""na_number_10_envelope"")) { mediaSizeName = MediaSizeName.NA_NUMBER_10_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-number-11-envelope"")) { + } else if (size.equalsIgnoreCase(""na_number_11_envelope"")) { mediaSizeName = MediaSizeName.NA_NUMBER_11_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-number-12-envelope"")) { + } else if (size.equalsIgnoreCase(""na_number_12_envelope"")) { mediaSizeName = MediaSizeName.NA_NUMBER_12_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-number-14-envelope"")) { + } else if (size.equalsIgnoreCase(""na_number_14_envelope"")) { mediaSizeName = MediaSizeName.NA_NUMBER_14_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-6x9-envelope"")) { + } else if (size.equalsIgnoreCase(""na_6x9_envelope"")) { mediaSizeName = MediaSizeName.NA_6X9_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-7x9-envelope"")) { + } else if (size.equalsIgnoreCase(""na_7x9_envelope"")) { mediaSizeName = MediaSizeName.NA_7X9_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-9x11-envelope"")) { + } else if (size.equalsIgnoreCase(""na_9x11_envelope"")) { mediaSizeName = MediaSizeName.NA_9X11_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-9x12-envelope"")) { + } else if (size.equalsIgnoreCase(""na_9x12_envelope"")) { mediaSizeName = MediaSizeName.NA_9X12_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-10x13-envelope"")) { + } else if (size.equalsIgnoreCase(""na_10x13_envelope"")) { mediaSizeName = MediaSizeName.NA_10X13_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-10x14-envelope"")) { + } else if (size.equalsIgnoreCase(""na_10x14_envelope"")) { mediaSizeName = MediaSizeName.NA_10X14_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-10x15-envelope"")) { + } else if (size.equalsIgnoreCase(""na_10x15_envelope"")) { mediaSizeName = MediaSizeName.NA_10X15_ENVELOPE; - } else if (size.equalsIgnoreCase(""na-5x7"")) { + } else if (size.equalsIgnoreCase(""na_5x7"")) { mediaSizeName = MediaSizeName.NA_5X7; - } else if (size.equalsIgnoreCase(""na-8x10"")) { + } else if (size.equalsIgnoreCase(""na_8x10"")) { mediaSizeName = MediaSizeName.NA_8X10; } else { mediaSizeName = MediaSizeName.NA_LETTER; @@ -200,9 +200,9 @@ public MediaSizeName selectMediaSizeNameOther(String size) { mediaSizeName = MediaSizeName.FOLIO; } else if (size.equalsIgnoreCase(""quarto"")) { mediaSizeName = MediaSizeName.QUARTO; - } else if (size.equalsIgnoreCase(""japanese-postcard"")) { + } else if (size.equalsIgnoreCase(""japanese_postcard"")) { mediaSizeName = MediaSizeName.JAPANESE_POSTCARD; - } else if (size.equalsIgnoreCase(""oufuko-postcard"")) { + } else if (size.equalsIgnoreCase(""oufuko_postcard"")) { mediaSizeName = MediaSizeName.JAPANESE_DOUBLE_POSTCARD; } else if (size.equalsIgnoreCase(""a"")) { mediaSizeName = MediaSizeName.A; @@ -214,13 +214,13 @@ public MediaSizeName selectMediaSizeNameOther(String size) { mediaSizeName = MediaSizeName.D; } else if (size.equalsIgnoreCase(""e"")) { mediaSizeName = MediaSizeName.E; - } else if (size.equalsIgnoreCase(""iso-designated-long"")) { + } else if (size.equalsIgnoreCase(""iso_designated_long"")) { mediaSizeName = MediaSizeName.ISO_DESIGNATED_LONG; - } else if (size.equalsIgnoreCase(""italian-envelope"")) { + } else if (size.equalsIgnoreCase(""italian_envelope"")) { mediaSizeName = MediaSizeName.ITALY_ENVELOPE; - } else if (size.equalsIgnoreCase(""monarch-envelope"")) { + } else if (size.equalsIgnoreCase(""monarch_envelope"")) { mediaSizeName = MediaSizeName.MONARCH_ENVELOPE; - } else if (size.equalsIgnoreCase(""personal-envelope"")) { + } else if (size.equalsIgnoreCase(""personal_envelope"")) { mediaSizeName = MediaSizeName.PERSONAL_ENVELOPE; }" f0a32dff9b9cf53707758226f6598ab32cca6b06,hbase,HBASE-11370 SSH doesn't need to scan meta if not- using ZK for assignment--,p,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java index 87433d3006f0..66edd66dd601 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/AssignmentManager.java @@ -458,10 +458,10 @@ void joinCluster() throws IOException, // need to be handled. // Scan hbase:meta to build list of existing regions, servers, and assignment - // Returns servers who have not checked in (assumed dead) and their regions - Map> deadServers; + // Returns servers who have not checked in (assumed dead) that some regions + // were assigned to (according to the meta) + Set deadServers = rebuildUserRegions(); - deadServers = rebuildUserRegions(); // This method will assign all user regions if a clean server startup or // it will reconstruct master state and cleanup any leftovers from // previous master process. @@ -489,8 +489,8 @@ void joinCluster() throws IOException, * @throws InterruptedException */ boolean processDeadServersAndRegionsInTransition( - final Map> deadServers) - throws KeeperException, IOException, InterruptedException, CoordinatedStateException { + final Set deadServers) throws KeeperException, + IOException, InterruptedException, CoordinatedStateException { List nodes = ZKUtil.listChildrenNoWatch(watcher, watcher.assignmentZNode); @@ -2702,13 +2702,12 @@ boolean waitUntilNoRegionsInTransition(final long timeout) /** * Rebuild the list of user regions and assignment information. *

- * Returns a map of servers that are not found to be online and the regions - * they were hosting. - * @return map of servers not online to their assigned regions, as stored - * in META + * Returns a set of servers that are not found to be online that hosted + * some regions. + * @return set of servers not online that hosted some regions per meta * @throws IOException */ - Map> rebuildUserRegions() throws + Set rebuildUserRegions() throws IOException, KeeperException, CoordinatedStateException { Set disabledOrEnablingTables = tableStateManager.getTablesInStates( ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.ENABLING); @@ -2722,16 +2721,16 @@ Map> rebuildUserRegions() throws List results = MetaReader.fullScan(this.catalogTracker); // Get any new but slow to checkin region server that joined the cluster Set onlineServers = serverManager.getOnlineServers().keySet(); - // Map of offline servers and their regions to be returned - Map> offlineServers = - new TreeMap>(); + // Set of offline servers to be returned + Set offlineServers = new HashSet(); // Iterate regions in META for (Result result : results) { HRegionInfo regionInfo = HRegionInfo.getHRegionInfo(result); if (regionInfo == null) continue; State state = RegionStateStore.getRegionState(result); + ServerName lastHost = HRegionInfo.getServerName(result); ServerName regionLocation = RegionStateStore.getRegionServer(result); - regionStates.createRegionState(regionInfo, state, regionLocation); + regionStates.createRegionState(regionInfo, state, regionLocation, lastHost); if (!regionStates.isRegionInState(regionInfo, State.OPEN)) { // Region is not open (either offline or in transition), skip continue; @@ -2739,13 +2738,10 @@ Map> rebuildUserRegions() throws TableName tableName = regionInfo.getTable(); if (!onlineServers.contains(regionLocation)) { // Region is located on a server that isn't online - List offlineRegions = offlineServers.get(regionLocation); - if (offlineRegions == null) { - offlineRegions = new ArrayList(1); - offlineServers.put(regionLocation, offlineRegions); + offlineServers.add(regionLocation); + if (useZKForAssignment) { + regionStates.regionOffline(regionInfo); } - regionStates.regionOffline(regionInfo); - offlineRegions.add(regionInfo); } else if (!disabledOrEnablingTables.contains(tableName)) { // Region is being served and on an active server // add only if region not in disabled or enabling table @@ -2838,13 +2834,9 @@ private void recoverTableInEnablingState() * @throws KeeperException */ private void processDeadServersAndRecoverLostRegions( - Map> deadServers) - throws IOException, KeeperException { - if (deadServers != null) { - for (Map.Entry> server: deadServers.entrySet()) { - ServerName serverName = server.getKey(); - // We need to keep such info even if the server is known dead - regionStates.setLastRegionServerOfRegions(serverName, server.getValue()); + Set deadServers) throws IOException, KeeperException { + if (deadServers != null && !deadServers.isEmpty()) { + for (ServerName serverName: deadServers) { if (!serverManager.isServerDead(serverName)) { serverManager.expireServer(serverName); // Let SSH do region re-assign } @@ -3420,7 +3412,7 @@ private String onRegionSplit(ServerName sn, TransitionCode code, } } else if (code == TransitionCode.SPLIT_PONR) { try { - regionStateStore.splitRegion(p, a, b, sn); + regionStates.splitRegion(p, a, b, sn); } catch (IOException ioe) { LOG.info(""Failed to record split region "" + p.getShortNameToLog()); return ""Failed to record the splitting in meta""; @@ -3469,7 +3461,7 @@ private String onRegionMerge(ServerName sn, TransitionCode code, } } else if (code == TransitionCode.MERGE_PONR) { try { - regionStateStore.mergeRegions(p, a, b, sn); + regionStates.mergeRegions(p, a, b, sn); } catch (IOException ioe) { LOG.info(""Failed to record merged region "" + p.getShortNameToLog()); return ""Failed to record the merging in meta""; diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java index 153ffcbf4794..360996508179 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/MasterFileSystem.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.NavigableMap; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -47,14 +46,11 @@ import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.backup.HFileArchiver; -import org.apache.hadoop.hbase.catalog.MetaReader; -import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.exceptions.DeserializationException; import org.apache.hadoop.hbase.fs.HFileSystem; import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.wal.HLog; -import org.apache.hadoop.hbase.regionserver.wal.HLogSplitter; import org.apache.hadoop.hbase.regionserver.wal.HLogUtil; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; @@ -340,30 +336,6 @@ private List getLogDirs(final Set serverNames) throws IOExcept return logDirs; } - /** - * Mark regions in recovering state when distributedLogReplay are set true - * @param serverNames Set of ServerNames to be replayed wals in order to recover changes contained - * in them - * @throws IOException - */ - public void prepareLogReplay(Set serverNames) throws IOException { - if (!this.distributedLogReplay) { - return; - } - // mark regions in recovering state - for (ServerName serverName : serverNames) { - NavigableMap regions = this.getServerUserRegions(serverName); - if (regions == null) { - continue; - } - try { - this.splitLogManager.markRegionsRecoveringInZK(serverName, regions.keySet()); - } catch (KeeperException e) { - throw new IOException(e); - } - } - } - /** * Mark regions in recovering state when distributedLogReplay are set true * @param serverName Failed region server whose wals to be replayed @@ -675,19 +647,6 @@ public HTableDescriptor addColumn(TableName tableName, HColumnDescriptor hcd) return htd; } - private NavigableMap getServerUserRegions(ServerName serverName) - throws IOException { - if (!this.master.isStopped()) { - try { - this.master.getCatalogTracker().waitForMeta(); - return MetaReader.getServerUserRegions(this.master.getCatalogTracker(), serverName); - } catch (InterruptedException e) { - throw (InterruptedIOException)new InterruptedIOException().initCause(e); - } - } - return null; - } - /** * The function is used in SSH to set recovery mode based on configuration after all outstanding * log split tasks drained. diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java index 85677af8cbd6..fd75b3ffa976 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/RegionStates.java @@ -46,6 +46,7 @@ import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** @@ -248,16 +249,22 @@ public void createRegionStates( * no effect, and the original state is returned. */ public RegionState createRegionState(final HRegionInfo hri) { - return createRegionState(hri, null, null); + return createRegionState(hri, null, null, null); } /** * Add a region to RegionStates with the specified state. * If the region is already in RegionStates, this call has * no effect, and the original state is returned. - */ - public synchronized RegionState createRegionState( - final HRegionInfo hri, State newState, ServerName serverName) { + * + * @param hri the region info to create a state for + * @param newState the state to the region in set to + * @param serverName the server the region is transitioning on + * @param lastHost the last server that hosts the region + * @return the current state + */ + public synchronized RegionState createRegionState(final HRegionInfo hri, + State newState, ServerName serverName, ServerName lastHost) { if (newState == null || (newState == State.OPEN && serverName == null)) { newState = State.OFFLINE; } @@ -274,16 +281,24 @@ public synchronized RegionState createRegionState( regionState = new RegionState(hri, newState, serverName); regionStates.put(encodedName, regionState); if (newState == State.OPEN) { - regionAssignments.put(hri, serverName); - lastAssignments.put(encodedName, serverName); - Set regions = serverHoldings.get(serverName); + if (!serverName.equals(lastHost)) { + LOG.warn(""Open region's last host "" + lastHost + + "" should be the same as the current one "" + serverName + + "", ignored the last and used the current one""); + lastHost = serverName; + } + lastAssignments.put(encodedName, lastHost); + regionAssignments.put(hri, lastHost); + } else if (!regionState.isUnassignable()) { + regionsInTransition.put(encodedName, regionState); + } + if (lastHost != null && newState != State.SPLIT) { + Set regions = serverHoldings.get(lastHost); if (regions == null) { regions = new HashSet(); - serverHoldings.put(serverName, regions); + serverHoldings.put(lastHost, regions); } regions.add(hri); - } else if (!regionState.isUnassignable()) { - regionsInTransition.put(encodedName, regionState); } } return regionState; @@ -590,6 +605,31 @@ public void tableDeleted(final TableName tableName) { } } + /** + * Get a copy of all regions assigned to a server + */ + public synchronized Set getServerRegions(ServerName serverName) { + Set regions = serverHoldings.get(serverName); + if (regions == null) return null; + return new HashSet(regions); + } + + /** + * Remove a region from all state maps. + */ + @VisibleForTesting + public synchronized void deleteRegion(final HRegionInfo hri) { + String encodedName = hri.getEncodedName(); + regionsInTransition.remove(encodedName); + regionStates.remove(encodedName); + lastAssignments.remove(encodedName); + ServerName sn = regionAssignments.remove(hri); + if (sn != null) { + Set regions = serverHoldings.get(sn); + regions.remove(hri); + } + } + /** * Checking if a region was assigned to a server which is not online now. * If so, we should hold re-assign this region till SSH has split its hlogs. @@ -651,6 +691,38 @@ synchronized void setLastRegionServerOfRegion( lastAssignments.put(encodedName, serverName); } + void splitRegion(HRegionInfo p, + HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException { + regionStateStore.splitRegion(p, a, b, sn); + synchronized (this) { + // After PONR, split is considered to be done. + // Update server holdings to be aligned with the meta. + Set regions = serverHoldings.get(sn); + if (regions == null) { + throw new IllegalStateException(sn + "" should host some regions""); + } + regions.remove(p); + regions.add(a); + regions.add(b); + } + } + + void mergeRegions(HRegionInfo p, + HRegionInfo a, HRegionInfo b, ServerName sn) throws IOException { + regionStateStore.mergeRegions(p, a, b, sn); + synchronized (this) { + // After PONR, merge is considered to be done. + // Update server holdings to be aligned with the meta. + Set regions = serverHoldings.get(sn); + if (regions == null) { + throw new IllegalStateException(sn + "" should host some regions""); + } + regions.remove(a); + regions.remove(b); + regions.add(p); + } + } + /** * At cluster clean re/start, mark all user regions closed except those of tables * that are excluded, such as disabled/disabling/enabling tables. All user regions @@ -661,8 +733,11 @@ synchronized Map closeAllUserRegions(Set exc Set toBeClosed = new HashSet(regionStates.size()); for(RegionState state: regionStates.values()) { HRegionInfo hri = state.getRegion(); + if (state.isSplit() || hri.isSplit()) { + continue; + } TableName tableName = hri.getTable(); - if (!TableName.META_TABLE_NAME.equals(tableName) && !hri.isSplit() + if (!TableName.META_TABLE_NAME.equals(tableName) && (noExcludeTables || !excludedTables.contains(tableName))) { toBeClosed.add(hri); } @@ -859,19 +934,4 @@ private RegionState updateRegionState(final HRegionInfo hri, } return regionState; } - - /** - * Remove a region from all state maps. - */ - private synchronized void deleteRegion(final HRegionInfo hri) { - String encodedName = hri.getEncodedName(); - regionsInTransition.remove(encodedName); - regionStates.remove(encodedName); - lastAssignments.remove(encodedName); - ServerName sn = regionAssignments.remove(hri); - if (sn != null) { - Set regions = serverHoldings.get(sn); - regions.remove(hri); - } - } } diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java index 50e09add5e66..70648e1c6cb3 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java @@ -46,6 +46,7 @@ import org.apache.hadoop.hbase.master.ServerManager; import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos; import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode; +import org.apache.hadoop.hbase.util.ConfigUtil; import org.apache.hadoop.hbase.zookeeper.ZKAssign; import org.apache.zookeeper.KeeperException; @@ -162,8 +163,16 @@ public void process() throws IOException { this.server.getCatalogTracker().waitForMeta(); // Skip getting user regions if the server is stopped. if (!this.server.isStopped()) { - hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(), - this.serverName).keySet(); + if (ConfigUtil.useZKForAssignment(server.getConfiguration())) { + hris = MetaReader.getServerUserRegions(this.server.getCatalogTracker(), + this.serverName).keySet(); + } else { + // Not using ZK for assignment, regionStates has everything we want + hris = am.getRegionStates().getServerRegions(serverName); + if (hris != null) { + hris.remove(HRegionInfo.FIRST_META_REGIONINFO); + } + } } break; } catch (InterruptedException e) { diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java index 10c23356e7cf..b4a780f6a44c 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java @@ -418,7 +418,7 @@ public void preSplitBeforePONR(ObserverContext ctx AssignmentManager.TEST_SKIP_SPLIT_HANDLING = true; // Now try splitting and it should work. split(hri, server, regionCount); - // Assert the ephemeral node is up in zk. + String path = ZKAssign.getNodeName(TESTING_UTIL.getZooKeeperWatcher(), hri.getEncodedName()); RegionTransition rt = null; @@ -437,7 +437,7 @@ public void preSplitBeforePONR(ObserverContext ctx } LOG.info(""EPHEMERAL NODE BEFORE SERVER ABORT, path="" + path + "", stats="" + stats); assertTrue(rt != null && rt.getEventType().equals(EventType.RS_ZK_REGION_SPLIT)); - // Now crash the server + // Now crash the server, for ZK-less assignment, the server is auto aborted cluster.abortRegionServer(tableRegionIndex); } waitUntilRegionServerDead(); @@ -1329,12 +1329,12 @@ private void printOutRegions(final HRegionServer hrs, final String prefix) private void waitUntilRegionServerDead() throws InterruptedException, InterruptedIOException { // Wait until the master processes the RS shutdown for (int i=0; cluster.getMaster().getClusterStatus(). - getServers().size() == NB_SERVERS && i<100; i++) { + getServers().size() > NB_SERVERS && i<100; i++) { LOG.info(""Waiting on server to go down""); Thread.sleep(100); } assertFalse(""Waited too long for RS to die"", cluster.getMaster().getClusterStatus(). - getServers().size() == NB_SERVERS); + getServers().size() > NB_SERVERS); } private void awaitDaughters(byte[] tableName, int numDaughters) throws InterruptedException { diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java index 0a2e8fd4855a..bd0fbd3347a9 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/TestHBaseFsck.java @@ -1426,6 +1426,12 @@ public void testSplitDaughtersNotInMeta() throws Exception { meta.delete(new Delete(daughters.getSecond().getRegionName())); meta.flushCommits(); + // Remove daughters from regionStates + RegionStates regionStates = TEST_UTIL.getMiniHBaseCluster().getMaster(). + getAssignmentManager().getRegionStates(); + regionStates.deleteRegion(daughters.getFirst()); + regionStates.deleteRegion(daughters.getSecond()); + HBaseFsck hbck = doFsck(conf, false); assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN}); //no LINGERING_SPLIT_PARENT" f3cc4e1607184a92210cf1b699328860d4ba3809,intellij-community,EP for upsource added--,a,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java b/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java index 3cd75ed07b6eb..185883c1cfcd0 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java @@ -17,6 +17,7 @@ public ApplicationEnvironment(CoreApplicationEnvironment appEnvironment) { appEnvironment.registerFileType(PropertiesFileType.INSTANCE, ""properties""); SyntaxHighlighterFactory.LANGUAGE_FACTORY.addExplicitExtension(PropertiesLanguage.INSTANCE, new PropertiesSyntaxHighlighterFactory()); appEnvironment.addExplicitExtension(LanguageParserDefinitions.INSTANCE, PropertiesLanguage.INSTANCE, new PropertiesParserDefinition()); + SyntaxHighlighterFactory.LANGUAGE_FACTORY.addExplicitExtension(PropertiesLanguage.INSTANCE, new PropertiesSyntaxHighlighterFactory()); } }" 8498280b0eb67684a43e65b226895914b5a489ff,kotlin,Debug output removed--,p,https://github.com/JetBrains/kotlin,"diff --git a/idea/src/org/jetbrains/jet/plugin/internal/resolvewindow/ResolveToolwindow.java b/idea/src/org/jetbrains/jet/plugin/internal/resolvewindow/ResolveToolwindow.java index d5dbe042557cc..4e35628ae2b5d 100644 --- a/idea/src/org/jetbrains/jet/plugin/internal/resolvewindow/ResolveToolwindow.java +++ b/idea/src/org/jetbrains/jet/plugin/internal/resolvewindow/ResolveToolwindow.java @@ -43,6 +43,9 @@ import static org.jetbrains.jet.lang.resolve.BindingContext.REFERENCE_TARGET; import static org.jetbrains.jet.lang.resolve.BindingContext.RESOLVED_CALL; +/* + * @author abreslav + */ public class ResolveToolwindow extends JPanel { public static class Factory implements ToolWindowFactory { @Override @@ -111,11 +114,8 @@ private void render(BytecodeToolwindow.Location location, BytecodeToolwindow.Loc } else { PsiElement start = PsiUtilCore.getElementAtOffset(psiFile, startOffset); - System.out.println(""start = "" + start.getText()); PsiElement end = PsiUtilCore.getElementAtOffset(psiFile, endOffset - 1); - System.out.println(""end = "" + end.getText()); elementAtOffset = PsiTreeUtil.findCommonParent(start, end); - System.out.println(""elementAtOffset = "" + elementAtOffset.getText()); } PsiElement currentElement = elementAtOffset;" cadd12fe44f37ce5c40652a800820eca8b09cfb7,intellij-community,Memory leak fixed. Area instances connected to- project and module haven't been disposed at their disposal.--,c,https://github.com/JetBrains/intellij-community,"diff --git a/source/com/intellij/openapi/module/impl/ModuleImpl.java b/source/com/intellij/openapi/module/impl/ModuleImpl.java index fabdb8a958812..ca57298d19b29 100644 --- a/source/com/intellij/openapi/module/impl/ModuleImpl.java +++ b/source/com/intellij/openapi/module/impl/ModuleImpl.java @@ -1,28 +1,30 @@ package com.intellij.openapi.module.impl; -import com.intellij.application.options.PathMacros; import com.intellij.application.options.ExpandMacroToPathMap; import com.intellij.application.options.PathMacroMap; +import com.intellij.application.options.PathMacros; import com.intellij.application.options.ReplacePathToMacroMap; import com.intellij.ide.plugins.PluginDescriptor; import com.intellij.ide.plugins.PluginManager; -import com.intellij.openapi.application.ex.ApplicationEx; -import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.ex.DecodeDefaultsUtil; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.components.impl.ComponentManagerImpl; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.module.*; +import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.module.ModuleComponent; +import com.intellij.openapi.module.ModuleType; +import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.impl.BaseFileConfigurable; import com.intellij.openapi.project.impl.ProjectImpl; -import com.intellij.openapi.util.*; +import com.intellij.openapi.util.Comparing; +import com.intellij.openapi.util.InvalidDataException; +import com.intellij.openapi.util.JDOMUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; -import com.intellij.openapi.extensions.AreaInstance; -import com.intellij.openapi.extensions.Extensions; import com.intellij.pom.PomModel; import com.intellij.pom.PomModule; import com.intellij.pom.core.impl.PomModuleImpl; @@ -180,6 +182,7 @@ public void dispose() { disposeComponents(); myIsDisposed = true; VirtualFileManager.getInstance().removeVirtualFileListener(myVirtualFileListener); + Extensions.disposeArea(this); } public VirtualFile[] getConfigurationFiles() { diff --git a/source/com/intellij/openapi/project/impl/ProjectImpl.java b/source/com/intellij/openapi/project/impl/ProjectImpl.java index dc4d9ac6bfd55..f1ab1313458dc 100644 --- a/source/com/intellij/openapi/project/impl/ProjectImpl.java +++ b/source/com/intellij/openapi/project/impl/ProjectImpl.java @@ -8,14 +8,14 @@ import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.startup.StartupManagerEx; import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.application.ex.ApplicationEx; -import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.application.ex.DecodeDefaultsUtil; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.components.impl.ComponentManagerImpl; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.extensions.AreaInstance; +import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.impl.ModuleImpl; @@ -35,8 +35,6 @@ import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.pointers.VirtualFilePointer; import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager; -import com.intellij.openapi.extensions.Extensions; -import com.intellij.openapi.extensions.AreaInstance; import com.intellij.pom.PomModel; import com.intellij.util.ArrayUtil; import org.jdom.Document; @@ -484,6 +482,7 @@ public void dispose() { } disposeComponents(); + Extensions.disposeArea(this); myDisposed = true; }" 575b48a63e55b5216bf78ecf48621ac8f9f80729,drools,[DROOLS-820] reuse PomModel if already available--,p,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java index bd16aa3b148..b710d0ffb6f 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java @@ -91,6 +91,8 @@ public class KieBuilderImpl private ClassLoader classLoader; + private PomModel pomModel; + public KieBuilderImpl(File file) { this.srcMfs = new DiskResourceReader( file ); } @@ -127,7 +129,7 @@ private PomModel init() { // if pomXML is null it will generate a default, using default ReleaseId // if pomXml is invalid, it assign pomModel to null - PomModel pomModel = buildPomModel(); + PomModel pomModel = getPomModel(); // if kModuleModelXML is null it will generate a default kModule, with a default kbase name // if kModuleModelXML is invalid, it will kModule to null @@ -283,6 +285,7 @@ private ResourceType getResourceType(String fileName) { } void cloneKieModuleForIncrementalCompilation() { + pomModel = null; trgMfs = trgMfs.clone(); init(); kModule = kModule.cloneForIncrementalCompilation( releaseId, kModuleModel, trgMfs ); @@ -412,6 +415,20 @@ public static boolean setDefaultsforEmptyKieModule(KieModuleModel kModuleModel) return false; } + public PomModel getPomModel() { + if (pomModel == null) { + pomModel = buildPomModel(); + } + return pomModel; + } + + /** + * This can be used for performance reason to avoid the recomputation of the pomModel when it is already available + */ + public void setPomModel( PomModel pomModel ) { + this.pomModel = pomModel; + } + private PomModel buildPomModel() { pomXml = getOrGeneratePomXml( srcMfs ); if ( pomXml == null ) { diff --git a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java index ff5b94cc5ef..3c0145ddff3 100644 --- a/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java +++ b/kie-ci/src/main/java/org/kie/scanner/KieModuleMetaDataImpl.java @@ -15,19 +15,16 @@ package org.kie.scanner; +import org.drools.compiler.kie.builder.impl.InternalKieModule; +import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.common.ProjectClassLoader; import org.drools.core.rule.KieModuleMetaInfo; -import org.drools.compiler.kproject.ReleaseIdImpl; -import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.rule.TypeMetaInfo; -import org.kie.api.builder.ReleaseId; -import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.eclipse.aether.artifact.Artifact; +import org.kie.api.builder.ReleaseId; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; @@ -78,10 +75,8 @@ public KieModuleMetaDataImpl(File pomFile) { } public KieModuleMetaDataImpl(InternalKieModule kieModule) { - String pomXmlPath = ((ReleaseIdImpl)kieModule.getReleaseId()).getPomXmlPath(); - InputStream pomStream = new ByteArrayInputStream(kieModule.getBytes(pomXmlPath)); - this.artifactResolver = getResolverFor(pomStream); this.kieModule = kieModule; + this.artifactResolver = getResolverFor( kieModule.getPomModel() ); for (String file : kieModule.getFileNames()) { if (!indexClass(file)) { if (file.endsWith(KieModuleModelImpl.KMODULE_INFO_JAR_PATH)) { @@ -148,9 +143,16 @@ private void init() { if (releaseId != null) { addArtifact(artifactResolver.resolveArtifact(releaseId)); } - for (DependencyDescriptor dep : artifactResolver.getAllDependecies()) { - addArtifact(artifactResolver.resolveArtifact(dep.getReleaseId())); + if ( kieModule != null ) { + for ( ReleaseId releaseId : kieModule.getPomModel().getDependencies() ) { + addArtifact( artifactResolver.resolveArtifact( releaseId ) ); + } + } else { + for ( DependencyDescriptor dep : artifactResolver.getAllDependecies() ) { + addArtifact( artifactResolver.resolveArtifact( dep.getReleaseId() ) ); + } } + packages.addAll(classes.keySet()); packages.addAll(rulesByPackage.keySet()); }" 17cf114310d01eb41045872d12758bff2c452d93,hbase,HBASE-5857 RIT map in RS not getting cleared- while region opening--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1329470 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 408cfbe5664e..025fc53d0e9a 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -2485,9 +2485,9 @@ public RegionOpeningState openRegion(HRegionInfo region, int versionOfOfflineNod } LOG.info(""Received request to open region: "" + region.getRegionNameAsString()); + HTableDescriptor htd = this.tableDescriptors.get(region.getTableName()); this.regionsInTransitionInRS.putIfAbsent(region.getEncodedNameAsBytes(), true); - HTableDescriptor htd = this.tableDescriptors.get(region.getTableName()); // Need to pass the expected version in the constructor. if (region.isRootRegion()) { this.service.submit(new OpenRootHandler(this, this, region, htd, diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java index c8e523f5e56e..8c3f67e1e490 100644 --- a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java +++ b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java @@ -47,9 +47,13 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.Assert.assertFalse; /** * Test open and close of regions using zk. @@ -308,6 +312,30 @@ public void testRSAlreadyProcessingRegion() throws Exception { LOG.info(""Done with testCloseRegion""); } + /** + * If region open fails with IOException in openRegion() while doing tableDescriptors.get() + * the region should not add into regionsInTransitionInRS map + * @throws Exception + */ + @Test + public void testRegionOpenFailsDueToIOException() throws Exception { + HRegionInfo REGIONINFO = new HRegionInfo(Bytes.toBytes(""t""), + HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW); + HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(0); + TableDescriptors htd = Mockito.mock(TableDescriptors.class); + Object orizinalState = Whitebox.getInternalState(regionServer,""tableDescriptors""); + Whitebox.setInternalState(regionServer, ""tableDescriptors"", htd); + Mockito.doThrow(new IOException()).when(htd).get((byte[]) Mockito.any()); + try { + regionServer.openRegion(REGIONINFO); + fail(""It should throw IOException ""); + } catch (IOException e) { + } + Whitebox.setInternalState(regionServer, ""tableDescriptors"", orizinalState); + assertFalse(""Region should not be in RIT"", + regionServer.getRegionsInTransitionInRS().containsKey(REGIONINFO.getEncodedNameAsBytes())); + } + private static void waitUntilAllRegionsAssigned() throws IOException { HTable meta = new HTable(TEST_UTIL.getConfiguration()," 84ff885f72d1ec8228407b6cdc9c09d342b5a0dc,kotlin,Constructor body generation extracted as a method- (+ migrated to Printer for convenience)--,p,https://github.com/JetBrains/kotlin,"diff --git a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java index 6fc139585610e..a0af388cecfbc 100644 --- a/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java +++ b/injector-generator/src/org/jetbrains/jet/di/DependencyInjectorGenerator.java @@ -16,15 +16,13 @@ package org.jetbrains.jet.di; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; +import com.google.common.collect.*; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.utils.Printer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @@ -281,70 +279,80 @@ private static DiType getEffectiveFieldType(Field field) { } private void generateConstructor(String injectorClassName, PrintStream out) { - String indent = "" ""; + Printer p = new Printer(out); + p.pushIndent(); // Constructor parameters if (parameters.isEmpty()) { - out.println("" public "" + injectorClassName + ""() {""); + p.println(""public "", injectorClassName, ""() {""); } else { - out.println("" public "" + injectorClassName + ""(""); + p.println(""public "", injectorClassName, ""(""); + p.pushIndent(); for (Iterator iterator = parameters.iterator(); iterator.hasNext(); ) { Parameter parameter = iterator.next(); - out.print(indent); + p.print(); // indent if (parameter.isRequired()) { - out.print(""@NotNull ""); + p.printWithNoIndent(""@NotNull ""); } - out.print(parameter.getType().getSimpleName() + "" "" + parameter.getName()); + p.printWithNoIndent(parameter.getType().getSimpleName(), "" "", parameter.getName()); if (iterator.hasNext()) { - out.println("",""); + p.printlnWithNoIndent("",""); } } - out.println(); - out.println("" ) {""); + p.printlnWithNoIndent(); + p.popIndent(); + p.println("") {""); } + p.pushIndent(); if (lazy) { // Remember parameters for (Parameter parameter : parameters) { - out.println(indent + ""this."" + parameter.getField().getName() + "" = "" + parameter.getName() + "";""); + p.println(""this."", parameter.getField().getName(), "" = "", parameter.getName(), "";""); } } else { - // Initialize fields - for (Field field : fields) { - //if (!backsParameter.contains(field) || field.isPublic()) { - String prefix = ""this.""; - out.println(indent + prefix + field.getName() + "" = "" + field.getInitialization().renderAsCode() + "";""); - //} - } - out.println(); + generateInitializingCode(p, fields); + } - // Call setters - for (Field field : fields) { - for (SetterDependency dependency : field.getDependencies()) { - String prefix = field.isPublic() ? ""this."" : """"; - out.println(indent + prefix + dependency.getDependent().getName() + ""."" + dependency.getSetterName() + ""("" + dependency.getDependency().getName() + "");""); - } - if (!field.getDependencies().isEmpty()) { - out.println(); - } - } + p.popIndent(); + p.println(""}""); + } - // call @PostConstruct - for (Field field : fields) { - // TODO: type of field may be different from type of object - List postConstructMethods = getPostConstructMethods(getEffectiveFieldType(field).getClazz()); - for (Method postConstruct : postConstructMethods) { - out.println(indent + field.getName() + ""."" + postConstruct.getName() + ""();""); - } - if (postConstructMethods.size() > 0) { - out.println(); - } + private static void generateInitializingCode(@NotNull Printer p, @NotNull Collection fields) { + // Initialize fields + for (Field field : fields) { + //if (!backsParameter.contains(field) || field.isPublic()) { + p.println(""this."", field.getName(), "" = "", field.getInitialization().renderAsCode(), "";""); + //} + } + p.printlnWithNoIndent(); + + // Call setters + for (Field field : fields) { + for (SetterDependency dependency : field.getDependencies()) { + String prefix = field.isPublic() ? ""this."" : """"; + String dependencyName = dependency.getDependency().getName(); + String dependentName = dependency.getDependent().getName(); + p.println(prefix, dependentName, ""."", dependency.getSetterName(), ""("", dependencyName, "");""); + } + if (!field.getDependencies().isEmpty()) { + p.printlnWithNoIndent(); } } - out.println("" }""); + // call @PostConstruct + for (Field field : fields) { + // TODO: type of field may be different from type of object + List postConstructMethods = getPostConstructMethods(getEffectiveFieldType(field).getClazz()); + for (Method postConstruct : postConstructMethods) { + p.println(field.getName(), ""."", postConstruct.getName(), ""();""); + } + if (postConstructMethods.size() > 0) { + p.printlnWithNoIndent(); + } + } } private static List getPostConstructMethods(Class clazz) {" ed110ba2625abe4a6c641f1f7fb335c9cac33b20,intellij-community,IDEA-114890 Find Jar On The Web: Looking For- Libraries progress can't ve cancelled--,c,https://github.com/JetBrains/intellij-community,"diff --git a/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java b/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java index 8fdf05c0a6204..c4a031e702b50 100644 --- a/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java +++ b/java/java-impl/src/com/intellij/jarFinder/FindJarFix.java @@ -154,7 +154,7 @@ public void run() { @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); - runnable.run(); + runUncanceledRunnableWithProgress(runnable, indicator); } @Override @@ -240,6 +240,21 @@ private void initiateDownload(String url, String jarName) { } } + private static void runUncanceledRunnableWithProgress(Runnable run, ProgressIndicator indicator) { + Thread t = new Thread(run, ""FindJar download thread""); + t.start(); + + try { + while (t.isAlive()) { + t.join(500); + indicator.checkCanceled(); + } + } + catch (InterruptedException e) { + indicator.checkCanceled(); + } + } + private void downloadJar(String jarUrl, String jarName) { final Project project = myModule.getProject(); final String dirPath = PropertiesComponent.getInstance(project).getValue(""findjar.last.used.dir"");" f4b4b023a3983531baf68542f35a318248dee6fa,kotlin,Introduce Variable: Support extraction of string- template fragments -KT-2089 Fixed--,a,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt index 50d6a8e82cb86..5df97b4d69fd5 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/KtPsiFactory.kt @@ -55,15 +55,25 @@ public class KtPsiFactory(private val project: Project) { return (createExpression(""a?.b"") as KtSafeQualifiedExpression).getOperationTokenNode() } - public fun createExpression(text: String): KtExpression { + private fun doCreateExpression(text: String): KtExpression { //TODO: '\n' below if important - some strange code indenting problems appear without it val expression = createProperty(""val x =\n$text"").getInitializer() ?: error(""Failed to create expression from text: '$text'"") + return expression + } + + public fun createExpression(text: String): KtExpression { + val expression = doCreateExpression(text) assert(expression.getText() == text) { ""Failed to create expression from text: '$text', resulting expression's text was: '${expression.getText()}'"" } return expression } + public fun createExpressionIfPossible(text: String): KtExpression? { + val expression = doCreateExpression(text) + return if (expression.getText() == text) expression else null + } + public fun createClassLiteral(className: String): KtClassLiteralExpression = createExpression(""$className::class"") as KtClassLiteralExpression @@ -291,6 +301,8 @@ public class KtPsiFactory(private val project: Project) { return stringTemplateExpression.getEntries()[0] as KtStringTemplateEntryWithExpression } + public fun createStringTemplate(content: String) = createExpression(""\""$content\"""") as KtStringTemplateExpression + public fun createPackageDirective(fqName: FqName): KtPackageDirective { return createFile(""package ${fqName.asString()}"").getPackageDirective()!! } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt index ddf33fe7354dc..e0b5338003d8e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/psiUtils.kt @@ -138,6 +138,8 @@ public fun PsiElement.getNextSiblingIgnoringWhitespaceAndComments(): PsiElement? return siblings(withItself = false).filter { it !is PsiWhiteSpace && it !is PsiComment }.firstOrNull() } +inline public fun T.nextSiblingOfSameType() = PsiTreeUtil.getNextSiblingOfType(this, T::class.java) + public fun PsiElement?.isAncestor(element: PsiElement, strict: Boolean = false): Boolean { return PsiTreeUtil.isAncestor(this, element, strict) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java index e5aded5d0bfd1..342ad7b094fc9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringUtil.java @@ -45,8 +45,8 @@ import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor; import org.jetbrains.kotlin.idea.KotlinBundle; import org.jetbrains.kotlin.idea.caches.resolve.ResolutionUtils; -import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils; import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde; +import org.jetbrains.kotlin.idea.refactoring.introduce.IntroduceUtilKt; import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers; import org.jetbrains.kotlin.idea.util.string.StringUtilKt; import org.jetbrains.kotlin.psi.*; @@ -489,7 +489,7 @@ public static String getExpressionShortText(@NotNull KtElement element) { //todo private static KtExpression findExpression( @NotNull KtFile file, int startOffset, int endOffset, boolean failOnNoExpression ) throws IntroduceRefactoringException { - KtExpression element = CodeInsightUtils.findExpression(file, startOffset, endOffset); + KtExpression element = IntroduceUtilKt.findExpressionOrStringFragment(file, startOffset, endOffset); if (element == null) { //todo: if it's infix expression => add (), then commit document then return new created expression diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt new file mode 100644 index 0000000000000..199d1db889d58 --- /dev/null +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt @@ -0,0 +1,99 @@ +/* + * Copyright 2010-2015 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.kotlin.idea.refactoring.introduce + +import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange +import com.intellij.psi.PsiElement +import org.jetbrains.kotlin.builtins.KotlinBuiltIns +import org.jetbrains.kotlin.idea.analysis.analyzeInContext +import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade +import org.jetbrains.kotlin.idea.util.getResolutionScope +import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.psiUtil.endOffset +import org.jetbrains.kotlin.psi.psiUtil.nextSiblingOfSameType +import org.jetbrains.kotlin.psi.psiUtil.startOffset +import org.jetbrains.kotlin.resolve.DelegatingBindingTrace +import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator +import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.TypeUtils + +class ExtractableSubstringInfo( + val startEntry: KtStringTemplateEntry, + val endEntry: KtStringTemplateEntry, + val prefix: String, + val suffix: String, + type: KotlinType? = null +) { + private fun guessLiteralType(literal: String): KotlinType { + val facade = template.getResolutionFacade() + val builtIns = facade.moduleDescriptor.builtIns + val stringType = builtIns.stringType + + if (startEntry != endEntry || startEntry !is KtLiteralStringTemplateEntry) return stringType + + val expr = KtPsiFactory(startEntry).createExpressionIfPossible(literal) ?: return stringType + + val context = facade.analyze(template, BodyResolveMode.PARTIAL) + val scope = template.getResolutionScope(context, facade) + + val tempContext = expr.analyzeInContext(scope, template) + val trace = DelegatingBindingTrace(tempContext, ""Evaluate '$literal'"") + val value = ConstantExpressionEvaluator(builtIns).evaluateExpression(expr, trace) + if (value == null || value.isError) return stringType + + return value.toConstantValue(TypeUtils.NO_EXPECTED_TYPE).type + } + + val template: KtStringTemplateExpression = startEntry.parent as KtStringTemplateExpression + + val content = with(entries.map { it.text }.joinToString(separator = """")) { substring(prefix.length, length - suffix.length) } + + val type = type ?: guessLiteralType(content) + + val contentRange: TextRange + get() = TextRange(startEntry.startOffset + prefix.length, endEntry.endOffset - suffix.length) + + val entries: Sequence + get() = sequence(startEntry) { if (it != endEntry) it.nextSiblingOfSameType() else null } + + fun createExpression(): KtExpression { + val quote = template.firstChild.text + val literalValue = if (KotlinBuiltIns.isString(type)) ""$quote$content$quote"" else content + return KtPsiFactory(startEntry).createExpression(literalValue).apply { extractableSubstringInfo = this@ExtractableSubstringInfo } + } + + fun copy(newTemplate: KtStringTemplateExpression): ExtractableSubstringInfo { + val oldEntries = template.entries + val newEntries = newTemplate.entries + val startIndex = oldEntries.indexOf(startEntry) + val endIndex = oldEntries.indexOf(endEntry) + if (startIndex < 0 || startIndex >= newEntries.size || endIndex < 0 || endIndex >= newEntries.size) { + throw AssertionError(""Old template($startIndex..$endIndex): ${template.text}, new template: ${newTemplate.text}"") + } + return ExtractableSubstringInfo(newEntries[startIndex], newEntries[endIndex], prefix, suffix, type) + } +} + +var KtExpression.extractableSubstringInfo: ExtractableSubstringInfo? by UserDataProperty(Key.create(""EXTRACTED_SUBSTRING_INFO"")) + +val KtExpression.substringContextOrThis: KtExpression + get() = extractableSubstringInfo?.template ?: this + +val PsiElement.substringContextOrThis: PsiElement + get() = (this as? KtExpression)?.extractableSubstringInfo?.template ?: this \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt index b8f2307c7f409..a40368b276ef3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceUtil.kt @@ -20,17 +20,16 @@ import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils import org.jetbrains.kotlin.idea.core.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringBundle import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtil -import org.jetbrains.kotlin.psi.KtExpression -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType -import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType -import org.jetbrains.kotlin.psi.psiUtil.getOutermostParentContainedIn +import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange +import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.psiUtil.* fun showErrorHint(project: Project, editor: Editor, message: String, title: String) { CodeInsightUtils.showErrorHint(project, editor, message, title, null) @@ -48,8 +47,9 @@ fun selectElementsWithTargetSibling( continuation: (elements: List, targetSibling: PsiElement) -> Unit ) { fun onSelectionComplete(elements: List, targetContainer: PsiElement) { - val parent = PsiTreeUtil.findCommonParent(elements) - ?: throw AssertionError(""Should have at least one parent: ${elements.joinToString(""\n"")}"") + val physicalElements = elements.map { it.substringContextOrThis } + val parent = PsiTreeUtil.findCommonParent(physicalElements) + ?: throw AssertionError(""Should have at least one parent: ${physicalElements.joinToString(""\n"")}"") if (parent == targetContainer) { continuation(elements, elements.first()) @@ -80,8 +80,9 @@ fun selectElementsWithTargetParent( } fun selectTargetContainer(elements: List) { - val parent = PsiTreeUtil.findCommonParent(elements) - ?: throw AssertionError(""Should have at least one parent: ${elements.joinToString(""\n"")}"") + val physicalElements = elements.map { it.substringContextOrThis } + val parent = PsiTreeUtil.findCommonParent(physicalElements) + ?: throw AssertionError(""Should have at least one parent: ${physicalElements.joinToString(""\n"")}"") val containers = getContainers(elements, parent) if (containers.isEmpty()) { @@ -147,3 +148,29 @@ fun PsiElement.findExpressionsByCopyableDataAndClearIt(key: Key): List< results.forEach { it.putCopyableUserData(key, null) } return results } + +fun findExpressionOrStringFragment(file: KtFile, startOffset: Int, endOffset: Int): KtExpression? { + CodeInsightUtils.findExpression(file, startOffset, endOffset)?.let { return it } + + val entry1 = file.findElementAt(startOffset)?.getNonStrictParentOfType() ?: return null + val entry2 = file.findElementAt(endOffset - 1)?.getNonStrictParentOfType() ?: return null + + if (entry1 == entry2 && entry1 is KtStringTemplateEntryWithExpression) return entry1.expression + + val stringTemplate = entry1.parent as? KtStringTemplateExpression ?: return null + if (entry2.parent != stringTemplate) return null + + val templateOffset = stringTemplate.startOffset + if (stringTemplate.getContentRange().equalsToRange(startOffset - templateOffset, endOffset - templateOffset)) return stringTemplate + + val prefixOffset = startOffset - entry1.startOffset + if (entry1 !is KtLiteralStringTemplateEntry && prefixOffset > 0) return null + + val suffixOffset = endOffset - entry2.startOffset + if (entry2 !is KtLiteralStringTemplateEntry && suffixOffset < entry2.textLength) return null + + val prefix = entry1.text.substring(0, prefixOffset) + val suffix = entry2.text.substring(suffixOffset) + + return ExtractableSubstringInfo(entry1, entry2, prefix, suffix).createExpression() +} \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt index 148341563a763..e4cfdf65b19a9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt @@ -21,6 +21,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key +import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile @@ -45,10 +46,7 @@ import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.intentions.RemoveCurlyBracesFromTemplateIntention import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringBundle import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringUtil -import org.jetbrains.kotlin.idea.refactoring.introduce.KotlinIntroduceHandlerBase -import org.jetbrains.kotlin.idea.refactoring.introduce.findElementByCopyableDataAndClearIt -import org.jetbrains.kotlin.idea.refactoring.introduce.findExpressionByCopyableDataAndClearIt -import org.jetbrains.kotlin.idea.refactoring.introduce.findExpressionsByCopyableDataAndClearIt +import org.jetbrains.kotlin.idea.refactoring.introduce.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.ShortenReferences @@ -105,17 +103,34 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { return newContainer.findElementAt(offset)?.parentsWithSelf?.firstOrNull { (it as? KtExpression)?.text == text } } - private fun replaceExpression(replace: KtExpression, addToReferences: Boolean): KtExpression { - val isActualExpression = expression == replace + private fun replaceExpression(expressionToReplace: KtExpression, addToReferences: Boolean): KtExpression { + val isActualExpression = expression == expressionToReplace val replacement = psiFactory.createExpression(nameSuggestion) - var result = if (replace.isFunctionLiteralOutsideParentheses()) { - val functionLiteralArgument = replace.getStrictParentOfType()!! + val substringInfo = expressionToReplace.extractableSubstringInfo + var result = if (expressionToReplace.isFunctionLiteralOutsideParentheses()) { + val functionLiteralArgument = expressionToReplace.getStrictParentOfType()!! val newCallExpression = functionLiteralArgument.moveInsideParenthesesAndReplaceWith(replacement, bindingContext) newCallExpression.valueArguments.last().getArgumentExpression()!! } + else if (substringInfo != null) { + with(substringInfo) { + val parent = startEntry.parent + + psiFactory.createStringTemplate(prefix).entries.singleOrNull()?.let { parent.addBefore(it, startEntry) } + + val refEntry = psiFactory.createBlockStringTemplateEntry(replacement) + val addedRefEntry = parent.addBefore(refEntry, startEntry) as KtStringTemplateEntryWithExpression + + psiFactory.createStringTemplate(suffix).entries.singleOrNull()?.let { parent.addAfter(it, endEntry) } + + parent.deleteChildRange(startEntry, endEntry) + + addedRefEntry.expression!! + } + } else { - replace.replace(replacement) as KtExpression + expressionToReplace.replace(replacement) as KtExpression } val parent = result.parent @@ -279,7 +294,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { expression.putCopyableUserData(EXPRESSION_KEY, true) for (replace in allReplaces) { - replace.putCopyableUserData(REPLACE_KEY, true) + replace.substringContextOrThis.putCopyableUserData(REPLACE_KEY, true) } commonParent.putCopyableUserData(COMMON_PARENT_KEY, true) @@ -290,7 +305,12 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { val newExpression = newCommonContainer.findExpressionByCopyableDataAndClearIt(EXPRESSION_KEY) val newCommonParent = newCommonContainer.findElementByCopyableDataAndClearIt(COMMON_PARENT_KEY) - val newAllReplaces = newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY) + val newAllReplaces = (allReplaces zip newCommonContainer.findExpressionsByCopyableDataAndClearIt(REPLACE_KEY)).map { + val (originalReplace, newReplace) = it + originalReplace.extractableSubstringInfo?.let { + originalReplace.apply { extractableSubstringInfo = it.copy(newReplace as KtStringTemplateExpression) } + } ?: newReplace + } runRefactoring(newExpression, newCommonContainer, newCommonParent, newAllReplaces) } @@ -299,7 +319,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List): PsiElement? { if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer } - val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> Math.min(offset, expr.startOffset) } + val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> Math.min(offset, expr.substringContextOrThis.startOffset) } return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) } ?: return null } @@ -376,38 +396,42 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { occurrencesToReplace: List?, onNonInteractiveFinish: ((KtProperty) -> Unit)? ) { - val parent = expression.parent + val substringInfo = expression.extractableSubstringInfo + val physicalExpression = expression.substringContextOrThis + + val parent = physicalExpression.parent when { parent is KtQualifiedExpression -> { - if (parent.receiverExpression != expression) { + if (parent.receiverExpression != physicalExpression) { return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.no.expression"")) } } - expression is KtStatementExpression -> + physicalExpression is KtStatementExpression -> return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.no.expression"")) - parent is KtOperationExpression && parent.operationReference == expression -> + parent is KtOperationExpression && parent.operationReference == physicalExpression -> return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.no.expression"")) } - PsiTreeUtil.getNonStrictParentOfType(expression, + PsiTreeUtil.getNonStrictParentOfType(physicalExpression, KtTypeReference::class.java, KtConstructorCalleeExpression::class.java, KtSuperExpression::class.java)?.let { return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.no.container"")) } - val expressionType = bindingContext.getType(expression) //can be null or error type - val scope = expression.getResolutionScope(bindingContext, resolutionFacade) - val dataFlowInfo = bindingContext.getDataFlowInfo(expression) + val expressionType = substringInfo?.type ?: bindingContext.getType(physicalExpression) //can be null or error type + val scope = physicalExpression.getResolutionScope(bindingContext, resolutionFacade) + val dataFlowInfo = bindingContext.getDataFlowInfo(physicalExpression) val bindingTrace = ObservableBindingTrace(BindingTraceContext()) - val typeNoExpectedType = expression.computeTypeInfoInContext(scope, expression, bindingTrace, dataFlowInfo).type + val typeNoExpectedType = substringInfo?.type + ?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type val noTypeInference = expressionType != null && typeNoExpectedType != null && !KotlinTypeChecker.DEFAULT.equalTypes(expressionType, typeNoExpectedType) - if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, expression) != null) { + if (expressionType == null && bindingContext.get(BindingContext.QUALIFIER, physicalExpression) != null) { return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.package.expression"")) } @@ -426,9 +450,11 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { OccurrencesChooser.ReplaceChoice.ALL -> allOccurrences else -> listOf(expression) } - val replaceOccurrence = expression.shouldReplaceOccurrence(bindingContext, container) || allReplaces.size > 1 + val replaceOccurrence = substringInfo != null + || expression.shouldReplaceOccurrence(bindingContext, container) + || allReplaces.size > 1 - val commonParent = PsiTreeUtil.findCommonParent(allReplaces) as KtElement + val commonParent = PsiTreeUtil.findCommonParent(allReplaces.map { it.substringContextOrThis }) as KtElement var commonContainer = commonParent.getContainer()!! if (commonContainer != container && container.isAncestor(commonContainer, true)) { commonContainer = container @@ -439,7 +465,11 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { calculateAnchor(commonParent, commonContainer, allReplaces), NewDeclarationNameValidator.Target.VARIABLES ) - val suggestedNames = KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, ""value"") + val suggestedNames = KotlinNameSuggester.suggestNamesByExpressionAndType(expression, + substringInfo?.type, + bindingContext, + validator, + ""value"") val introduceVariableContext = IntroduceVariableContext( expression, suggestedNames.iterator().next(), allReplaces, commonContainer, commonParent, replaceOccurrence, noTypeInference, expressionType, bindingContext, resolutionFacade @@ -477,7 +507,12 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { } if (isInplaceAvailable && occurrencesToReplace == null) { - OccurrencesChooser.simpleChooser(editor).showChooser(expression, allOccurrences, callback) + val chooser = object: OccurrencesChooser(editor) { + override fun getOccurrenceRange(occurrence: KtExpression): TextRange? { + return occurrence.extractableSubstringInfo?.contentRange ?: occurrence.textRange + } + } + chooser.showChooser(expression, allOccurrences, callback) } else { callback.pass(OccurrencesChooser.ReplaceChoice.ALL) @@ -494,13 +529,17 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { resolutionFacade: ResolutionFacade, originalContext: BindingContext ): List> { - val file = getContainingKtFile() + val physicalExpression = substringContextOrThis + val contentRange = extractableSubstringInfo?.contentRange - val references = collectDescendantsOfType() + val file = physicalExpression.getContainingKtFile() + + val references = physicalExpression + .collectDescendantsOfType { contentRange == null || contentRange.contains(it.textRange) } fun isResolvableNextTo(neighbour: KtExpression): Boolean { val scope = neighbour.getResolutionScope(originalContext, resolutionFacade) - val newContext = analyzeInContext(scope, neighbour) + val newContext = physicalExpression.analyzeInContext(scope, neighbour) val project = file.project return references.all { val originalDescriptor = originalContext[BindingContext.REFERENCE_TARGET, it] @@ -515,8 +554,8 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { } } - val firstContainer = getContainer() ?: return emptyList() - val firstOccurrenceContainer = getOccurrenceContainer() ?: return emptyList() + val firstContainer = physicalExpression.getContainer() ?: return emptyList() + val firstOccurrenceContainer = physicalExpression.getOccurrenceContainer() ?: return emptyList() val containers = SmartList(firstContainer) val occurrenceContainers = SmartList(firstOccurrenceContainer) @@ -554,8 +593,10 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { val expression = expressionToExtract?.let { KtPsiUtil.safeDeparenthesize(it) } ?: return showErrorHint(project, editor, KotlinRefactoringBundle.message(""cannot.refactor.no.expression"")) - val resolutionFacade = expression.getResolutionFacade() - val bindingContext = resolutionFacade.analyze(expression, BodyResolveMode.FULL) + val physicalExpression = expression.substringContextOrThis + + val resolutionFacade = physicalExpression.getResolutionFacade() + val bindingContext = resolutionFacade.analyze(physicalExpression, BodyResolveMode.FULL) fun runWithChosenContainers(container: KtElement, occurrenceContainer: KtElement) { doRefactoring(project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext, occurrencesToReplace, onNonInteractiveFinish) @@ -580,6 +621,7 @@ object KotlinIntroduceVariableHandler : KotlinIntroduceHandlerBase() { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { if (file !is KtFile) return + try { KotlinRefactoringUtil.selectExpression(editor, file) { doRefactoring(project, editor, it, null, null) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt index 8a2eea70be839..0539b523418dd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt @@ -23,6 +23,8 @@ import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody +import org.jetbrains.kotlin.idea.refactoring.introduce.ExtractableSubstringInfo +import org.jetbrains.kotlin.idea.refactoring.introduce.extractableSubstringInfo import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiRange.Empty import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.* @@ -60,7 +62,7 @@ public interface UnificationResult { override fun and(other: Status): Status = this }; - public abstract fun and(other: Status): Status + public abstract infix fun and(other: Status): Status } object Unmatched : UnificationResult { @@ -111,6 +113,7 @@ public class KotlinPsiUnifier( val declarationPatternsToTargets = MultiMap() val weakMatches = HashMap() var checkEquivalence: Boolean = false + var targetSubstringInfo: ExtractableSubstringInfo? = null private fun KotlinPsiRange.getBindingContext(): BindingContext { val element = (this as? KotlinPsiRange.ListRange)?.startElement as? KtElement @@ -702,7 +705,73 @@ public class KotlinPsiUnifier( return targetElementType != null && KotlinTypeChecker.DEFAULT.isSubtypeOf(targetElementType, parameter.expectedType) } + private fun doUnifyStringTemplateFragments(target: KtStringTemplateExpression, pattern: ExtractableSubstringInfo): Status { + val prefixLength = pattern.prefix.length + val suffixLength = pattern.suffix.length + val targetEntries = target.entries + val patternEntries = pattern.entries.toList() + for ((index, targetEntry) in targetEntries.withIndex()) { + if (index + patternEntries.size > targetEntries.size) return UNMATCHED + + val targetEntryText = targetEntry.text + + if (pattern.startEntry == pattern.endEntry && (prefixLength > 0 || suffixLength > 0)) { + if (targetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = with(pattern.startEntry.text) { substring(prefixLength, length - suffixLength) } + val i = targetEntryText.indexOf(patternText) + if (i < 0) continue + val targetPrefix = targetEntryText.substring(0, i) + val targetSuffix = targetEntryText.substring(i + patternText.length) + targetSubstringInfo = ExtractableSubstringInfo(targetEntry, targetEntry, targetPrefix, targetSuffix, pattern.type) + return MATCHED + } + + val matchStartByText = pattern.startEntry is KtLiteralStringTemplateEntry + val matchEndByText = pattern.endEntry is KtLiteralStringTemplateEntry + + val targetPrefix = if (matchStartByText) { + if (targetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = pattern.startEntry.text.substring(prefixLength) + if (!targetEntryText.endsWith(patternText)) continue + targetEntryText.substring(0, targetEntryText.length - patternText.length) + } + else """" + + val lastTargetEntry = targetEntries[index + patternEntries.lastIndex] + + val targetSuffix = if (matchEndByText) { + if (lastTargetEntry !is KtLiteralStringTemplateEntry) continue + + val patternText = with(pattern.endEntry.text) { substring(0, length - suffixLength) } + val lastTargetEntryText = lastTargetEntry.text + if (!lastTargetEntryText.startsWith(patternText)) continue + lastTargetEntryText.substring(patternText.length) + } + else """" + + val fromIndex = if (matchStartByText) 1 else 0 + val toIndex = if (matchEndByText) patternEntries.lastIndex - 1 else patternEntries.lastIndex + val status = (fromIndex..toIndex).fold(MATCHED) { s, patternEntryIndex -> + val targetEntryToUnify = targetEntries[index + patternEntryIndex] + val patternEntryToUnify = patternEntries[patternEntryIndex] + if (s != UNMATCHED) s and doUnify(targetEntryToUnify, patternEntryToUnify) else s + } + if (status == UNMATCHED) continue + targetSubstringInfo = ExtractableSubstringInfo(targetEntry, lastTargetEntry, targetPrefix, targetSuffix, pattern.type) + return status + } + + return UNMATCHED + } + fun doUnify(target: KotlinPsiRange, pattern: KotlinPsiRange): Status { + (pattern.elements.singleOrNull() as? KtExpression)?.extractableSubstringInfo?.let { + val targetTemplate = target.elements.singleOrNull() as? KtStringTemplateExpression ?: return UNMATCHED + return doUnifyStringTemplateFragments(targetTemplate, it) + } + val targetElements = target.elements val patternElements = pattern.elements if (targetElements.size() != patternElements.size()) return UNMATCHED @@ -828,8 +897,14 @@ public class KotlinPsiUnifier( when { substitution.size() != descriptorToParameter.size() -> Unmatched - status == MATCHED -> - if (weakMatches.isEmpty()) StronglyMatched(target, substitution) else WeaklyMatched(target, substitution, weakMatches) + status == MATCHED -> { + val targetRange = targetSubstringInfo?.createExpression()?.toRange() ?: target + if (weakMatches.isEmpty()) { + StronglyMatched(targetRange, substitution) + } else { + WeaklyMatched(targetRange, substitution, weakMatches) + } + } else -> Unmatched } diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt new file mode 100644 index 0000000000000..8d3f78f7b2c84 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt @@ -0,0 +1,3 @@ +fun foo(param: Int): String { + return ""abc${param}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt new file mode 100644 index 0000000000000..a7ef59f2d4287 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt @@ -0,0 +1,3 @@ +fun foo(param: Int): String { + return ""abc$param"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt new file mode 100644 index 0000000000000..3cc3e6f347136 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt @@ -0,0 +1,3 @@ +fun foo(a: Int): String { + return ""abc$a\ndef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts new file mode 100644 index 0000000000000..0c9a536b18e6d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt.conflicts @@ -0,0 +1 @@ +Cannot find an expression to introduce \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt new file mode 100644 index 0000000000000..1ec4ee42caffa --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt @@ -0,0 +1,6 @@ +fun foo(param: Int): String { + val x = ""xyfalsez"" + val y = ""xyFalsez"" + val z = false + return ""abfalsedef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after new file mode 100644 index 0000000000000..39c2dc543c645 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt.after @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val b = false + val x = ""xy${b}z"" + val y = ""xyFalsez"" + val z = false + return ""ab${b}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt new file mode 100644 index 0000000000000..826c73d618f23 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val x = ""a1234_"" + val y = ""-4123a"" + val z = ""+1243a"" + val u = 123 + return ""ab123def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after new file mode 100644 index 0000000000000..7be885da6e484 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt.after @@ -0,0 +1,8 @@ +fun foo(param: Int): String { + val i = 123 + val x = ""a${i}4_"" + val y = ""-4${i}a"" + val z = ""+1243a"" + val u = 123 + return ""ab${i}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt new file mode 100644 index 0000000000000..7d6dde9721900 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt @@ -0,0 +1,6 @@ +fun foo(param: Int): String { + val x = ""atrue123"" + val x = ""aTRUE123"" + val z = true + return ""abtruedef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after new file mode 100644 index 0000000000000..ba078c9b293ee --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt.after @@ -0,0 +1,7 @@ +fun foo(param: Int): String { + val b = true + val x = ""a${b}123"" + val x = ""aTRUE123"" + val z = true + return ""ab${b}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt new file mode 100644 index 0000000000000..8b10cb97d4cbb --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""abc$a"" + val y = ""abc${a}"" + val z = ""abc{$a}def"" + return ""abc$a"" + ""def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after new file mode 100644 index 0000000000000..2e2d3540f7ce0 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = ""abc$a"" + val x = s + val y = s + val z = ""abc{$a}def"" + return s + ""def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt new file mode 100644 index 0000000000000..2a19834a5bc67 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""-${a + 1}"" + val y = ""x${a + 1}y"" + val z = ""x${a - 1}y"" + return ""abc${a + 1}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after new file mode 100644 index 0000000000000..920ba830a2157 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val i = a + 1 + val x = ""-$i"" + val y = ""x${i}y"" + val z = ""x${a - 1}y"" + return ""abc${i}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt new file mode 100644 index 0000000000000..b3e5ea58080b3 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""-$a"" + val y = ""x${a}y"" + val z = ""x$ay"" + return ""abc${a}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after new file mode 100644 index 0000000000000..60d242b3bb83d --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val a1 = a + val x = ""-$a1"" + val y = ""x${a1}y"" + val z = ""x$ay"" + return ""abc${a1}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt new file mode 100644 index 0000000000000..e059fcf97328b --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = ""+cd$a:${a + 1}efg"" + val y = ""+cd$a${a + 1}efg"" + return ""abcd$a:${a + 1}ef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after new file mode 100644 index 0000000000000..3bc1c2c2842a1 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = ""cd$a:${a + 1}ef"" + val x = ""+${s}g"" + val y = ""+cd$a${a + 1}efg"" + return ""ab$s"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt new file mode 100644 index 0000000000000..e81ce108d0de8 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = ""_c$a:${a + 1}d_"" + val y = ""_$a:${a + 1}d_"" + return ""abc$a:${a + 1}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after new file mode 100644 index 0000000000000..fc66f321bf26e --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = ""c$a:${a + 1}d"" + val x = ""_${s}_"" + val y = ""_$a:${a + 1}d_"" + return ""ab${s}ef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt new file mode 100644 index 0000000000000..f77d65ff3a28c --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt @@ -0,0 +1,5 @@ +fun foo(a: Int): String { + val x = ""_ab$a:${a + 1}cd__"" + val y = ""_a$a:${a + 1}cd__"" + return ""ab$a:${a + 1}cdef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after new file mode 100644 index 0000000000000..58ec28df9cd03 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt.after @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val s = ""ab$a:${a + 1}cd"" + val x = ""_${s}__"" + val y = ""_a$a:${a + 1}cd__"" + return ""${s}ef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt new file mode 100644 index 0000000000000..d4f1d34ed57dc --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt @@ -0,0 +1,9 @@ +fun foo(a: Int): String { + val x = """"""_c$a + :${a + 1}d_"""""" + val y = ""_$a:${a + 1}d_"" + val z = """"""_c$a:${a + 1}d_"""""" + val u = ""_c$a\n:${a + 1}d_"" + return """"""abc$a + :${a + 1}def"""""" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after new file mode 100644 index 0000000000000..31a44acbe3f34 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt.after @@ -0,0 +1,9 @@ +fun foo(a: Int): String { + val s = """"""c$a + :${a + 1}d"""""" + val x = """"""_${s}_"""""" + val y = ""_$a:${a + 1}d_"" + val z = """"""_c$a:${a + 1}d_"""""" + val u = ""_c$a\n:${a + 1}d_"" + return """"""ab${s}ef"""""" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt new file mode 100644 index 0000000000000..9dc8211a168fb --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""xabc$a"" + val y = ""${a}abcx"" + val z = ""xacb$a"" + return ""abcdef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after new file mode 100644 index 0000000000000..fb4778f7e0761 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = ""abc"" + val x = ""x$s$a"" + val y = ""${a}${s}x"" + val z = ""xacb$a"" + return ""${s}def"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt new file mode 100644 index 0000000000000..091f98c39f182 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""xcd$a"" + val y = ""${a}cdx"" + val z = ""xcf$a"" + return ""abcdef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after new file mode 100644 index 0000000000000..f83413680bb83 --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = ""cd"" + val x = ""x$s$a"" + val y = ""${a}${s}x"" + val z = ""xcf$a"" + return ""ab${s}ef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt new file mode 100644 index 0000000000000..53d3c4eff519e --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt @@ -0,0 +1,6 @@ +fun foo(a: Int): String { + val x = ""xdef$a"" + val y = ""${a}defx"" + val z = ""xddf$a"" + return ""abcdef"" +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after new file mode 100644 index 0000000000000..ca6300ff3806c --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt.after @@ -0,0 +1,7 @@ +fun foo(a: Int): String { + val s = ""def"" + val x = ""x$s$a"" + val y = ""${a}${s}x"" + val z = ""xddf$a"" + return ""abc$s"" +} \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java index 1f1abfd5543ab..2f0a0c80f16ee 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractionTestGenerated.java @@ -507,6 +507,111 @@ public void testOuterItInsideNestedLamba() throws Exception { doIntroduceVariableTest(fileName); } } + + @TestMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates"") + @TestDataPath(""$PROJECT_ROOT"") + @RunWith(JUnit3RunnerWithInners.class) + public static class StringTemplates extends AbstractExtractionTest { + public void testAllFilesPresentInStringTemplates() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""idea/testData/refactoring/introduceVariable/stringTemplates""), Pattern.compile(""^(.+)\\.kt$""), true); + } + + @TestMetadata(""brokenEntryWithBlockExpr.kt"") + public void testBrokenEntryWithBlockExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithBlockExpr.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""brokenEntryWithExpr.kt"") + public void testBrokenEntryWithExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/brokenEntryWithExpr.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""brokenEscapeEntry.kt"") + public void testBrokenEscapeEntry() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/brokenEscapeEntry.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""extractFalse.kt"") + public void testExtractFalse() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/extractFalse.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""extractIntegerLiteral.kt"") + public void testExtractIntegerLiteral() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/extractIntegerLiteral.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""extractTrue.kt"") + public void testExtractTrue() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/extractTrue.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""fullContent.kt"") + public void testFullContent() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/fullContent.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""fullEntryWithBlockExpr.kt"") + public void testFullEntryWithBlockExpr() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithBlockExpr.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""fullEntryWithSimpleName.kt"") + public void testFullEntryWithSimpleName() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/fullEntryWithSimpleName.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""multipleEntriesWithPrefix.kt"") + public void testMultipleEntriesWithPrefix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithPrefix.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""multipleEntriesWithSubstring.kt"") + public void testMultipleEntriesWithSubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSubstring.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""multipleEntriesWithSuffix.kt"") + public void testMultipleEntriesWithSuffix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/multipleEntriesWithSuffix.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""rawTemplateWithSubstring.kt"") + public void testRawTemplateWithSubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/rawTemplateWithSubstring.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""singleEntryPrefix.kt"") + public void testSingleEntryPrefix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/singleEntryPrefix.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""singleEntrySubstring.kt"") + public void testSingleEntrySubstring() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySubstring.kt""); + doIntroduceVariableTest(fileName); + } + + @TestMetadata(""singleEntrySuffix.kt"") + public void testSingleEntrySuffix() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/stringTemplates/singleEntrySuffix.kt""); + doIntroduceVariableTest(fileName); + } + } } @TestMetadata(""idea/testData/refactoring/extractFunction"")" 8bf446f012faddf7762db07ed85199f05c58d6bf,intellij-community,fields are protected--,p,https://github.com/JetBrains/intellij-community,"diff --git a/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java b/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java index 3098a777bb395..db779e12d25ab 100644 --- a/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java +++ b/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java @@ -45,17 +45,17 @@ public MovedFileInfo(VirtualFile file, final String newPath) { } protected final Project myProject; - private final AbstractVcs myVcs; - private final ChangeListManager myChangeListManager; - private final MyVirtualFileAdapter myVFSListener; - private final MyCommandAdapter myCommandListener; - private final VcsShowConfirmationOption myAddOption; - private final VcsShowConfirmationOption myRemoveOption; - private final List myAddedFiles = new ArrayList(); - private final Map myCopyFromMap = new HashMap(); - private final List myDeletedFiles = new ArrayList(); - private final List myDeletedWithoutConfirmFiles = new ArrayList(); - private final List myMovedFiles = new ArrayList(); + protected final AbstractVcs myVcs; + protected final ChangeListManager myChangeListManager; + protected final MyVirtualFileAdapter myVFSListener; + protected final MyCommandAdapter myCommandListener; + protected final VcsShowConfirmationOption myAddOption; + protected final VcsShowConfirmationOption myRemoveOption; + protected final List myAddedFiles = new ArrayList(); + protected final Map myCopyFromMap = new HashMap(); + protected final List myDeletedFiles = new ArrayList(); + protected final List myDeletedWithoutConfirmFiles = new ArrayList(); + protected final List myMovedFiles = new ArrayList(); protected enum VcsDeleteType { SILENT, CONFIRM, IGNORE }" f38296da61ed21544ad45609c52d950adf913dca,elasticsearch,Percolator response now always returns the- `matches` key.--Closes -4881-,c,https://github.com/elastic/elasticsearch,"diff --git a/rest-api-spec/test/percolate/17_empty.yaml b/rest-api-spec/test/percolate/17_empty.yaml new file mode 100644 index 0000000000000..0cd1ac5bb8d32 --- /dev/null +++ b/rest-api-spec/test/percolate/17_empty.yaml @@ -0,0 +1,31 @@ +--- +""Basic percolation tests on an empty cluster"": + + - do: + indices.create: + index: test_index + + - do: + indices.refresh: {} + + - do: + percolate: + index: test_index + type: test_type + body: + doc: + foo: bar + + - match: {'total': 0} + - match: {'matches': []} + + - do: + count_percolate: + index: test_index + type: test_type + body: + doc: + foo: bar + + - is_false: matches + - match: {'total': 0} diff --git a/src/main/java/org/elasticsearch/action/percolate/PercolateResponse.java b/src/main/java/org/elasticsearch/action/percolate/PercolateResponse.java index dd2edcfb83d12..c6ae1d0d4c384 100644 --- a/src/main/java/org/elasticsearch/action/percolate/PercolateResponse.java +++ b/src/main/java/org/elasticsearch/action/percolate/PercolateResponse.java @@ -42,7 +42,7 @@ */ public class PercolateResponse extends BroadcastOperationResponse implements Iterable, ToXContent { - private static final Match[] EMPTY = new Match[0]; + public static final Match[] EMPTY = new Match[0]; private long tookInMillis; private Match[] matches; @@ -60,10 +60,10 @@ public PercolateResponse(int totalShards, int successfulShards, int failedShards this.aggregations = aggregations; } - public PercolateResponse(int totalShards, int successfulShards, int failedShards, List shardFailures, long tookInMillis) { + public PercolateResponse(int totalShards, int successfulShards, int failedShards, List shardFailures, long tookInMillis, Match[] matches) { super(totalShards, successfulShards, failedShards, shardFailures); this.tookInMillis = tookInMillis; - this.matches = EMPTY; + this.matches = matches; } PercolateResponse() { @@ -87,18 +87,30 @@ public long getTookInMillis() { return tookInMillis; } + /** + * @return The queries that match with the document being percolated. This can return null if th. + */ public Match[] getMatches() { return this.matches; } + /** + * @return The total number of queries that have matched with the document being percolated. + */ public long getCount() { return count; } + /** + * @return Any facet that has been executed on the query metadata. This can return null. + */ public InternalFacets getFacets() { return facets; } + /** + * @return Any aggregations that has been executed on the query metadata. This can return null. + */ public InternalAggregations getAggregations() { return aggregations; } @@ -116,7 +128,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws RestActions.buildBroadcastShardsHeader(builder, this); builder.field(Fields.TOTAL, count); - if (matches.length != 0) { + if (matches != null) { builder.startArray(Fields.MATCHES); boolean justIds = ""ids"".equals(params.param(""percolate_format"")); if (justIds) { @@ -171,10 +183,12 @@ public void readFrom(StreamInput in) throws IOException { tookInMillis = in.readVLong(); count = in.readVLong(); int size = in.readVInt(); - matches = new Match[size]; - for (int i = 0; i < size; i++) { - matches[i] = new Match(); - matches[i].readFrom(in); + if (size != -1) { + matches = new Match[size]; + for (int i = 0; i < size; i++) { + matches[i] = new Match(); + matches[i].readFrom(in); + } } facets = InternalFacets.readOptionalFacets(in); aggregations = InternalAggregations.readOptionalAggregations(in); @@ -185,9 +199,13 @@ public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVLong(tookInMillis); out.writeVLong(count); - out.writeVInt(matches.length); - for (Match match : matches) { - match.writeTo(out); + if (matches == null) { + out.writeVInt(-1); + } else { + out.writeVInt(matches.length); + for (Match match : matches) { + match.writeTo(out); + } } out.writeOptionalStreamable(facets); out.writeOptionalStreamable(aggregations); diff --git a/src/main/java/org/elasticsearch/action/percolate/TransportPercolateAction.java b/src/main/java/org/elasticsearch/action/percolate/TransportPercolateAction.java index 0a27d598b3911..f8bc3776742f7 100644 --- a/src/main/java/org/elasticsearch/action/percolate/TransportPercolateAction.java +++ b/src/main/java/org/elasticsearch/action/percolate/TransportPercolateAction.java @@ -155,7 +155,8 @@ public static PercolateResponse reduce(PercolateRequest request, AtomicReference if (shardResults == null) { long tookInMillis = System.currentTimeMillis() - request.startTime; - return new PercolateResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures, tookInMillis); + PercolateResponse.Match[] matches = request.onlyCount() ? null : PercolateResponse.EMPTY; + return new PercolateResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures, tookInMillis, matches); } else { PercolatorService.ReduceResult result = percolatorService.reduce(percolatorTypeId, shardResults); long tookInMillis = System.currentTimeMillis() - request.startTime; diff --git a/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/src/main/java/org/elasticsearch/percolator/PercolatorService.java index e89498bce497a..9b90880539f52 100644 --- a/src/main/java/org/elasticsearch/percolator/PercolatorService.java +++ b/src/main/java/org/elasticsearch/percolator/PercolatorService.java @@ -795,8 +795,6 @@ private void queryBasedPercolating(Engine.Searcher percolatorSearcher, Percolate public final static class ReduceResult { - private static PercolateResponse.Match[] EMPTY = new PercolateResponse.Match[0]; - private final long count; private final PercolateResponse.Match[] matches; private final InternalFacets reducedFacets; @@ -811,7 +809,7 @@ public final static class ReduceResult { public ReduceResult(long count, InternalFacets reducedFacets, InternalAggregations reducedAggregations) { this.count = count; - this.matches = EMPTY; + this.matches = null; this.reducedFacets = reducedFacets; this.reducedAggregations = reducedAggregations; } diff --git a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java index 4e6b873bf93ca..4247a0e8a2f61 100644 --- a/src/test/java/org/elasticsearch/percolator/PercolatorTests.java +++ b/src/test/java/org/elasticsearch/percolator/PercolatorTests.java @@ -931,7 +931,7 @@ public void testCountPercolation() throws Exception { .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field(""field1"", ""b"").endObject())) .execute().actionGet(); assertMatchCount(response, 2l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate doc with field1=c""); response = client().preparePercolate() @@ -939,7 +939,7 @@ public void testCountPercolation() throws Exception { .setPercolateDoc(docBuilder().setDoc(yamlBuilder().startObject().field(""field1"", ""c"").endObject())) .execute().actionGet(); assertMatchCount(response, 2l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate doc with field1=b c""); response = client().preparePercolate() @@ -947,7 +947,7 @@ public void testCountPercolation() throws Exception { .setPercolateDoc(docBuilder().setDoc(smileBuilder().startObject().field(""field1"", ""b c"").endObject())) .execute().actionGet(); assertMatchCount(response, 4l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate doc with field1=d""); response = client().preparePercolate() @@ -955,7 +955,7 @@ public void testCountPercolation() throws Exception { .setPercolateDoc(docBuilder().setDoc(jsonBuilder().startObject().field(""field1"", ""d"").endObject())) .execute().actionGet(); assertMatchCount(response, 1l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate non existing doc""); try { @@ -1003,7 +1003,7 @@ public void testCountPercolatingExistingDocs() throws Exception { .setGetRequest(Requests.getRequest(""test"").type(""type"").id(""1"")) .execute().actionGet(); assertMatchCount(response, 2l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate existing doc with id 2""); response = client().preparePercolate() @@ -1011,7 +1011,7 @@ public void testCountPercolatingExistingDocs() throws Exception { .setGetRequest(Requests.getRequest(""test"").type(""type"").id(""2"")) .execute().actionGet(); assertMatchCount(response, 2l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate existing doc with id 3""); response = client().preparePercolate() @@ -1019,7 +1019,7 @@ public void testCountPercolatingExistingDocs() throws Exception { .setGetRequest(Requests.getRequest(""test"").type(""type"").id(""3"")) .execute().actionGet(); assertMatchCount(response, 4l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); logger.info(""--> Count percolate existing doc with id 4""); response = client().preparePercolate() @@ -1027,7 +1027,7 @@ public void testCountPercolatingExistingDocs() throws Exception { .setGetRequest(Requests.getRequest(""test"").type(""type"").id(""4"")) .execute().actionGet(); assertMatchCount(response, 1l); - assertThat(response.getMatches(), emptyArray()); + assertThat(response.getMatches(), nullValue()); } @Test" 021315f049c6fc19159f2e7495456744cb0d17e6,kotlin,"Minor, make ModuleDescriptor public in injectors--It's much more convenient to call injector.getModule() than-injector.getResolveSession().getModuleDescriptor()-",p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForLazyResolveWithJava.java b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForLazyResolveWithJava.java index abf224408114a..f6c96d6b9d44a 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForLazyResolveWithJava.java +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForLazyResolveWithJava.java @@ -157,7 +157,7 @@ public InjectorForLazyResolveWithJava( this.kotlinBuiltIns = module.getBuiltIns(); this.platformToKotlinClassMap = module.getPlatformToKotlinClassMap(); this.declarationProviderFactory = declarationProviderFactory; - this.resolveSession = new ResolveSession(project, globalContext, module, declarationProviderFactory, bindingTrace); + this.resolveSession = new ResolveSession(project, globalContext, getModule(), declarationProviderFactory, bindingTrace); this.scopeProvider = new ScopeProvider(getResolveSession()); this.moduleContentScope = moduleContentScope; this.moduleClassResolver = moduleClassResolver; @@ -173,8 +173,8 @@ public InjectorForLazyResolveWithJava( this.samConversionResolver = SamConversionResolverImpl.INSTANCE$; this.javaSourceElementFactory = new JavaSourceElementFactoryImpl(); this.globalJavaResolverContext = new GlobalJavaResolverContext(storageManager, getJavaClassFinder(), virtualFileFinder, deserializedDescriptorResolver, psiBasedExternalAnnotationResolver, traceBasedExternalSignatureResolver, traceBasedErrorReporter, psiBasedMethodSignatureChecker, lazyResolveBasedCache, javaPropertyInitializerEvaluator, samConversionResolver, javaSourceElementFactory, moduleClassResolver); - this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, module); - this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, module); + this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, getModule()); + this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, getModule()); this.javaFlexibleTypeCapabilitiesProvider = new JavaFlexibleTypeCapabilitiesProvider(); this.lazyResolveToken = new LazyResolveToken(); this.javaLazyAnalyzerPostConstruct = new JavaLazyAnalyzerPostConstruct(); @@ -190,10 +190,10 @@ public InjectorForLazyResolveWithJava( this.forLoopConventionsChecker = new ForLoopConventionsChecker(); this.descriptorResolver = new DescriptorResolver(); this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); - this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, module, javaFlexibleTypeCapabilitiesProvider, storageManager, lazyResolveToken, dynamicTypesSettings); + this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, getModule(), javaFlexibleTypeCapabilitiesProvider, storageManager, lazyResolveToken, dynamicTypesSettings); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(descriptorResolver, typeResolver, annotationResolver); this.delegatedPropertyResolver = new DelegatedPropertyResolver(); - this.reflectionTypes = new ReflectionTypes(module); + this.reflectionTypes = new ReflectionTypes(getModule()); this.callExpressionResolver = new CallExpressionResolver(); this.statementFilter = new StatementFilter(); this.candidateResolver = new CandidateResolver(); @@ -205,8 +205,8 @@ public InjectorForLazyResolveWithJava( this.scriptBodyResolver = new ScriptBodyResolver(); this.additionalFileScopeProvider = new AdditionalFileScopeProvider(); this.javaClassDataFinder = new JavaClassDataFinder(virtualFileFinder, deserializedDescriptorResolver); - this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(module, storageManager, virtualFileFinder, traceBasedErrorReporter); - this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, module, javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); + this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(getModule(), storageManager, virtualFileFinder, traceBasedErrorReporter); + this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, getModule(), javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); this.resolveSession.setAnnotationResolve(annotationResolver); this.resolveSession.setDescriptorResolver(descriptorResolver); @@ -317,6 +317,10 @@ public InjectorForLazyResolveWithJava( public void destroy() { } + public ModuleDescriptorImpl getModule() { + return this.module; + } + public ResolveSession getResolveSession() { return this.resolveSession; } diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForReplWithJava.java b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForReplWithJava.java index 2042291e401e4..9d0bd2f5d9871 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForReplWithJava.java +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForReplWithJava.java @@ -179,7 +179,7 @@ public InjectorForReplWithJava( this.kotlinBuiltIns = module.getBuiltIns(); this.platformToKotlinClassMap = module.getPlatformToKotlinClassMap(); this.declarationProviderFactory = declarationProviderFactory; - this.resolveSession = new ResolveSession(project, globalContext, module, declarationProviderFactory, bindingTrace); + this.resolveSession = new ResolveSession(project, globalContext, getModule(), declarationProviderFactory, bindingTrace); this.scopeProvider = new ScopeProvider(getResolveSession()); this.moduleContentScope = moduleContentScope; this.lazyTopDownAnalyzer = new LazyTopDownAnalyzer(); @@ -197,11 +197,11 @@ public InjectorForReplWithJava( this.javaSourceElementFactory = new JavaSourceElementFactoryImpl(); this.singleModuleClassResolver = new SingleModuleClassResolver(); this.globalJavaResolverContext = new GlobalJavaResolverContext(storageManager, javaClassFinder, virtualFileFinder, deserializedDescriptorResolver, psiBasedExternalAnnotationResolver, traceBasedExternalSignatureResolver, traceBasedErrorReporter, psiBasedMethodSignatureChecker, lazyResolveBasedCache, javaPropertyInitializerEvaluator, samConversionResolver, javaSourceElementFactory, singleModuleClassResolver); - this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, module); - this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, module); + this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, getModule()); + this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, getModule()); this.javaClassDataFinder = new JavaClassDataFinder(virtualFileFinder, deserializedDescriptorResolver); - this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(module, storageManager, virtualFileFinder, traceBasedErrorReporter); - this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, module, javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); + this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(getModule(), storageManager, virtualFileFinder, traceBasedErrorReporter); + this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, getModule(), javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); this.javaLazyAnalyzerPostConstruct = new JavaLazyAnalyzerPostConstruct(); this.javaFlexibleTypeCapabilitiesProvider = new JavaFlexibleTypeCapabilitiesProvider(); this.kotlinJvmCheckerProvider = KotlinJvmCheckerProvider.INSTANCE$; @@ -218,10 +218,10 @@ public InjectorForReplWithJava( this.descriptorResolver = new DescriptorResolver(); this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); this.lazinessToken = new LazinessToken(); - this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, module, javaFlexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); + this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, getModule(), javaFlexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(descriptorResolver, typeResolver, annotationResolver); this.delegatedPropertyResolver = new DelegatedPropertyResolver(); - this.reflectionTypes = new ReflectionTypes(module); + this.reflectionTypes = new ReflectionTypes(getModule()); this.callExpressionResolver = new CallExpressionResolver(); this.statementFilter = new StatementFilter(); this.candidateResolver = new CandidateResolver(); @@ -392,6 +392,10 @@ public InjectorForReplWithJava( public void destroy() { } + public ModuleDescriptorImpl getModule() { + return this.module; + } + public ResolveSession getResolveSession() { return this.resolveSession; } diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJvm.java b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJvm.java index dff22a2b9dc77..ab4a917ad5b70 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJvm.java +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJvm.java @@ -178,7 +178,7 @@ public InjectorForTopDownAnalyzerForJvm( this.kotlinBuiltIns = module.getBuiltIns(); this.platformToKotlinClassMap = module.getPlatformToKotlinClassMap(); this.declarationProviderFactory = declarationProviderFactory; - this.resolveSession = new ResolveSession(project, globalContext, module, declarationProviderFactory, bindingTrace); + this.resolveSession = new ResolveSession(project, globalContext, getModule(), declarationProviderFactory, bindingTrace); this.scopeProvider = new ScopeProvider(getResolveSession()); this.moduleContentScope = moduleContentScope; this.lazyTopDownAnalyzer = new LazyTopDownAnalyzer(); @@ -196,11 +196,11 @@ public InjectorForTopDownAnalyzerForJvm( this.javaSourceElementFactory = new JavaSourceElementFactoryImpl(); this.singleModuleClassResolver = new SingleModuleClassResolver(); this.globalJavaResolverContext = new GlobalJavaResolverContext(storageManager, javaClassFinder, virtualFileFinder, deserializedDescriptorResolver, psiBasedExternalAnnotationResolver, traceBasedExternalSignatureResolver, traceBasedErrorReporter, psiBasedMethodSignatureChecker, lazyResolveBasedCache, javaPropertyInitializerEvaluator, samConversionResolver, javaSourceElementFactory, singleModuleClassResolver); - this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, module); - this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, module); + this.lazyJavaPackageFragmentProvider = new LazyJavaPackageFragmentProvider(globalJavaResolverContext, getModule()); + this.javaDescriptorResolver = new JavaDescriptorResolver(lazyJavaPackageFragmentProvider, getModule()); this.javaClassDataFinder = new JavaClassDataFinder(virtualFileFinder, deserializedDescriptorResolver); - this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(module, storageManager, virtualFileFinder, traceBasedErrorReporter); - this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, module, javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); + this.binaryClassAnnotationAndConstantLoader = new BinaryClassAnnotationAndConstantLoaderImpl(getModule(), storageManager, virtualFileFinder, traceBasedErrorReporter); + this.deserializationComponentsForJava = new DeserializationComponentsForJava(storageManager, getModule(), javaClassDataFinder, binaryClassAnnotationAndConstantLoader, lazyJavaPackageFragmentProvider); this.javaLazyAnalyzerPostConstruct = new JavaLazyAnalyzerPostConstruct(); this.javaFlexibleTypeCapabilitiesProvider = new JavaFlexibleTypeCapabilitiesProvider(); this.kotlinJvmCheckerProvider = KotlinJvmCheckerProvider.INSTANCE$; @@ -216,10 +216,10 @@ public InjectorForTopDownAnalyzerForJvm( this.descriptorResolver = new DescriptorResolver(); this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); this.lazinessToken = new LazinessToken(); - this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, module, javaFlexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); + this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, getModule(), javaFlexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(descriptorResolver, typeResolver, annotationResolver); this.delegatedPropertyResolver = new DelegatedPropertyResolver(); - this.reflectionTypes = new ReflectionTypes(module); + this.reflectionTypes = new ReflectionTypes(getModule()); this.callExpressionResolver = new CallExpressionResolver(); this.statementFilter = new StatementFilter(); this.candidateResolver = new CandidateResolver(); @@ -391,6 +391,10 @@ public InjectorForTopDownAnalyzerForJvm( public void destroy() { } + public ModuleDescriptorImpl getModule() { + return this.module; + } + public ResolveSession getResolveSession() { return this.resolveSession; } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/di/InjectorForLazyTopDownAnalyzerBasic.java b/compiler/frontend/src/org/jetbrains/kotlin/di/InjectorForLazyTopDownAnalyzerBasic.java index 2f29800e24bbe..76cef999acc4b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/di/InjectorForLazyTopDownAnalyzerBasic.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/di/InjectorForLazyTopDownAnalyzerBasic.java @@ -137,7 +137,7 @@ public InjectorForLazyTopDownAnalyzerBasic( this.kotlinBuiltIns = module.getBuiltIns(); this.platformToKotlinClassMap = module.getPlatformToKotlinClassMap(); this.declarationProviderFactory = declarationProviderFactory; - this.resolveSession = new ResolveSession(project, globalContext, module, declarationProviderFactory, bindingTrace); + this.resolveSession = new ResolveSession(project, globalContext, getModule(), declarationProviderFactory, bindingTrace); this.scopeProvider = new ScopeProvider(getResolveSession()); this.lazyTopDownAnalyzerForTopLevel = new LazyTopDownAnalyzerForTopLevel(); this.defaultProvider = DefaultProvider.INSTANCE$; @@ -154,10 +154,10 @@ public InjectorForLazyTopDownAnalyzerBasic( this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); this.flexibleTypeCapabilitiesProvider = new FlexibleTypeCapabilitiesProvider(); this.lazinessToken = new LazinessToken(); - this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, module, flexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); + this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, getModule(), flexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesSettings); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(descriptorResolver, typeResolver, annotationResolver); this.delegatedPropertyResolver = new DelegatedPropertyResolver(); - this.reflectionTypes = new ReflectionTypes(module); + this.reflectionTypes = new ReflectionTypes(getModule()); this.callExpressionResolver = new CallExpressionResolver(); this.statementFilter = new StatementFilter(); this.candidateResolver = new CandidateResolver(); @@ -303,6 +303,10 @@ public InjectorForLazyTopDownAnalyzerBasic( public void destroy() { } + public ModuleDescriptorImpl getModule() { + return this.module; + } + public ResolveSession getResolveSession() { return this.resolveSession; } diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractSdkAnnotationsValidityTest.java b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractSdkAnnotationsValidityTest.java index 87c14ef82df51..29771d305cee7 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractSdkAnnotationsValidityTest.java +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/AbstractSdkAnnotationsValidityTest.java @@ -25,8 +25,8 @@ import org.jetbrains.kotlin.cli.jvm.compiler.JetCoreEnvironment; import org.jetbrains.kotlin.descriptors.*; import org.jetbrains.kotlin.descriptors.impl.DeclarationDescriptorVisitorEmptyBodies; -import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJava; +import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.load.java.JavaBindingContext; import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.platform.JavaToKotlinClassMap; @@ -77,7 +77,7 @@ public void testNoErrorsInAlternativeSignatures() throws IOException { BindingTrace trace = new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace(); InjectorForLazyResolveWithJava injector = InjectorForLazyResolveWithJavaUtil.create(commonEnvironment.getProject(), trace, false); - ModuleDescriptor module = injector.getResolveSession().getModuleDescriptor(); + ModuleDescriptor module = injector.getModule(); AlternativeSignatureErrorFindingVisitor visitor = new AlternativeSignatureErrorFindingVisitor(trace.getBindingContext(), errors); diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/LoadDescriptorUtil.java b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/LoadDescriptorUtil.java index a8d4e500a4f38..b53dcd3a3844b 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/LoadDescriptorUtil.java +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/LoadDescriptorUtil.java @@ -33,10 +33,9 @@ import org.jetbrains.kotlin.codegen.forTestCompile.ForTestCompileRuntime; import org.jetbrains.kotlin.codegen.state.GenerationState; import org.jetbrains.kotlin.config.CompilerConfiguration; -import org.jetbrains.kotlin.descriptors.ModuleDescriptor; import org.jetbrains.kotlin.descriptors.PackageViewDescriptor; -import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJava; +import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.psi.JetFile; @@ -95,9 +94,8 @@ public static Pair loadTestPackageAndBind BindingTrace trace = new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace(); InjectorForLazyResolveWithJava injector = InjectorForLazyResolveWithJavaUtil.create(jetCoreEnvironment.getProject(), trace, true); - ModuleDescriptor module = injector.getResolveSession().getModuleDescriptor(); - PackageViewDescriptor packageView = module.getPackage(TEST_PACKAGE_FQNAME); + PackageViewDescriptor packageView = injector.getModule().getPackage(TEST_PACKAGE_FQNAME); assert packageView != null; return Pair.create(packageView, trace.getBindingContext()); diff --git a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java index bf412a687758e..3a67dee6d9af9 100644 --- a/compiler/tests/org/jetbrains/kotlin/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java +++ b/compiler/tests/org/jetbrains/kotlin/jvm/compiler/longTest/ResolveDescriptorsFromExternalLibraries.java @@ -30,9 +30,8 @@ import org.jetbrains.kotlin.cli.jvm.compiler.JetCoreEnvironment; import org.jetbrains.kotlin.config.CompilerConfiguration; import org.jetbrains.kotlin.descriptors.ClassDescriptor; -import org.jetbrains.kotlin.descriptors.ModuleDescriptor; -import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJava; +import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.resolve.BindingTraceContext; import org.jetbrains.kotlin.test.ConfigurationKind; @@ -181,7 +180,6 @@ public void dispose() { } InjectorForLazyResolveWithJava injector = InjectorForLazyResolveWithJavaUtil.create(jetCoreEnvironment.getProject(), new BindingTraceContext(), false); - ModuleDescriptor moduleDescriptor = injector.getResolveSession().getModuleDescriptor(); boolean hasErrors; try { @@ -213,7 +211,7 @@ public void dispose() { } String className = entryName.substring(0, entryName.length() - "".class"".length()).replace(""/"", "".""); try { - ClassDescriptor clazz = resolveTopLevelClass(moduleDescriptor, new FqName(className)); + ClassDescriptor clazz = resolveTopLevelClass(injector.getModule(), new FqName(className)); if (clazz == null) { throw new IllegalStateException(""class not found by name "" + className + "" in "" + libDescription); } diff --git a/compiler/tests/org/jetbrains/kotlin/types/JetTypeCheckerTest.java b/compiler/tests/org/jetbrains/kotlin/types/JetTypeCheckerTest.java index 8c320b19a5ec6..abbfa514a889d 100644 --- a/compiler/tests/org/jetbrains/kotlin/types/JetTypeCheckerTest.java +++ b/compiler/tests/org/jetbrains/kotlin/types/JetTypeCheckerTest.java @@ -27,8 +27,8 @@ import org.jetbrains.kotlin.descriptors.PackageViewDescriptor; import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor; import org.jetbrains.kotlin.descriptors.impl.ReceiverParameterDescriptorImpl; -import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJava; +import org.jetbrains.kotlin.di.InjectorForLazyResolveWithJavaUtil; import org.jetbrains.kotlin.di.InjectorForTests; import org.jetbrains.kotlin.name.FqName; import org.jetbrains.kotlin.psi.JetExpression; @@ -594,7 +594,7 @@ private WritableScopeImpl addImports(JetScope scope) { scope, scope.getContainingDeclaration(), RedeclarationHandler.DO_NOTHING, ""JetTypeCheckerTest.addImports""); BindingTraceContext trace = new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace(); InjectorForLazyResolveWithJava injector = InjectorForLazyResolveWithJavaUtil.create(getProject(), trace, true); - ModuleDescriptor module = injector.getResolveSession().getModuleDescriptor(); + ModuleDescriptor module = injector.getModule(); for (ImportPath defaultImport : module.getDefaultImports()) { FqName fqName = defaultImport.fqnPart(); if (defaultImport.isAllUnder()) { diff --git a/generators/src/org/jetbrains/kotlin/generators/injectors/GenerateInjectors.kt b/generators/src/org/jetbrains/kotlin/generators/injectors/GenerateInjectors.kt index 66f0ee35f0538..7bbedf82f0af5 100644 --- a/generators/src/org/jetbrains/kotlin/generators/injectors/GenerateInjectors.kt +++ b/generators/src/org/jetbrains/kotlin/generators/injectors/GenerateInjectors.kt @@ -242,7 +242,7 @@ private fun DependencyInjectorGenerator.commonForResolveSessionBased() { parameter() parameter(useAsContext = true) parameter() - parameter(name = ""module"", useAsContext = true) + publicParameter(name = ""module"", useAsContext = true) parameter() publicField() diff --git a/js/js.frontend/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJs.java b/js/js.frontend/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJs.java index 8eed7526f3372..3bd58674e277d 100644 --- a/js/js.frontend/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJs.java +++ b/js/js.frontend/src/org/jetbrains/kotlin/di/InjectorForTopDownAnalyzerForJs.java @@ -137,7 +137,7 @@ public InjectorForTopDownAnalyzerForJs( this.kotlinBuiltIns = module.getBuiltIns(); this.platformToKotlinClassMap = module.getPlatformToKotlinClassMap(); this.declarationProviderFactory = declarationProviderFactory; - this.resolveSession = new ResolveSession(project, globalContext, module, declarationProviderFactory, bindingTrace); + this.resolveSession = new ResolveSession(project, globalContext, getModule(), declarationProviderFactory, bindingTrace); this.scopeProvider = new ScopeProvider(getResolveSession()); this.lazyTopDownAnalyzerForTopLevel = new LazyTopDownAnalyzerForTopLevel(); this.kotlinJsCheckerProvider = KotlinJsCheckerProvider.INSTANCE$; @@ -154,10 +154,10 @@ public InjectorForTopDownAnalyzerForJs( this.qualifiedExpressionResolver = new QualifiedExpressionResolver(); this.flexibleTypeCapabilitiesProvider = new FlexibleTypeCapabilitiesProvider(); this.lazinessToken = new LazinessToken(); - this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, module, flexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesAllowed); + this.typeResolver = new TypeResolver(annotationResolver, qualifiedExpressionResolver, getModule(), flexibleTypeCapabilitiesProvider, storageManager, lazinessToken, dynamicTypesAllowed); this.localClassifierAnalyzer = new LocalClassifierAnalyzer(descriptorResolver, typeResolver, annotationResolver); this.delegatedPropertyResolver = new DelegatedPropertyResolver(); - this.reflectionTypes = new ReflectionTypes(module); + this.reflectionTypes = new ReflectionTypes(getModule()); this.callExpressionResolver = new CallExpressionResolver(); this.statementFilter = new StatementFilter(); this.candidateResolver = new CandidateResolver(); @@ -303,6 +303,10 @@ public InjectorForTopDownAnalyzerForJs( public void destroy() { } + public ModuleDescriptorImpl getModule() { + return this.module; + } + public ResolveSession getResolveSession() { return this.resolveSession; }" f9f7c57dbf2cd80f2f486d78da0c90a014617e19,camel,[CAMEL-1510] BatchProcessor interrupt has side- effects (submitted on behalf of Christopher Hunt)--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@765686 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java index a35b33f052d10..0589899f52972 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/BatchProcessor.java @@ -18,7 +18,12 @@ import java.util.Collection; import java.util.Iterator; -import java.util.concurrent.LinkedBlockingQueue; +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; import org.apache.camel.Exchange; import org.apache.camel.Processor; @@ -30,13 +35,12 @@ import org.apache.camel.util.ServiceHelper; /** - * A base class for any kind of {@link Processor} which implements some kind of - * batch processing. + * A base class for any kind of {@link Processor} which implements some kind of batch processing. * * @version $Revision$ */ public class BatchProcessor extends ServiceSupport implements Processor { - + public static final long DEFAULT_BATCH_TIMEOUT = 1000L; public static final int DEFAULT_BATCH_SIZE = 100; @@ -82,9 +86,9 @@ public int getBatchSize() { } /** - * Sets the in batch size. This is the number of incoming exchanges that this batch processor - * will process before its completed. The default value is {@link #DEFAULT_BATCH_SIZE}. - * + * Sets the in batch size. This is the number of incoming exchanges that this batch processor will + * process before its completed. The default value is {@link #DEFAULT_BATCH_SIZE}. + * * @param batchSize the size */ public void setBatchSize(int batchSize) { @@ -96,10 +100,10 @@ public int getOutBatchSize() { } /** - * Sets the out batch size. If the batch processor holds more exchanges than this out size then - * the completion is triggered. Can for instance be used to ensure that this batch is completed when - * a certain number of exchanges has been collected. By default this feature is not enabled. - * + * Sets the out batch size. If the batch processor holds more exchanges than this out size then the + * completion is triggered. Can for instance be used to ensure that this batch is completed when a certain + * number of exchanges has been collected. By default this feature is not enabled. + * * @param outBatchSize the size */ public void setOutBatchSize(int outBatchSize) { @@ -127,16 +131,16 @@ public Processor getProcessor() { } /** - * A strategy method to decide if the ""in"" batch is completed. That is, whether the resulting - * exchanges in the in queue should be drained to the ""out"" collection. + * A strategy method to decide if the ""in"" batch is completed. That is, whether the resulting exchanges in + * the in queue should be drained to the ""out"" collection. */ protected boolean isInBatchCompleted(int num) { return num >= batchSize; } - + /** - * A strategy method to decide if the ""out"" batch is completed. That is, whether the resulting - * exchange in the out collection should be sent. + * A strategy method to decide if the ""out"" batch is completed. That is, whether the resulting exchange in + * the out collection should be sent. */ protected boolean isOutBatchCompleted() { if (outBatchSize == 0) { @@ -147,9 +151,8 @@ protected boolean isOutBatchCompleted() { } /** - * Strategy Method to process an exchange in the batch. This method allows - * derived classes to perform custom processing before or after an - * individual exchange is processed + * Strategy Method to process an exchange in the batch. This method allows derived classes to perform + * custom processing before or after an individual exchange is processed */ protected void processExchange(Exchange exchange) throws Exception { processor.process(exchange); @@ -181,53 +184,119 @@ public void process(Exchange exchange) throws Exception { * Sender thread for queued-up exchanges. */ private class BatchSender extends Thread { - - private volatile boolean cancelRequested; - private LinkedBlockingQueue queue; - + private Queue queue; + private Lock queueLock = new ReentrantLock(); + private boolean exchangeEnqueued; + private Condition exchangeEnqueuedCondition = queueLock.newCondition(); + public BatchSender() { super(""Batch Sender""); - this.queue = new LinkedBlockingQueue(); + this.queue = new LinkedList(); } @Override public void run() { - while (true) { - try { - Thread.sleep(batchTimeout); - queue.drainTo(collection, batchSize); - } catch (InterruptedException e) { - if (cancelRequested) { - return; - } - - while (isInBatchCompleted(queue.size())) { - queue.drainTo(collection, batchSize); - } - - if (!isOutBatchCompleted()) { - continue; + // Wait until one of either: + // * an exchange being queued; + // * the batch timeout expiring; or + // * the thread being cancelled. + // + // If an exchange is queued then we need to determine whether the + // batch is complete. If it is complete then we send out the batched + // exchanges. Otherwise we move back into our wait state. + // + // If the batch times out then we send out the batched exchanges + // collected so far. + // + // If we receive an interrupt then all blocking operations are + // interrupted and our thread terminates. + // + // The goal of the following algorithm in terms of synchronisation + // is to provide fine grained locking i.e. retaining the lock only + // when required. Special consideration is given to releasing the + // lock when calling an overloaded method such as isInBatchComplete, + // isOutBatchComplete and around sendExchanges. The latter is + // especially important as the process of sending out the exchanges + // would otherwise block new exchanges from being queued. + + queueLock.lock(); + try { + do { + try { + if (!exchangeEnqueued) { + exchangeEnqueuedCondition.await(batchTimeout, TimeUnit.MILLISECONDS); + } + + if (!exchangeEnqueued) { + drainQueueTo(collection, batchSize); + } else { + exchangeEnqueued = false; + while (isInBatchCompleted(queue.size())) { + drainQueueTo(collection, batchSize); + } + + queueLock.unlock(); + try { + if (!isOutBatchCompleted()) { + continue; + } + } finally { + queueLock.lock(); + } + } + + queueLock.unlock(); + try { + try { + sendExchanges(); + } catch (Exception e) { + getExceptionHandler().handleException(e); + } + } finally { + queueLock.lock(); + } + + } catch (InterruptedException e) { + break; } - } - try { - sendExchanges(); - } catch (Exception e) { - getExceptionHandler().handleException(e); + + } while (true); + + } finally { + queueLock.unlock(); + } + } + + /** + * This method should be called with queueLock held + */ + private void drainQueueTo(Collection collection, int batchSize) { + for (int i = 0; i < batchSize; ++i) { + Exchange e = queue.poll(); + if (e != null) { + collection.add(e); + } else { + break; } } } - + public void cancel() { - cancelRequested = true; interrupt(); } - + public void enqueueExchange(Exchange exchange) { - queue.add(exchange); - interrupt(); + queueLock.lock(); + try { + queue.add(exchange); + exchangeEnqueued = true; + exchangeEnqueuedCondition.signal(); + } finally { + queueLock.unlock(); + } } - + private void sendExchanges() throws Exception { GroupedExchange grouped = null; @@ -253,5 +322,5 @@ private void sendExchanges() throws Exception { } } } - + }" 84f6d17c7bae1fbe1437ca0f62be476e012dbe8c,spring-framework,"Clean up spring-expression tests warnings--Clean up compiler warnings in the tests of spring-expression. This-commit adds type parameters to some of the types (mostly `List` and-`Map`). Some of them can't be cleaned up, some tests are even-specifically for raw types.-",p,https://github.com/spring-projects/spring-framework,"diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java index d8e871e3c988..c4b1df90bcfa 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -75,14 +75,14 @@ public void testConversionsAvailable() throws Exception { // ArrayList containing List to List Class clazz = typeDescriptorForListOfString.getElementTypeDescriptor().getType(); assertEquals(String.class,clazz); - List l = (List) tcs.convertValue(listOfInteger, TypeDescriptor.forObject(listOfInteger), typeDescriptorForListOfString); + List l = (List) tcs.convertValue(listOfInteger, TypeDescriptor.forObject(listOfInteger), typeDescriptorForListOfString); assertNotNull(l); // ArrayList containing List to List clazz = typeDescriptorForListOfInteger.getElementTypeDescriptor().getType(); assertEquals(Integer.class,clazz); - l = (List) tcs.convertValue(listOfString, TypeDescriptor.forObject(listOfString), typeDescriptorForListOfString); + l = (List) tcs.convertValue(listOfString, TypeDescriptor.forObject(listOfString), typeDescriptorForListOfString); assertNotNull(l); } @@ -95,7 +95,7 @@ public void testSetParameterizedList() throws Exception { // Assign a List to the List field - the component elements should be converted parser.parseExpression(""listOfInteger"").setValue(context,listOfString); assertEquals(3,e.getValue(context,Integer.class).intValue()); // size now 3 - Class clazz = parser.parseExpression(""listOfInteger[1].getClass()"").getValue(context,Class.class); // element type correctly Integer + Class clazz = parser.parseExpression(""listOfInteger[1].getClass()"").getValue(context, Class.class); // element type correctly Integer assertEquals(Integer.class,clazz); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java index aebe15846839..9758a93977cb 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.expression.spel; import static org.junit.Assert.assertEquals; @@ -64,12 +80,12 @@ public static class MapAccessor implements PropertyAccessor { @Override public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { - return (((Map) target).containsKey(name)); + return (((Map) target).containsKey(name)); } @Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { - return new TypedValue(((Map) target).get(name)); + return new TypedValue(((Map) target).get(name)); } @Override @@ -298,7 +314,7 @@ public void emptyList() { @Test public void resolveCollectionElementType() { - listNotGeneric = new ArrayList(); + listNotGeneric = new ArrayList(2); listNotGeneric.add(5); listNotGeneric.add(6); SpelExpressionParser parser = new SpelExpressionParser(); @@ -338,7 +354,7 @@ public void resolveMapKeyValueTypes() { @Test public void testListOfScalar() { - listOfScalarNotGeneric = new ArrayList(); + listOfScalarNotGeneric = new ArrayList(1); listOfScalarNotGeneric.add(""5""); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(""listOfScalarNotGeneric[0]""); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java index ae65b1983da2..60b3550177a1 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java @@ -182,12 +182,12 @@ public static class MapAccessor implements PropertyAccessor { @Override public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { - return (((Map) target).containsKey(name)); + return (((Map) target).containsKey(name)); } @Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { - return new TypedValue(((Map) target).get(name)); + return new TypedValue(((Map) target).get(name)); } @Override diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java index 30f68a4053b7..f3c1bb5bc26f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SelectionAndProjectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public void selectionWithList() throws Exception { EvaluationContext context = new StandardEvaluationContext(new ListTestBean()); Object value = expression.getValue(context); assertTrue(value instanceof List); - List list = (List) value; + List list = (List) value; assertEquals(5, list.size()); assertEquals(0, list.get(0)); assertEquals(1, list.get(1)); @@ -79,7 +79,7 @@ public void selectionWithSet() throws Exception { EvaluationContext context = new StandardEvaluationContext(new SetTestBean()); Object value = expression.getValue(context); assertTrue(value instanceof List); - List list = (List) value; + List list = (List) value; assertEquals(5, list.size()); assertEquals(0, list.get(0)); assertEquals(1, list.get(1)); @@ -221,7 +221,7 @@ public void projectionWithList() throws Exception { context.setVariable(""testList"", IntegerTestBean.createList()); Object value = expression.getValue(context); assertTrue(value instanceof List); - List list = (List) value; + List list = (List) value; assertEquals(3, list.size()); assertEquals(5, list.get(0)); assertEquals(6, list.get(1)); @@ -235,7 +235,7 @@ public void projectionWithSet() throws Exception { context.setVariable(""testList"", IntegerTestBean.createSet()); Object value = expression.getValue(context); assertTrue(value instanceof List); - List list = (List) value; + List list = (List) value; assertEquals(3, list.size()); assertEquals(5, list.get(0)); assertEquals(6, list.get(1)); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java index 30d71941b9c0..45402fc63ebc 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -166,15 +166,15 @@ public void testSetGenericMapElementRequiresCoercion() throws Exception { e.setValue(eContext, ""true""); // All keys should be strings - Set ks = parse(""mapOfStringToBoolean.keySet()"").getValue(eContext,Set.class); + Set ks = parse(""mapOfStringToBoolean.keySet()"").getValue(eContext, Set.class); for (Object o: ks) { assertEquals(String.class,o.getClass()); } // All values should be booleans - Collection vs = parse(""mapOfStringToBoolean.values()"").getValue(eContext,Collection.class); + Collection vs = parse(""mapOfStringToBoolean.values()"").getValue(eContext, Collection.class); for (Object o: vs) { - assertEquals(Boolean.class,o.getClass()); + assertEquals(Boolean.class, o.getClass()); } // One final test check coercion on the key for a map lookup diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java index 002fef3a96cd..02b92f6b9b49 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -383,8 +383,8 @@ public void testAssignment() throws Exception { @Test public void testTypes() throws Exception { - Class dateClass = parser.parseExpression(""T(java.util.Date)"").getValue(Class.class); - assertEquals(Date.class,dateClass); + Class dateClass = parser.parseExpression(""T(java.util.Date)"").getValue(Class.class); + assertEquals(Date.class, dateClass); boolean trueValue = parser.parseExpression(""T(java.math.RoundingMode).CEILING < T(java.math.RoundingMode).FLOOR"").getValue(Boolean.class); assertTrue(trueValue); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java index 32447dda910f..a4ef723a8f66 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -481,7 +481,7 @@ static class Unconvertable {} /** * Used to validate the match returned from a compareArguments call. */ - private void checkMatch(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { + private void checkMatch(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArguments(getTypeDescriptors(expectedTypes), getTypeDescriptors(inputTypes), typeConverter); if (expectedMatchKind == null) { assertNull(""Did not expect them to match in any way"", matchInfo); @@ -504,7 +504,7 @@ else if (expectedMatchKind == ArgumentsMatchKind.REQUIRES_CONVERSION) { /** * Used to validate the match returned from a compareArguments call. */ - private void checkMatch2(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { + private void checkMatch2(Class[] inputTypes, Class[] expectedTypes, StandardTypeConverter typeConverter, ArgumentsMatchKind expectedMatchKind) { ReflectionHelper.ArgumentsMatchInfo matchInfo = ReflectionHelper.compareArgumentsVarargs(getTypeDescriptors(expectedTypes), getTypeDescriptors(inputTypes), typeConverter); if (expectedMatchKind == null) { assertNull(""Did not expect them to match in any way: "" + matchInfo, matchInfo); @@ -535,9 +535,9 @@ private void checkArgument(Object expected, Object actual) { assertEquals(expected,actual); } - private List getTypeDescriptors(Class... types) { + private List getTypeDescriptors(Class... types) { List typeDescriptors = new ArrayList(types.length); - for (Class type : types) { + for (Class type : types) { typeDescriptors.add(TypeDescriptor.valueOf(type)); } return typeDescriptors;" a342029d36fc8cdd6be3ab540cd2527ddd022188,elasticsearch,"Histogram Facet: Allow to define a key field and- value script, closes -517.--",a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java index 7c7d7def474f9..8c1ae4e0f8b03 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java @@ -95,6 +95,7 @@ public KeyValueScriptHistogramFacetCollector(String facetName, String fieldName, @Override protected void doSetNextReader(IndexReader reader, int docBase) throws IOException { fieldData = (NumericFieldData) fieldDataCache.cache(fieldDataType, reader, indexFieldName); + valueScript.setNextReader(reader); } @Override public Facet facet() {" 9da487e0fdbf657f9b401e62d165ab13105488a0,hadoop,YARN-3853. Add docker container runtime support to- LinuxContainterExecutor. Contributed by Sidharta Seethana.--(cherry picked from commit 3e6fce91a471b4a5099de109582e7c6417e8a822)--Conflicts:- hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 993828da00951..724ddd0eea536 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -98,6 +98,10 @@ Release 2.8.0 - UNRELEASED YARN-3852. Add docker container support to container-executor (Abin Shahab via vvasudev) + YARN-3853. Add docker container runtime support to LinuxContainterExecutor. + (Sidharta Seethana via vvasudev) + + IMPROVEMENTS YARN-644. Basic null check is not performed on passed in arguments before diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java index 79f9b0d2910f0..68bfbbfdd148b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/ContainerExecutor.java @@ -24,8 +24,10 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -39,6 +41,7 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; +import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; @@ -160,7 +163,7 @@ public abstract void deleteAsUser(DeletionAsUserContext ctx) * @return true if container is still alive * @throws IOException */ - public abstract boolean isContainerProcessAlive(ContainerLivenessContext ctx) + public abstract boolean isContainerAlive(ContainerLivenessContext ctx) throws IOException; /** @@ -174,6 +177,7 @@ public abstract boolean isContainerProcessAlive(ContainerLivenessContext ctx) */ public int reacquireContainer(ContainerReacquisitionContext ctx) throws IOException, InterruptedException { + Container container = ctx.getContainer(); String user = ctx.getUser(); ContainerId containerId = ctx.getContainerId(); @@ -193,10 +197,11 @@ public int reacquireContainer(ContainerReacquisitionContext ctx) LOG.info(""Reacquiring "" + containerId + "" with pid "" + pid); ContainerLivenessContext livenessContext = new ContainerLivenessContext .Builder() + .setContainer(container) .setUser(user) .setPid(pid) .build(); - while(isContainerProcessAlive(livenessContext)) { + while(isContainerAlive(livenessContext)) { Thread.sleep(1000); } @@ -243,9 +248,20 @@ public void writeLaunchEnv(OutputStream out, Map environment, Map> resources, List command) throws IOException{ ContainerLaunch.ShellScriptBuilder sb = ContainerLaunch.ShellScriptBuilder.create(); + Set whitelist = new HashSet(); + whitelist.add(YarnConfiguration.NM_DOCKER_CONTAINER_EXECUTOR_IMAGE_NAME); + whitelist.add(ApplicationConstants.Environment.HADOOP_YARN_HOME.name()); + whitelist.add(ApplicationConstants.Environment.HADOOP_COMMON_HOME.name()); + whitelist.add(ApplicationConstants.Environment.HADOOP_HDFS_HOME.name()); + whitelist.add(ApplicationConstants.Environment.HADOOP_CONF_DIR.name()); + whitelist.add(ApplicationConstants.Environment.JAVA_HOME.name()); if (environment != null) { for (Map.Entry env : environment.entrySet()) { - sb.env(env.getKey().toString(), env.getValue().toString()); + if (!whitelist.contains(env.getKey())) { + sb.env(env.getKey().toString(), env.getValue().toString()); + } else { + sb.whitelistedEnv(env.getKey().toString(), env.getValue().toString()); + } } } if (resources != null) { @@ -492,6 +508,7 @@ public void run() { try { Thread.sleep(delay); containerExecutor.signalContainer(new ContainerSignalContext.Builder() + .setContainer(container) .setUser(user) .setPid(pid) .setSignal(signal) diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java index b9be2b110e2d0..5819f2378d669 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DefaultContainerExecutor.java @@ -430,7 +430,7 @@ public boolean signalContainer(ContainerSignalContext ctx) } @Override - public boolean isContainerProcessAlive(ContainerLivenessContext ctx) + public boolean isContainerAlive(ContainerLivenessContext ctx) throws IOException { String pid = ctx.getPid(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java index d3b5d0a7dda2e..9dffff3037b34 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/DockerContainerExecutor.java @@ -413,7 +413,7 @@ public boolean signalContainer(ContainerSignalContext ctx) } @Override - public boolean isContainerProcessAlive(ContainerLivenessContext ctx) + public boolean isContainerAlive(ContainerLivenessContext ctx) throws IOException { String pid = ctx.getPid(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java index c60b80b8e97c2..f8e58c1ddddd9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java @@ -20,15 +20,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; @@ -46,10 +37,14 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; -import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandler; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerModule; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.DelegatingLinuxContainerRuntime; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntime; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerLivenessContext; import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerReacquisitionContext; import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext; @@ -60,6 +55,22 @@ import org.apache.hadoop.yarn.server.nodemanager.util.LCEResourcesHandler; import org.apache.hadoop.yarn.util.ConverterUtils; +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*; + +/** Container execution for Linux. Provides linux-specific localization + * mechanisms, resource management via cgroups and can switch between multiple + * container runtimes - e.g Standard ""Process Tree"", Docker etc + */ + public class LinuxContainerExecutor extends ContainerExecutor { private static final Log LOG = LogFactory @@ -73,6 +84,15 @@ public class LinuxContainerExecutor extends ContainerExecutor { private int containerSchedPriorityAdjustment = 0; private boolean containerLimitUsers; private ResourceHandler resourceHandlerChain; + private LinuxContainerRuntime linuxContainerRuntime; + + public LinuxContainerExecutor() { + } + + // created primarily for testing + public LinuxContainerExecutor(LinuxContainerRuntime linuxContainerRuntime) { + this.linuxContainerRuntime = linuxContainerRuntime; + } @Override public void setConf(Configuration conf) { @@ -87,8 +107,8 @@ public void setConf(Configuration conf) { if (conf.get(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY) != null) { containerSchedPriorityIsSet = true; containerSchedPriorityAdjustment = conf - .getInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, - YarnConfiguration.DEFAULT_NM_CONTAINER_EXECUTOR_SCHED_PRIORITY); + .getInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, + YarnConfiguration.DEFAULT_NM_CONTAINER_EXECUTOR_SCHED_PRIORITY); } nonsecureLocalUser = conf.get( YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY, @@ -122,48 +142,6 @@ String getRunAsUser(String user) { } } - - - /** - * List of commands that the setuid script will execute. - */ - enum Commands { - INITIALIZE_CONTAINER(0), - LAUNCH_CONTAINER(1), - SIGNAL_CONTAINER(2), - DELETE_AS_USER(3); - - private int value; - Commands(int value) { - this.value = value; - } - int getValue() { - return value; - } - } - - /** - * Result codes returned from the C container-executor. - * These must match the values in container-executor.h. - */ - enum ResultCode { - OK(0), - INVALID_USER_NAME(2), - UNABLE_TO_EXECUTE_CONTAINER_SCRIPT(7), - INVALID_CONTAINER_PID(9), - INVALID_CONTAINER_EXEC_PERMISSIONS(22), - INVALID_CONFIG_FILE(24), - WRITE_CGROUP_FAILED(27); - - private final int value; - ResultCode(int value) { - this.value = value; - } - int getValue() { - return value; - } - } - protected String getContainerExecutorExecutablePath(Configuration conf) { String yarnHomeEnvVar = System.getenv(ApplicationConstants.Environment.HADOOP_YARN_HOME.key()); @@ -205,9 +183,9 @@ public void init() throws IOException { + "" (error="" + exitCode + "")"", e); } - try { - Configuration conf = super.getConf(); + Configuration conf = super.getConf(); + try { resourceHandlerChain = ResourceHandlerModule .getConfiguredResourceHandlerChain(conf); if (resourceHandlerChain != null) { @@ -218,9 +196,20 @@ public void init() throws IOException { throw new IOException(""Failed to bootstrap configured resource subsystems!""); } + try { + if (linuxContainerRuntime == null) { + LinuxContainerRuntime runtime = new DelegatingLinuxContainerRuntime(); + + runtime.initialize(conf); + this.linuxContainerRuntime = runtime; + } + } catch (ContainerExecutionException e) { + throw new IOException(""Failed to initialize linux container runtime(s)!""); + } + resourcesHandler.init(this); } - + @Override public void startLocalizer(LocalizerStartContext ctx) throws IOException, InterruptedException { @@ -240,7 +229,7 @@ public void startLocalizer(LocalizerStartContext ctx) command.addAll(Arrays.asList(containerExecutorExe, runAsUser, user, - Integer.toString(Commands.INITIALIZE_CONTAINER.getValue()), + Integer.toString(PrivilegedOperation.RunAsUserCommand.INITIALIZE_CONTAINER.getValue()), appId, nmPrivateContainerTokensPath.toUri().getPath().toString(), StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, @@ -296,6 +285,7 @@ public int launchContainer(ContainerStartContext ctx) throws IOException { Path containerWorkDir = ctx.getContainerWorkDir(); List localDirs = ctx.getLocalDirs(); List logDirs = ctx.getLogDirs(); + Map> localizedResources = ctx.getLocalizedResources(); verifyUsernamePattern(user); String runAsUser = getRunAsUser(user); @@ -353,50 +343,48 @@ public int launchContainer(ContainerStartContext ctx) throws IOException { throw new IOException(""ResourceHandlerChain.preStart() failed!""); } - ShellCommandExecutor shExec = null; - try { Path pidFilePath = getPidFilePath(containerId); if (pidFilePath != null) { - List command = new ArrayList(); - addSchedPriorityCommand(command); - command.addAll(Arrays.asList( - containerExecutorExe, runAsUser, user, Integer - .toString(Commands.LAUNCH_CONTAINER.getValue()), appId, - containerIdStr, containerWorkDir.toString(), - nmPrivateContainerScriptPath.toUri().getPath().toString(), - nmPrivateTokensPath.toUri().getPath().toString(), - pidFilePath.toString(), - StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, - localDirs), - StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, - logDirs), - resourcesOptions)); + List prefixCommands= new ArrayList<>(); + ContainerRuntimeContext.Builder builder = new ContainerRuntimeContext + .Builder(container); + + addSchedPriorityCommand(prefixCommands); + if (prefixCommands.size() > 0) { + builder.setExecutionAttribute(CONTAINER_LAUNCH_PREFIX_COMMANDS, + prefixCommands); + } + + builder.setExecutionAttribute(LOCALIZED_RESOURCES, localizedResources) + .setExecutionAttribute(RUN_AS_USER, runAsUser) + .setExecutionAttribute(USER, user) + .setExecutionAttribute(APPID, appId) + .setExecutionAttribute(CONTAINER_ID_STR, containerIdStr) + .setExecutionAttribute(CONTAINER_WORK_DIR, containerWorkDir) + .setExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH, + nmPrivateContainerScriptPath) + .setExecutionAttribute(NM_PRIVATE_TOKENS_PATH, nmPrivateTokensPath) + .setExecutionAttribute(PID_FILE_PATH, pidFilePath) + .setExecutionAttribute(LOCAL_DIRS, localDirs) + .setExecutionAttribute(LOG_DIRS, logDirs) + .setExecutionAttribute(RESOURCES_OPTIONS, resourcesOptions); if (tcCommandFile != null) { - command.add(tcCommandFile); + builder.setExecutionAttribute(TC_COMMAND_FILE, tcCommandFile); } - String[] commandArray = command.toArray(new String[command.size()]); - shExec = new ShellCommandExecutor(commandArray, null, // NM's cwd - container.getLaunchContext().getEnvironment()); // sanitized env - if (LOG.isDebugEnabled()) { - LOG.debug(""launchContainer: "" + Arrays.toString(commandArray)); - } - shExec.execute(); - if (LOG.isDebugEnabled()) { - logOutput(shExec.getOutput()); - } + linuxContainerRuntime.launchContainer(builder.build()); } else { LOG.info(""Container was marked as inactive. Returning terminated error""); return ExitCode.TERMINATED.getExitCode(); } - } catch (ExitCodeException e) { - int exitCode = shExec.getExitCode(); + } catch (ContainerExecutionException e) { + int exitCode = e.getExitCode(); LOG.warn(""Exit code from container "" + containerId + "" is : "" + exitCode); // 143 (SIGTERM) and 137 (SIGKILL) exit codes means the container was // terminated/killed forcefully. In all other cases, log the - // container-executor's output + // output if (exitCode != ExitCode.FORCE_KILLED.getExitCode() && exitCode != ExitCode.TERMINATED.getExitCode()) { LOG.warn(""Exception from container-launch with container ID: "" @@ -406,13 +394,13 @@ public int launchContainer(ContainerStartContext ctx) throws IOException { builder.append(""Exception from container-launch.\n""); builder.append(""Container id: "" + containerId + ""\n""); builder.append(""Exit code: "" + exitCode + ""\n""); - if (!Optional.fromNullable(e.getMessage()).or("""").isEmpty()) { - builder.append(""Exception message: "" + e.getMessage() + ""\n""); + if (!Optional.fromNullable(e.getErrorOutput()).or("""").isEmpty()) { + builder.append(""Exception message: "" + e.getErrorOutput() + ""\n""); } builder.append(""Stack trace: "" + StringUtils.stringifyException(e) + ""\n""); - if (!shExec.getOutput().isEmpty()) { - builder.append(""Shell output: "" + shExec.getOutput() + ""\n""); + if (!e.getOutput().isEmpty()) { + builder.append(""Shell output: "" + e.getOutput() + ""\n""); } String diagnostics = builder.toString(); logOutput(diagnostics); @@ -435,10 +423,7 @@ public int launchContainer(ContainerStartContext ctx) throws IOException { ""containerId: "" + containerId + "". Exception: "" + e); } } - if (LOG.isDebugEnabled()) { - LOG.debug(""Output from LinuxContainerExecutor's launchContainer follows:""); - logOutput(shExec.getOutput()); - } + return 0; } @@ -476,6 +461,7 @@ public int reacquireContainer(ContainerReacquisitionContext ctx) @Override public boolean signalContainer(ContainerSignalContext ctx) throws IOException { + Container container = ctx.getContainer(); String user = ctx.getUser(); String pid = ctx.getPid(); Signal signal = ctx.getSignal(); @@ -483,30 +469,27 @@ public boolean signalContainer(ContainerSignalContext ctx) verifyUsernamePattern(user); String runAsUser = getRunAsUser(user); - String[] command = - new String[] { containerExecutorExe, - runAsUser, - user, - Integer.toString(Commands.SIGNAL_CONTAINER.getValue()), - pid, - Integer.toString(signal.getValue()) }; - ShellCommandExecutor shExec = new ShellCommandExecutor(command); - if (LOG.isDebugEnabled()) { - LOG.debug(""signalContainer: "" + Arrays.toString(command)); - } + ContainerRuntimeContext runtimeContext = new ContainerRuntimeContext + .Builder(container) + .setExecutionAttribute(RUN_AS_USER, runAsUser) + .setExecutionAttribute(USER, user) + .setExecutionAttribute(PID, pid) + .setExecutionAttribute(SIGNAL, signal) + .build(); + try { - shExec.execute(); - } catch (ExitCodeException e) { - int ret_code = shExec.getExitCode(); - if (ret_code == ResultCode.INVALID_CONTAINER_PID.getValue()) { + linuxContainerRuntime.signalContainer(runtimeContext); + } catch (ContainerExecutionException e) { + int retCode = e.getExitCode(); + if (retCode == PrivilegedOperation.ResultCode.INVALID_CONTAINER_PID.getValue()) { return false; } LOG.warn(""Error in signalling container "" + pid + "" with "" + signal - + ""; exit = "" + ret_code, e); - logOutput(shExec.getOutput()); + + ""; exit = "" + retCode, e); + logOutput(e.getOutput()); throw new IOException(""Problem signalling container "" + pid + "" with "" - + signal + ""; output: "" + shExec.getOutput() + "" and exitCode: "" - + ret_code, e); + + signal + ""; output: "" + e.getOutput() + "" and exitCode: "" + + retCode, e); } return true; } @@ -526,7 +509,8 @@ public void deleteAsUser(DeletionAsUserContext ctx) { Arrays.asList(containerExecutorExe, runAsUser, user, - Integer.toString(Commands.DELETE_AS_USER.getValue()), + Integer.toString(PrivilegedOperation. + RunAsUserCommand.DELETE_AS_USER.getValue()), dirString)); List pathsToDelete = new ArrayList(); if (baseDirs == null || baseDirs.size() == 0) { @@ -560,13 +544,15 @@ public void deleteAsUser(DeletionAsUserContext ctx) { } @Override - public boolean isContainerProcessAlive(ContainerLivenessContext ctx) + public boolean isContainerAlive(ContainerLivenessContext ctx) throws IOException { String user = ctx.getUser(); String pid = ctx.getPid(); + Container container = ctx.getContainer(); // Send a test signal to the process as the user to see if it's alive return signalContainer(new ContainerSignalContext.Builder() + .setContainer(container) .setUser(user) .setPid(pid) .setSignal(Signal.NULL) diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java index af168c5943bd6..bf00d74dce7ef 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/ContainerLaunch.java @@ -303,6 +303,7 @@ public Integer call() { exec.activateContainer(containerID, pidFilePath); ret = exec.launchContainer(new ContainerStartContext.Builder() .setContainer(container) + .setLocalizedResources(localResources) .setNmPrivateContainerScriptPath(nmPrivateContainerScriptPath) .setNmPrivateTokensPath(nmPrivateTokensPath) .setUser(user) @@ -427,6 +428,7 @@ public void cleanupContainer() throws IOException { boolean result = exec.signalContainer( new ContainerSignalContext.Builder() + .setContainer(container) .setUser(user) .setPid(processId) .setSignal(signal) @@ -528,6 +530,8 @@ public static ShellScriptBuilder create() { public abstract void command(List command) throws IOException; + public abstract void whitelistedEnv(String key, String value) throws IOException; + public abstract void env(String key, String value) throws IOException; public final void symlink(Path src, Path dst) throws IOException { @@ -585,6 +589,11 @@ public void command(List command) { errorCheck(); } + @Override + public void whitelistedEnv(String key, String value) { + line(""export "", key, ""=${"", key, "":-"", ""\"""", value, ""\""}""); + } + @Override public void env(String key, String value) { line(""export "", key, ""=\"""", value, ""\""""); @@ -626,6 +635,12 @@ public void command(List command) throws IOException { errorCheck(); } + @Override + public void whitelistedEnv(String key, String value) throws IOException { + lineWithLenCheck(""@set "", key, ""="", value); + errorCheck(); + } + @Override public void env(String key, String value) throws IOException { lineWithLenCheck(""@set "", key, ""="", value); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java index f220cbd98f7cd..cbbf7a80c0b00 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperation.java @@ -45,10 +45,12 @@ public enum OperationType { LAUNCH_CONTAINER(""""), //no CLI switch supported yet SIGNAL_CONTAINER(""""), //no CLI switch supported yet DELETE_AS_USER(""""), //no CLI switch supported yet + LAUNCH_DOCKER_CONTAINER(""""), //no CLI switch supported yet TC_MODIFY_STATE(""--tc-modify-state""), TC_READ_STATE(""--tc-read-state""), TC_READ_STATS(""--tc-read-stats""), - ADD_PID_TO_CGROUP(""""); //no CLI switch supported yet. + ADD_PID_TO_CGROUP(""""), //no CLI switch supported yet. + RUN_DOCKER_CMD(""--run-docker""); private final String option; @@ -62,6 +64,7 @@ public String getOption() { } public static final String CGROUP_ARG_PREFIX = ""cgroups=""; + public static final String CGROUP_ARG_NO_TASKS = ""none""; private final OperationType opType; private final List args; @@ -117,4 +120,45 @@ public boolean equals(Object other) { public int hashCode() { return opType.hashCode() + 97 * args.hashCode(); } + + /** + * List of commands that the container-executor will execute. + */ + public enum RunAsUserCommand { + INITIALIZE_CONTAINER(0), + LAUNCH_CONTAINER(1), + SIGNAL_CONTAINER(2), + DELETE_AS_USER(3), + LAUNCH_DOCKER_CONTAINER(4); + + private int value; + RunAsUserCommand(int value) { + this.value = value; + } + public int getValue() { + return value; + } + } + + /** + * Result codes returned from the C container-executor. + * These must match the values in container-executor.h. + */ + public enum ResultCode { + OK(0), + INVALID_USER_NAME(2), + UNABLE_TO_EXECUTE_CONTAINER_SCRIPT(7), + INVALID_CONTAINER_PID(9), + INVALID_CONTAINER_EXEC_PERMISSIONS(22), + INVALID_CONFIG_FILE(24), + WRITE_CGROUP_FAILED(27); + + private final int value; + ResultCode(int value) { + this.value = value; + } + public int getValue() { + return value; + } + } } \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java index 20c234d984a0e..3622489a499f9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationException.java @@ -24,6 +24,9 @@ public class PrivilegedOperationException extends YarnException { private static final long serialVersionUID = 1L; + private Integer exitCode; + private String output; + private String errorOutput; public PrivilegedOperationException() { super(); @@ -33,11 +36,36 @@ public PrivilegedOperationException(String message) { super(message); } + public PrivilegedOperationException(String message, Integer exitCode, + String output, String errorOutput) { + super(message); + this.exitCode = exitCode; + this.output = output; + this.errorOutput = errorOutput; + } + public PrivilegedOperationException(Throwable cause) { super(cause); } + public PrivilegedOperationException(Throwable cause, Integer exitCode, String + output, String errorOutput) { + super(cause); + this.exitCode = exitCode; + this.output = output; + this.errorOutput = errorOutput; + } public PrivilegedOperationException(String message, Throwable cause) { super(message, cause); } -} + + public Integer getExitCode() { + return exitCode; + } + + public String getOutput() { + return output; + } + + public String getErrorOutput() { return errorOutput; } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java index 6fe0f5ce47f3d..1d71938ba2626 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/PrivilegedOperationExecutor.java @@ -20,6 +20,7 @@ package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged; +import com.google.common.annotations.VisibleForTesting; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -101,7 +102,13 @@ public String[] getPrivilegedOperationExecutionCommand(List } fullCommand.add(containerExecutorExe); - fullCommand.add(operation.getOperationType().getOption()); + + String cliSwitch = operation.getOperationType().getOption(); + + if (!cliSwitch.isEmpty()) { + fullCommand.add(cliSwitch); + } + fullCommand.addAll(operation.getArguments()); String[] fullCommandArray = @@ -142,6 +149,8 @@ public String executePrivilegedOperation(List prefixCommands, try { exec.execute(); if (LOG.isDebugEnabled()) { + LOG.debug(""command array:""); + LOG.debug(Arrays.toString(fullCommandArray)); LOG.debug(""Privileged Execution Operation Output:""); LOG.debug(exec.getOutput()); } @@ -152,7 +161,11 @@ public String executePrivilegedOperation(List prefixCommands, .append(System.lineSeparator()).append(exec.getOutput()).toString(); LOG.warn(logLine); - throw new PrivilegedOperationException(e); + + //stderr from shell executor seems to be stuffed into the exception + //'message' - so, we have to extract it and set it as the error out + throw new PrivilegedOperationException(e, e.getExitCode(), + exec.getOutput(), e.getMessage()); } catch (IOException e) { LOG.warn(""IOException executing command: "", e); throw new PrivilegedOperationException(e); @@ -202,7 +215,7 @@ public String executePrivilegedOperation(PrivilegedOperation operation, StringBuffer finalOpArg = new StringBuffer(PrivilegedOperation .CGROUP_ARG_PREFIX); - boolean noneArgsOnly = true; + boolean noTasks = true; for (PrivilegedOperation op : ops) { if (!op.getOperationType() @@ -227,23 +240,24 @@ public String executePrivilegedOperation(PrivilegedOperation operation, throw new PrivilegedOperationException(""Invalid argument: "" + arg); } - if (tasksFile.equals(""none"")) { + if (tasksFile.equals(PrivilegedOperation.CGROUP_ARG_NO_TASKS)) { //Don't append to finalOpArg continue; } - if (noneArgsOnly == false) { + if (noTasks == false) { //We have already appended at least one tasks file. finalOpArg.append(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR); finalOpArg.append(tasksFile); } else { finalOpArg.append(tasksFile); - noneArgsOnly = false; + noTasks = false; } } - if (noneArgsOnly) { - finalOpArg.append(""none""); //there were no tasks file to append + if (noTasks) { + finalOpArg.append(PrivilegedOperation.CGROUP_ARG_NO_TASKS); //there + // were no tasks file to append } PrivilegedOperation finalOp = new PrivilegedOperation( diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java index 70dc8181de888..6020bc1379fd1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandler.java @@ -78,6 +78,14 @@ public String createCGroup(CGroupController controller, String cGroupId) public void deleteCGroup(CGroupController controller, String cGroupId) throws ResourceHandlerException; + /** + * Gets the relative path for the cgroup, independent of a controller, for a + * given cgroup id. + * @param cGroupId - id of the cgroup + * @return path for the cgroup relative to the root of (any) controller. + */ + public String getRelativePathForCGroup(String cGroupId); + /** * Gets the full path for the cgroup, given a controller and a cgroup id * @param controller - controller type for the cgroup diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java index ff5612133990e..0d71a9da83cf5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/CGroupsHandlerImpl.java @@ -147,9 +147,9 @@ static Map initializeControllerPathsFromMtab( } else { String error = new StringBuffer(""Mount point Based on mtab file: "") - .append(mtab) - .append("". Controller mount point not writable for: "") - .append(name).toString(); + .append(mtab) + .append("". Controller mount point not writable for: "") + .append(name).toString(); LOG.error(error); throw new ResourceHandlerException(error); @@ -271,6 +271,12 @@ public void mountCGroupController(CGroupController controller) } } + @Override + public String getRelativePathForCGroup(String cGroupId) { + return new StringBuffer(cGroupPrefix).append(""/"") + .append(cGroupId).toString(); + } + @Override public String getPathForCGroup(CGroupController controller, String cGroupId) { return new StringBuffer(getControllerPath(controller)) diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java new file mode 100644 index 0000000000000..633fa668ae411 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DefaultLinuxContainerRuntime.java @@ -0,0 +1,148 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.util.StringUtils; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; + +import java.util.List; + +import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*; + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public class DefaultLinuxContainerRuntime implements LinuxContainerRuntime { + private static final Log LOG = LogFactory + .getLog(DefaultLinuxContainerRuntime.class); + private Configuration conf; + private final PrivilegedOperationExecutor privilegedOperationExecutor; + + public DefaultLinuxContainerRuntime(PrivilegedOperationExecutor + privilegedOperationExecutor) { + this.privilegedOperationExecutor = privilegedOperationExecutor; + } + + @Override + public void initialize(Configuration conf) + throws ContainerExecutionException { + this.conf = conf; + } + + @Override + public void prepareContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + //nothing to do here at the moment. + } + + @Override + public void launchContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + PrivilegedOperation launchOp = new PrivilegedOperation( + PrivilegedOperation.OperationType.LAUNCH_CONTAINER, (String) null); + + //All of these arguments are expected to be available in the runtime context + launchOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER), + ctx.getExecutionAttribute(USER), + Integer.toString(PrivilegedOperation. + RunAsUserCommand.LAUNCH_CONTAINER.getValue()), + ctx.getExecutionAttribute(APPID), + ctx.getExecutionAttribute(CONTAINER_ID_STR), + ctx.getExecutionAttribute(CONTAINER_WORK_DIR).toString(), + ctx.getExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH).toUri() + .getPath(), + ctx.getExecutionAttribute(NM_PRIVATE_TOKENS_PATH).toUri().getPath(), + ctx.getExecutionAttribute(PID_FILE_PATH).toString(), + StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, + ctx.getExecutionAttribute(LOCAL_DIRS)), + StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, + ctx.getExecutionAttribute(LOG_DIRS)), + ctx.getExecutionAttribute(RESOURCES_OPTIONS)); + + String tcCommandFile = ctx.getExecutionAttribute(TC_COMMAND_FILE); + + if (tcCommandFile != null) { + launchOp.appendArgs(tcCommandFile); + } + + //List -> stored as List -> fetched/converted to List + //we can't do better here thanks to type-erasure + @SuppressWarnings(""unchecked"") + List prefixCommands = (List) ctx.getExecutionAttribute( + CONTAINER_LAUNCH_PREFIX_COMMANDS); + + try { + privilegedOperationExecutor.executePrivilegedOperation(prefixCommands, + launchOp, null, container.getLaunchContext().getEnvironment(), + false); + } catch (PrivilegedOperationException e) { + LOG.warn(""Launch container failed. Exception: "", e); + + throw new ContainerExecutionException(""Launch container failed"", e + .getExitCode(), e.getOutput(), e.getErrorOutput()); + } + } + + @Override + public void signalContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + PrivilegedOperation signalOp = new PrivilegedOperation( + PrivilegedOperation.OperationType.SIGNAL_CONTAINER, (String) null); + + signalOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER), + ctx.getExecutionAttribute(USER), + Integer.toString(PrivilegedOperation.RunAsUserCommand + .SIGNAL_CONTAINER.getValue()), + ctx.getExecutionAttribute(PID), + Integer.toString(ctx.getExecutionAttribute(SIGNAL).getValue())); + + try { + PrivilegedOperationExecutor executor = PrivilegedOperationExecutor + .getInstance(conf); + + executor.executePrivilegedOperation(null, + signalOp, null, container.getLaunchContext().getEnvironment(), + false); + } catch (PrivilegedOperationException e) { + LOG.warn(""Signal container failed. Exception: "", e); + + throw new ContainerExecutionException(""Signal container failed"", e + .getExitCode(), e.getOutput(), e.getErrorOutput()); + } + } + + @Override + public void reapContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java new file mode 100644 index 0000000000000..a59415fff3fcd --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DelegatingLinuxContainerRuntime.java @@ -0,0 +1,110 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; + +import java.util.Map; + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public class DelegatingLinuxContainerRuntime implements LinuxContainerRuntime { + private static final Log LOG = LogFactory + .getLog(DelegatingLinuxContainerRuntime.class); + private DefaultLinuxContainerRuntime defaultLinuxContainerRuntime; + private DockerLinuxContainerRuntime dockerLinuxContainerRuntime; + + @Override + public void initialize(Configuration conf) + throws ContainerExecutionException { + PrivilegedOperationExecutor privilegedOperationExecutor = + PrivilegedOperationExecutor.getInstance(conf); + + defaultLinuxContainerRuntime = new DefaultLinuxContainerRuntime( + privilegedOperationExecutor); + defaultLinuxContainerRuntime.initialize(conf); + dockerLinuxContainerRuntime = new DockerLinuxContainerRuntime( + privilegedOperationExecutor); + dockerLinuxContainerRuntime.initialize(conf); + } + + private LinuxContainerRuntime pickContainerRuntime(Container container) { + Map env = container.getLaunchContext().getEnvironment(); + LinuxContainerRuntime runtime; + + if (DockerLinuxContainerRuntime.isDockerContainerRequested(env)){ + runtime = dockerLinuxContainerRuntime; + } else { + runtime = defaultLinuxContainerRuntime; + } + + if (LOG.isInfoEnabled()) { + LOG.info(""Using container runtime: "" + runtime.getClass() + .getSimpleName()); + } + + return runtime; + } + + @Override + public void prepareContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + LinuxContainerRuntime runtime = pickContainerRuntime(container); + + runtime.prepareContainer(ctx); + } + + @Override + public void launchContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + LinuxContainerRuntime runtime = pickContainerRuntime(container); + + runtime.launchContainer(ctx); + } + + @Override + public void signalContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + LinuxContainerRuntime runtime = pickContainerRuntime(container); + + runtime.signalContainer(ctx); + } + + @Override + public void reapContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + LinuxContainerRuntime runtime = pickContainerRuntime(container); + + runtime.reapContainer(ctx); + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java new file mode 100644 index 0000000000000..2430a7878e82f --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/DockerLinuxContainerRuntime.java @@ -0,0 +1,273 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.util.StringUtils; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerModule; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerClient; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker.DockerRunCommand; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*; + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public class DockerLinuxContainerRuntime implements LinuxContainerRuntime { + private static final Log LOG = LogFactory.getLog( + DockerLinuxContainerRuntime.class); + + @InterfaceAudience.Private + public static final String ENV_DOCKER_CONTAINER_IMAGE = + ""YARN_CONTAINER_RUNTIME_DOCKER_IMAGE""; + @InterfaceAudience.Private + public static final String ENV_DOCKER_CONTAINER_IMAGE_FILE = + ""YARN_CONTAINER_RUNTIME_DOCKER_IMAGE_FILE""; + @InterfaceAudience.Private + public static final String ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE = + ""YARN_CONTAINER_RUNTIME_DOCKER_RUN_OVERRIDE_DISABLE""; + + + private Configuration conf; + private DockerClient dockerClient; + private PrivilegedOperationExecutor privilegedOperationExecutor; + + public static boolean isDockerContainerRequested( + Map env) { + if (env == null) { + return false; + } + + String type = env.get(ContainerRuntimeConstants.ENV_CONTAINER_TYPE); + + return type != null && type.equals(""docker""); + } + + public DockerLinuxContainerRuntime(PrivilegedOperationExecutor + privilegedOperationExecutor) { + this.privilegedOperationExecutor = privilegedOperationExecutor; + } + + @Override + public void initialize(Configuration conf) + throws ContainerExecutionException { + this.conf = conf; + dockerClient = new DockerClient(conf); + } + + @Override + public void prepareContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + + } + + public void addCGroupParentIfRequired(String resourcesOptions, + String containerIdStr, DockerRunCommand runCommand) + throws ContainerExecutionException { + if (resourcesOptions.equals( + (PrivilegedOperation.CGROUP_ARG_PREFIX + PrivilegedOperation + .CGROUP_ARG_NO_TASKS))) { + if (LOG.isInfoEnabled()) { + LOG.info(""no resource restrictions specified. not using docker's "" + + ""cgroup options""); + } + } else { + if (LOG.isInfoEnabled()) { + LOG.info(""using docker's cgroups options""); + } + + try { + CGroupsHandler cGroupsHandler = ResourceHandlerModule + .getCGroupsHandler(conf); + String cGroupPath = ""/"" + cGroupsHandler.getRelativePathForCGroup( + containerIdStr); + + if (LOG.isInfoEnabled()) { + LOG.info(""using cgroup parent: "" + cGroupPath); + } + + runCommand.setCGroupParent(cGroupPath); + } catch (ResourceHandlerException e) { + LOG.warn(""unable to use cgroups handler. Exception: "", e); + throw new ContainerExecutionException(e); + } + } + } + + + @Override + public void launchContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + Map environment = container.getLaunchContext() + .getEnvironment(); + String imageName = environment.get(ENV_DOCKER_CONTAINER_IMAGE); + + if (imageName == null) { + throw new ContainerExecutionException(ENV_DOCKER_CONTAINER_IMAGE + + "" not set!""); + } + + String containerIdStr = container.getContainerId().toString(); + String runAsUser = ctx.getExecutionAttribute(RUN_AS_USER); + Path containerWorkDir = ctx.getExecutionAttribute(CONTAINER_WORK_DIR); + //List -> stored as List -> fetched/converted to List + //we can't do better here thanks to type-erasure + @SuppressWarnings(""unchecked"") + List localDirs = ctx.getExecutionAttribute(LOCAL_DIRS); + @SuppressWarnings(""unchecked"") + List logDirs = ctx.getExecutionAttribute(LOG_DIRS); + @SuppressWarnings(""unchecked"") + DockerRunCommand runCommand = new DockerRunCommand(containerIdStr, + runAsUser, imageName) + .detachOnRun() + .setContainerWorkDir(containerWorkDir.toString()) + .setNetworkType(""host"") + .addMountLocation(""/etc/passwd"", ""/etc/password:ro""); + List allDirs = new ArrayList<>(localDirs); + + allDirs.add(containerWorkDir.toString()); + allDirs.addAll(logDirs); + for (String dir: allDirs) { + runCommand.addMountLocation(dir, dir); + } + + String resourcesOpts = ctx.getExecutionAttribute(RESOURCES_OPTIONS); + + /** Disabling docker's cgroup parent support for the time being. Docker + * needs to use a more recent libcontainer that supports net_cls. In + * addition we also need to revisit current cgroup creation in YARN. + */ + //addCGroupParentIfRequired(resourcesOpts, containerIdStr, runCommand); + + Path nmPrivateContainerScriptPath = ctx.getExecutionAttribute( + NM_PRIVATE_CONTAINER_SCRIPT_PATH); + + String disableOverride = environment.get( + ENV_DOCKER_CONTAINER_RUN_OVERRIDE_DISABLE); + + if (disableOverride != null && disableOverride.equals(""true"")) { + if (LOG.isInfoEnabled()) { + LOG.info(""command override disabled""); + } + } else { + List overrideCommands = new ArrayList<>(); + Path launchDst = + new Path(containerWorkDir, ContainerLaunch.CONTAINER_SCRIPT); + + overrideCommands.add(""bash""); + overrideCommands.add(launchDst.toUri().getPath()); + runCommand.setOverrideCommandWithArgs(overrideCommands); + } + + String commandFile = dockerClient.writeCommandToTempFile(runCommand, + containerIdStr); + PrivilegedOperation launchOp = new PrivilegedOperation( + PrivilegedOperation.OperationType.LAUNCH_DOCKER_CONTAINER, (String) + null); + + launchOp.appendArgs(runAsUser, ctx.getExecutionAttribute(USER), + Integer.toString(PrivilegedOperation + .RunAsUserCommand.LAUNCH_DOCKER_CONTAINER.getValue()), + ctx.getExecutionAttribute(APPID), + containerIdStr, containerWorkDir.toString(), + nmPrivateContainerScriptPath.toUri().getPath(), + ctx.getExecutionAttribute(NM_PRIVATE_TOKENS_PATH).toUri().getPath(), + ctx.getExecutionAttribute(PID_FILE_PATH).toString(), + StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, + localDirs), + StringUtils.join(PrivilegedOperation.LINUX_FILE_PATH_SEPARATOR, + logDirs), + commandFile, + resourcesOpts); + + String tcCommandFile = ctx.getExecutionAttribute(TC_COMMAND_FILE); + + if (tcCommandFile != null) { + launchOp.appendArgs(tcCommandFile); + } + + try { + privilegedOperationExecutor.executePrivilegedOperation(null, + launchOp, null, container.getLaunchContext().getEnvironment(), + false); + } catch (PrivilegedOperationException e) { + LOG.warn(""Launch container failed. Exception: "", e); + + throw new ContainerExecutionException(""Launch container failed"", e + .getExitCode(), e.getOutput(), e.getErrorOutput()); + } + } + + @Override + public void signalContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + Container container = ctx.getContainer(); + PrivilegedOperation signalOp = new PrivilegedOperation( + PrivilegedOperation.OperationType.SIGNAL_CONTAINER, (String) null); + + signalOp.appendArgs(ctx.getExecutionAttribute(RUN_AS_USER), + ctx.getExecutionAttribute(USER), + Integer.toString(PrivilegedOperation + .RunAsUserCommand.SIGNAL_CONTAINER.getValue()), + ctx.getExecutionAttribute(PID), + Integer.toString(ctx.getExecutionAttribute(SIGNAL).getValue())); + + try { + PrivilegedOperationExecutor executor = PrivilegedOperationExecutor + .getInstance(conf); + + executor.executePrivilegedOperation(null, + signalOp, null, container.getLaunchContext().getEnvironment(), + false); + } catch (PrivilegedOperationException e) { + LOG.warn(""Signal container failed. Exception: "", e); + + throw new ContainerExecutionException(""Signal container failed"", e + .getExitCode(), e.getOutput(), e.getErrorOutput()); + } + } + + @Override + public void reapContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException { + + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java new file mode 100644 index 0000000000000..38aea9d7ba899 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntime.java @@ -0,0 +1,38 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntime; + +/** Linux-specific container runtime implementations must implement this + * interface. + */ + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public interface LinuxContainerRuntime extends ContainerRuntime { + void initialize(Configuration conf) throws ContainerExecutionException; +} + diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java new file mode 100644 index 0000000000000..d2069a9356697 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/LinuxContainerRuntimeConstants.java @@ -0,0 +1,69 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext.Attribute; + +import java.util.List; +import java.util.Map; + +public final class LinuxContainerRuntimeConstants { + private LinuxContainerRuntimeConstants() { + } + + public static final Attribute LOCALIZED_RESOURCES = Attribute + .attribute(Map.class, ""localized_resources""); + public static final Attribute CONTAINER_LAUNCH_PREFIX_COMMANDS = + Attribute.attribute(List.class, ""container_launch_prefix_commands""); + public static final Attribute RUN_AS_USER = + Attribute.attribute(String.class, ""run_as_user""); + public static final Attribute USER = Attribute.attribute(String.class, + ""user""); + public static final Attribute APPID = + Attribute.attribute(String.class, ""appid""); + public static final Attribute CONTAINER_ID_STR = Attribute + .attribute(String.class, ""container_id_str""); + public static final Attribute CONTAINER_WORK_DIR = Attribute + .attribute(Path.class, ""container_work_dir""); + public static final Attribute NM_PRIVATE_CONTAINER_SCRIPT_PATH = + Attribute.attribute(Path.class, ""nm_private_container_script_path""); + public static final Attribute NM_PRIVATE_TOKENS_PATH = Attribute + .attribute(Path.class, ""nm_private_tokens_path""); + public static final Attribute PID_FILE_PATH = Attribute.attribute( + Path.class, ""pid_file_path""); + public static final Attribute LOCAL_DIRS = Attribute.attribute( + List.class, ""local_dirs""); + public static final Attribute LOG_DIRS = Attribute.attribute( + List.class, ""log_dirs""); + public static final Attribute RESOURCES_OPTIONS = Attribute.attribute( + String.class, ""resources_options""); + public static final Attribute TC_COMMAND_FILE = Attribute.attribute( + String.class, ""tc_command_file""); + public static final Attribute CGROUP_RELATIVE_PATH = Attribute + .attribute(String.class, ""cgroup_relative_path""); + + public static final Attribute PID = Attribute.attribute( + String.class, ""pid""); + public static final Attribute SIGNAL = Attribute + .attribute(ContainerExecutor.Signal.class, ""signal""); +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java new file mode 100644 index 0000000000000..faf955f8eea61 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerClient.java @@ -0,0 +1,82 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.Writer; + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public final class DockerClient { + private static final Log LOG = LogFactory.getLog(DockerClient.class); + private static final String TMP_FILE_PREFIX = ""docker.""; + private static final String TMP_FILE_SUFFIX = "".cmd""; + private final String tmpDirPath; + + public DockerClient(Configuration conf) throws ContainerExecutionException { + + String tmpDirBase = conf.get(""hadoop.tmp.dir""); + if (tmpDirBase == null) { + throw new ContainerExecutionException(""hadoop.tmp.dir not set!""); + } + tmpDirPath = tmpDirBase + ""/nm-docker-cmds""; + + File tmpDir = new File(tmpDirPath); + if (!(tmpDir.exists() || tmpDir.mkdirs())) { + LOG.warn(""Unable to create directory: "" + tmpDirPath); + throw new ContainerExecutionException(""Unable to create directory: "" + + tmpDirPath); + } + } + + public String writeCommandToTempFile(DockerCommand cmd, String filePrefix) + throws ContainerExecutionException { + File dockerCommandFile = null; + try { + dockerCommandFile = File.createTempFile(TMP_FILE_PREFIX + filePrefix, + TMP_FILE_SUFFIX, new + File(tmpDirPath)); + + Writer writer = new OutputStreamWriter(new FileOutputStream(dockerCommandFile), + ""UTF-8""); + PrintWriter printWriter = new PrintWriter(writer); + printWriter.print(cmd.getCommandWithArguments()); + printWriter.close(); + + return dockerCommandFile.getAbsolutePath(); + } catch (IOException e) { + LOG.warn(""Unable to write docker command to temporary file!""); + throw new ContainerExecutionException(e); + } + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java new file mode 100644 index 0000000000000..3b76a5cca40ce --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerCommand.java @@ -0,0 +1,66 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.util.StringUtils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@InterfaceAudience.Private +@InterfaceStability.Unstable + +/** Represents a docker sub-command + * e.g 'run', 'load', 'inspect' etc., + */ + +public abstract class DockerCommand { + private final String command; + private final List commandWithArguments; + + protected DockerCommand(String command) { + this.command = command; + this.commandWithArguments = new ArrayList<>(); + commandWithArguments.add(command); + } + + /** Returns the docker sub-command string being used + * e.g 'run' + */ + public final String getCommandOption() { + return this.command; + } + + /** Add command commandWithArguments - this method is only meant for use by + * sub-classes + * @param arguments to be added + */ + protected final void addCommandArguments(String... arguments) { + this.commandWithArguments.addAll(Arrays.asList(arguments)); + } + + public String getCommandWithArguments() { + return StringUtils.join("" "", commandWithArguments); + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java new file mode 100644 index 0000000000000..e4d92e08bc168 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerLoadCommand.java @@ -0,0 +1,30 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker; + +public class DockerLoadCommand extends DockerCommand { + private static final String LOAD_COMMAND = ""load""; + + public DockerLoadCommand(String localImageFile) { + super(LOAD_COMMAND); + super.addCommandArguments(""--i="" + localImageFile); + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java new file mode 100644 index 0000000000000..f9a890e9d3041 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/docker/DockerRunCommand.java @@ -0,0 +1,107 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.docker; + +import org.apache.hadoop.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; + +public class DockerRunCommand extends DockerCommand { + private static final String RUN_COMMAND = ""run""; + private final String image; + private List overrrideCommandWithArgs; + + /** The following are mandatory: */ + public DockerRunCommand(String containerId, String user, String image) { + super(RUN_COMMAND); + super.addCommandArguments(""--name="" + containerId, ""--user="" + user); + this.image = image; + } + + public DockerRunCommand removeContainerOnExit() { + super.addCommandArguments(""--rm""); + return this; + } + + public DockerRunCommand detachOnRun() { + super.addCommandArguments(""-d""); + return this; + } + + public DockerRunCommand setContainerWorkDir(String workdir) { + super.addCommandArguments(""--workdir="" + workdir); + return this; + } + + public DockerRunCommand setNetworkType(String type) { + super.addCommandArguments(""--net="" + type); + return this; + } + + public DockerRunCommand addMountLocation(String sourcePath, String + destinationPath) { + super.addCommandArguments(""-v"", sourcePath + "":"" + destinationPath); + return this; + } + + public DockerRunCommand setCGroupParent(String parentPath) { + super.addCommandArguments(""--cgroup-parent="" + parentPath); + return this; + } + + public DockerRunCommand addDevice(String sourceDevice, String + destinationDevice) { + super.addCommandArguments(""--device="" + sourceDevice + "":"" + + destinationDevice); + return this; + } + + public DockerRunCommand enableDetach() { + super.addCommandArguments(""--detach=true""); + return this; + } + + public DockerRunCommand disableDetach() { + super.addCommandArguments(""--detach=false""); + return this; + } + + public DockerRunCommand setOverrideCommandWithArgs( + List overrideCommandWithArgs) { + this.overrrideCommandWithArgs = overrideCommandWithArgs; + return this; + } + + @Override + public String getCommandWithArguments() { + List argList = new ArrayList<>(); + + argList.add(super.getCommandWithArguments()); + argList.add(image); + + if (overrrideCommandWithArgs != null) { + argList.addAll(overrrideCommandWithArgs); + } + + return StringUtils.join("" "", argList); + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java new file mode 100644 index 0000000000000..1fbece2205e27 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerExecutionException.java @@ -0,0 +1,85 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.yarn.exceptions.YarnException; + +/** Exception caused in a container runtime impl. 'Runtime' is not used in + * the class name to avoid confusion with a java RuntimeException + */ + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public class ContainerExecutionException extends YarnException { + private static final long serialVersionUID = 1L; + private static final Integer EXIT_CODE_UNSET = -1; + private static final String OUTPUT_UNSET = """"; + + private Integer exitCode; + private String output; + private String errorOutput; + + public ContainerExecutionException(String message) { + super(message); + exitCode = EXIT_CODE_UNSET; + output = OUTPUT_UNSET; + errorOutput = OUTPUT_UNSET; + } + + public ContainerExecutionException(Throwable throwable) { + super(throwable); + exitCode = EXIT_CODE_UNSET; + output = OUTPUT_UNSET; + errorOutput = OUTPUT_UNSET; + } + + + public ContainerExecutionException(String message, Integer exitCode, String + output, String errorOutput) { + super(message); + this.exitCode = exitCode; + this.output = output; + this.errorOutput = errorOutput; + } + + public ContainerExecutionException(Throwable cause, Integer exitCode, String + output, String errorOutput) { + super(cause); + this.exitCode = exitCode; + this.output = output; + this.errorOutput = errorOutput; + } + + public Integer getExitCode() { + return exitCode; + } + + public String getOutput() { + return output; + } + + public String getErrorOutput() { + return errorOutput; + } + +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java new file mode 100644 index 0000000000000..e05f3fcb12c52 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntime.java @@ -0,0 +1,50 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; + +/** An abstraction for various container runtime implementations. Examples + * include Process Tree, Docker, Appc runtimes etc., These implementations + * are meant for low-level OS container support - dependencies on + * higher-level nodemananger constructs should be avoided. + */ + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public interface ContainerRuntime { + /** Prepare a container to be ready for launch */ + void prepareContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException; + + /** Launch a container. */ + void launchContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException; + + /** Signal a container - request to terminate, status check etc., */ + void signalContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException; + + /** Any container cleanup that may be required. */ + void reapContainer(ContainerRuntimeContext ctx) + throws ContainerExecutionException; +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java new file mode 100644 index 0000000000000..4473856a2d6ef --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeConstants.java @@ -0,0 +1,33 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime; + +import org.apache.hadoop.classification.InterfaceAudience.Private; + +public class ContainerRuntimeConstants { + + /* Switch container runtimes. Work in progress: These + * parameters may be changed/removed in the future. */ + + @Private + public static final String ENV_CONTAINER_TYPE = + ""YARN_CONTAINER_RUNTIME_TYPE""; +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java new file mode 100644 index 0000000000000..4194b99300683 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/runtime/ContainerRuntimeContext.java @@ -0,0 +1,105 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime; + +import org.apache.hadoop.classification.InterfaceAudience; +import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +@InterfaceAudience.Private +@InterfaceStability.Unstable +public final class ContainerRuntimeContext { + private final Container container; + private final Map, Object> executionAttributes; + + /** An attribute class that attempts to provide better type safety as compared + * with using a map of string to object. + * @param + */ + public static final class Attribute { + private final Class valueClass; + private final String id; + + private Attribute(Class valueClass, String id) { + this.valueClass = valueClass; + this.id = id; + } + + @Override + public int hashCode() { + return valueClass.hashCode() + 31 * id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == null || !(obj instanceof Attribute)){ + return false; + } + + Attribute attribute = (Attribute) obj; + + return valueClass.equals(attribute.valueClass) && id.equals(attribute.id); + } + public static Attribute attribute(Class valueClass, String id) { + return new Attribute(valueClass, id); + } + } + + public static final class Builder { + private final Container container; + private Map, Object> executionAttributes; + + public Builder(Container container) { + executionAttributes = new HashMap<>(); + this.container = container; + } + + public Builder setExecutionAttribute(Attribute attribute, E value) { + this.executionAttributes.put(attribute, attribute.valueClass.cast(value)); + return this; + } + + public ContainerRuntimeContext build() { + return new ContainerRuntimeContext(this); + } + } + + private ContainerRuntimeContext(Builder builder) { + this.container = builder.container; + this.executionAttributes = builder.executionAttributes; + } + + public Container getContainer() { + return this.container; + } + + public Map, Object> getExecutionAttributes() { + return Collections.unmodifiableMap(this.executionAttributes); + } + + public E getExecutionAttribute(Attribute attribute) { + return attribute.valueClass.cast(executionAttributes.get(attribute)); + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java index acadae9e957c1..43113efb88dd6 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerLivenessContext.java @@ -22,6 +22,7 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; /** * Encapsulates information required for container liveness checks. @@ -30,16 +31,23 @@ @InterfaceAudience.Private @InterfaceStability.Unstable public final class ContainerLivenessContext { + private final Container container; private final String user; private final String pid; public static final class Builder { + private Container container; private String user; private String pid; public Builder() { } + public Builder setContainer(Container container) { + this.container = container; + return this; + } + public Builder setUser(String user) { this.user = user; return this; @@ -56,10 +64,15 @@ public ContainerLivenessContext build() { } private ContainerLivenessContext(Builder builder) { + this.container = builder.container; this.user = builder.user; this.pid = builder.pid; } + public Container getContainer() { + return this.container; + } + public String getUser() { return this.user; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java index 8adcab7bf4160..d93cdafd768e2 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerReacquisitionContext.java @@ -23,6 +23,7 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; /** * Encapsulates information required for container reacquisition. @@ -31,16 +32,23 @@ @InterfaceAudience.Private @InterfaceStability.Unstable public final class ContainerReacquisitionContext { + private final Container container; private final String user; private final ContainerId containerId; public static final class Builder { + private Container container; private String user; private ContainerId containerId; public Builder() { } + public Builder setContainer(Container container) { + this.container = container; + return this; + } + public Builder setUser(String user) { this.user = user; return this; @@ -57,10 +65,15 @@ public ContainerReacquisitionContext build() { } private ContainerReacquisitionContext(Builder builder) { + this.container = builder.container; this.user = builder.user; this.containerId = builder.containerId; } + public Container getContainer() { + return this.container; + } + public String getUser() { return this.user; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java index cc40af534291a..56b571bb23cc1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerSignalContext.java @@ -23,6 +23,7 @@ import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor.Signal; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; /** * Encapsulates information required for container signaling. @@ -31,11 +32,13 @@ @InterfaceAudience.Private @InterfaceStability.Unstable public final class ContainerSignalContext { + private final Container container; private final String user; private final String pid; private final Signal signal; public static final class Builder { + private Container container; private String user; private String pid; private Signal signal; @@ -43,6 +46,11 @@ public static final class Builder { public Builder() { } + public Builder setContainer(Container container) { + this.container = container; + return this; + } + public Builder setUser(String user) { this.user = user; return this; @@ -64,11 +72,16 @@ public ContainerSignalContext build() { } private ContainerSignalContext(Builder builder) { + this.container = builder.container; this.user = builder.user; this.pid = builder.pid; this.signal = builder.signal; } + public Container getContainer() { + return this.container; + } + public String getUser() { return this.user; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java index 7dfff02626af4..ffcc519f8b7ba 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/executor/ContainerStartContext.java @@ -25,7 +25,9 @@ import org.apache.hadoop.fs.Path; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; +import java.util.Collections; import java.util.List; +import java.util.Map; /** * Encapsulates information required for starting/launching containers. @@ -35,6 +37,7 @@ @InterfaceStability.Unstable public final class ContainerStartContext { private final Container container; + private final Map> localizedResources; private final Path nmPrivateContainerScriptPath; private final Path nmPrivateTokensPath; private final String user; @@ -45,6 +48,7 @@ public final class ContainerStartContext { public static final class Builder { private Container container; + private Map> localizedResources; private Path nmPrivateContainerScriptPath; private Path nmPrivateTokensPath; private String user; @@ -61,6 +65,12 @@ public Builder setContainer(Container container) { return this; } + public Builder setLocalizedResources(Map> localizedResources) { + this.localizedResources = localizedResources; + return this; + } + public Builder setNmPrivateContainerScriptPath( Path nmPrivateContainerScriptPath) { this.nmPrivateContainerScriptPath = nmPrivateContainerScriptPath; @@ -104,6 +114,7 @@ public ContainerStartContext build() { private ContainerStartContext(Builder builder) { this.container = builder.container; + this.localizedResources = builder.localizedResources; this.nmPrivateContainerScriptPath = builder.nmPrivateContainerScriptPath; this.nmPrivateTokensPath = builder.nmPrivateTokensPath; this.user = builder.user; @@ -117,6 +128,14 @@ public Container getContainer() { return this.container; } + public Map> getLocalizedResources() { + if (this.localizedResources != null) { + return Collections.unmodifiableMap(this.localizedResources); + } else { + return null; + } + } + public Path getNmPrivateContainerScriptPath() { return this.nmPrivateContainerScriptPath; } @@ -138,10 +157,10 @@ public Path getContainerWorkDir() { } public List getLocalDirs() { - return this.localDirs; + return Collections.unmodifiableList(this.localDirs); } public List getLogDirs() { - return this.logDirs; + return Collections.unmodifiableList(this.logDirs); } } \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java index 30c0392b69914..0ef788bcd9819 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestLinuxContainerExecutorWithMocks.java @@ -32,6 +32,8 @@ import java.io.IOException; import java.io.LineNumberReader; import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -50,6 +52,10 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerDiagnosticsUpdateEvent; import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.DefaultLinuxContainerRuntime; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntime; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext; import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext; import org.apache.hadoop.yarn.server.nodemanager.executor.DeletionAsUserContext; @@ -61,11 +67,19 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; + public class TestLinuxContainerExecutorWithMocks { private static final Log LOG = LogFactory .getLog(TestLinuxContainerExecutorWithMocks.class); + private static final String MOCK_EXECUTOR = + ""./src/test/resources/mock-container-executor""; + private static final String MOCK_EXECUTOR_WITH_ERROR = + ""./src/test/resources/mock-container-executer-with-error""; + + private String tmpMockExecutor; private LinuxContainerExecutor mockExec = null; private final File mockParamFile = new File(""./params.txt""); private LocalDirsHandlerService dirsHandler; @@ -88,20 +102,42 @@ private List readMockParams() throws IOException { reader.close(); return ret; } - + + private void setupMockExecutor(String executorPath, Configuration conf) + throws IOException { + //we'll always use the tmpMockExecutor - since + // PrivilegedOperationExecutor can only be initialized once. + + Files.copy(Paths.get(executorPath), Paths.get(tmpMockExecutor), + REPLACE_EXISTING); + + File executor = new File(tmpMockExecutor); + + if (!FileUtil.canExecute(executor)) { + FileUtil.setExecutable(executor, true); + } + String executorAbsolutePath = executor.getAbsolutePath(); + conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, + executorAbsolutePath); + } + @Before - public void setup() { + public void setup() throws IOException, ContainerExecutionException { assumeTrue(!Path.WINDOWS); - File f = new File(""./src/test/resources/mock-container-executor""); - if(!FileUtil.canExecute(f)) { - FileUtil.setExecutable(f, true); - } - String executorPath = f.getAbsolutePath(); + + tmpMockExecutor = System.getProperty(""test.build.data"") + + ""/tmp-mock-container-executor""; + Configuration conf = new Configuration(); - conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath); - mockExec = new LinuxContainerExecutor(); + LinuxContainerRuntime linuxContainerRuntime; + + setupMockExecutor(MOCK_EXECUTOR, conf); + linuxContainerRuntime = new DefaultLinuxContainerRuntime( + PrivilegedOperationExecutor.getInstance(conf)); dirsHandler = new LocalDirsHandlerService(); dirsHandler.init(conf); + linuxContainerRuntime.initialize(conf); + mockExec = new LinuxContainerExecutor(linuxContainerRuntime); mockExec.setConf(conf); } @@ -114,7 +150,7 @@ public void tearDown() { public void testContainerLaunch() throws IOException { String appSubmitter = ""nobody""; String cmd = String.valueOf( - LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue()); + PrivilegedOperation.RunAsUserCommand.LAUNCH_CONTAINER.getValue()); String appId = ""APP_ID""; String containerId = ""CONTAINER_ID""; Container container = mock(Container.class); @@ -161,13 +197,8 @@ public void testContainerLaunch() throws IOException { public void testContainerLaunchWithPriority() throws IOException { // set the scheduler priority to make sure still works with nice -n prio - File f = new File(""./src/test/resources/mock-container-executor""); - if (!FileUtil.canExecute(f)) { - FileUtil.setExecutable(f, true); - } - String executorPath = f.getAbsolutePath(); Configuration conf = new Configuration(); - conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath); + setupMockExecutor(MOCK_EXECUTOR, conf); conf.setInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, 2); mockExec.setConf(conf); @@ -231,20 +262,25 @@ public void testStartLocalizer() throws IOException { @Test - public void testContainerLaunchError() throws IOException { + public void testContainerLaunchError() + throws IOException, ContainerExecutionException { // reinitialize executer - File f = new File(""./src/test/resources/mock-container-executer-with-error""); - if (!FileUtil.canExecute(f)) { - FileUtil.setExecutable(f, true); - } - String executorPath = f.getAbsolutePath(); Configuration conf = new Configuration(); - conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath); + setupMockExecutor(MOCK_EXECUTOR_WITH_ERROR, conf); conf.set(YarnConfiguration.NM_LOCAL_DIRS, ""file:///bin/echo""); conf.set(YarnConfiguration.NM_LOG_DIRS, ""file:///dev/null""); - mockExec = spy(new LinuxContainerExecutor()); + + LinuxContainerExecutor exec; + LinuxContainerRuntime linuxContainerRuntime = new + DefaultLinuxContainerRuntime(PrivilegedOperationExecutor.getInstance + (conf)); + + linuxContainerRuntime.initialize(conf); + exec = new LinuxContainerExecutor(linuxContainerRuntime); + + mockExec = spy(exec); doAnswer( new Answer() { @Override @@ -263,7 +299,7 @@ public Object answer(InvocationOnMock invocationOnMock) String appSubmitter = ""nobody""; String cmd = String - .valueOf(LinuxContainerExecutor.Commands.LAUNCH_CONTAINER.getValue()); + .valueOf(PrivilegedOperation.RunAsUserCommand.LAUNCH_CONTAINER.getValue()); String appId = ""APP_ID""; String containerId = ""CONTAINER_ID""; Container container = mock(Container.class); @@ -299,6 +335,7 @@ public Object answer(InvocationOnMock invocationOnMock) Path pidFile = new Path(workDir, ""pid.txt""); mockExec.activateContainer(cId, pidFile); + int ret = mockExec.launchContainer(new ContainerStartContext.Builder() .setContainer(container) .setNmPrivateContainerScriptPath(scriptPath) @@ -330,16 +367,23 @@ public void testInit() throws Exception { } - @Test public void testContainerKill() throws IOException { String appSubmitter = ""nobody""; String cmd = String.valueOf( - LinuxContainerExecutor.Commands.SIGNAL_CONTAINER.getValue()); + PrivilegedOperation.RunAsUserCommand.SIGNAL_CONTAINER.getValue()); ContainerExecutor.Signal signal = ContainerExecutor.Signal.QUIT; String sigVal = String.valueOf(signal.getValue()); - + + Container container = mock(Container.class); + ContainerId cId = mock(ContainerId.class); + ContainerLaunchContext context = mock(ContainerLaunchContext.class); + + when(container.getContainerId()).thenReturn(cId); + when(container.getLaunchContext()).thenReturn(context); + mockExec.signalContainer(new ContainerSignalContext.Builder() + .setContainer(container) .setUser(appSubmitter) .setPid(""1000"") .setSignal(signal) @@ -353,7 +397,7 @@ public void testContainerKill() throws IOException { public void testDeleteAsUser() throws IOException { String appSubmitter = ""nobody""; String cmd = String.valueOf( - LinuxContainerExecutor.Commands.DELETE_AS_USER.getValue()); + PrivilegedOperation.RunAsUserCommand.DELETE_AS_USER.getValue()); Path dir = new Path(""/tmp/testdir""); Path testFile = new Path(""testfile""); Path baseDir0 = new Path(""/grid/0/BaseDir""); @@ -395,14 +439,9 @@ public void testDeleteAsUser() throws IOException { Arrays.asList(YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER, appSubmitter, cmd, """", baseDir0.toString(), baseDir1.toString()), readMockParams()); - - File f = new File(""./src/test/resources/mock-container-executer-with-error""); - if (!FileUtil.canExecute(f)) { - FileUtil.setExecutable(f, true); - } - String executorPath = f.getAbsolutePath(); + ; Configuration conf = new Configuration(); - conf.set(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH, executorPath); + setupMockExecutor(MOCK_EXECUTOR, conf); mockExec.setConf(conf); mockExec.deleteAsUser(new DeletionAsUserContext.Builder() diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java index 8f297ede75a75..849dbabf20ae2 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java @@ -118,7 +118,7 @@ public void testExecutionCommand() { PrivilegedOperationExecutor exec = PrivilegedOperationExecutor .getInstance(confWithExecutorPath); PrivilegedOperation op = new PrivilegedOperation(PrivilegedOperation - .OperationType.LAUNCH_CONTAINER, (String) null); + .OperationType.TC_MODIFY_STATE, (String) null); String[] cmdArray = exec.getPrivilegedOperationExecutionCommand(null, op); //No arguments added - so the resulting array should consist of @@ -127,10 +127,8 @@ public void testExecutionCommand() { Assert.assertEquals(customExecutorPath, cmdArray[0]); Assert.assertEquals(op.getOperationType().getOption(), cmdArray[1]); - //other (dummy) arguments to launch container - String[] additionalArgs = { ""test_user"", ""yarn"", ""1"", ""app_01"", - ""container_01"", ""workdir"", ""launch_script.sh"", ""tokens"", ""pidfile"", - ""nm-local-dirs"", ""nm-log-dirs"", ""resource-spec"" }; + //other (dummy) arguments to tc modify state + String[] additionalArgs = { ""cmd_file_1"", ""cmd_file_2"", ""cmd_file_3""}; op.appendArgs(additionalArgs); cmdArray = exec.getPrivilegedOperationExecutionCommand(null, op); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java new file mode 100644 index 0000000000000..31ed4963341fb --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java @@ -0,0 +1,219 @@ +/* + * * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; +import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants; +import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.LinuxContainerRuntimeConstants.*; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; + +public class TestDockerContainerRuntime { + private Configuration conf; + PrivilegedOperationExecutor mockExecutor; + String containerId; + Container container; + ContainerId cId; + ContainerLaunchContext context; + HashMap env; + String image; + String runAsUser; + String user; + String appId; + String containerIdStr = containerId; + Path containerWorkDir; + Path nmPrivateContainerScriptPath; + Path nmPrivateTokensPath; + Path pidFilePath; + List localDirs; + List logDirs; + String resourcesOptions; + + @Before + public void setup() { + String tmpPath = new StringBuffer(System.getProperty(""test.build.data"")) + .append + ('/').append(""hadoop.tmp.dir"").toString(); + + conf = new Configuration(); + conf.set(""hadoop.tmp.dir"", tmpPath); + + mockExecutor = Mockito + .mock(PrivilegedOperationExecutor.class); + containerId = ""container_id""; + container = mock(Container.class); + cId = mock(ContainerId.class); + context = mock(ContainerLaunchContext.class); + env = new HashMap(); + image = ""busybox:latest""; + + env.put(DockerLinuxContainerRuntime.ENV_DOCKER_CONTAINER_IMAGE, image); + when(container.getContainerId()).thenReturn(cId); + when(cId.toString()).thenReturn(containerId); + when(container.getLaunchContext()).thenReturn(context); + when(context.getEnvironment()).thenReturn(env); + + runAsUser = ""run_as_user""; + user = ""user""; + appId = ""app_id""; + containerIdStr = containerId; + containerWorkDir = new Path(""/test_container_work_dir""); + nmPrivateContainerScriptPath = new Path(""/test_script_path""); + nmPrivateTokensPath = new Path(""/test_private_tokens_path""); + pidFilePath = new Path(""/test_pid_file_path""); + localDirs = new ArrayList<>(); + logDirs = new ArrayList<>(); + resourcesOptions = ""cgroups:none""; + + localDirs.add(""/test_local_dir""); + logDirs.add(""/test_log_dir""); + } + + @Test + public void testSelectDockerContainerType() { + Map envDockerType = new HashMap<>(); + Map envOtherType = new HashMap<>(); + + envDockerType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, ""docker""); + envOtherType.put(ContainerRuntimeConstants.ENV_CONTAINER_TYPE, ""other""); + + Assert.assertEquals(false, DockerLinuxContainerRuntime + .isDockerContainerRequested(null)); + Assert.assertEquals(true, DockerLinuxContainerRuntime + .isDockerContainerRequested(envDockerType)); + Assert.assertEquals(false, DockerLinuxContainerRuntime + .isDockerContainerRequested(envOtherType)); + } + + @Test + @SuppressWarnings(""unchecked"") + public void testDockerContainerLaunch() + throws ContainerExecutionException, PrivilegedOperationException, + IOException { + DockerLinuxContainerRuntime runtime = new DockerLinuxContainerRuntime( + mockExecutor); + runtime.initialize(conf); + + ContainerRuntimeContext.Builder builder = new ContainerRuntimeContext + .Builder(container); + + builder.setExecutionAttribute(RUN_AS_USER, runAsUser) + .setExecutionAttribute(USER, user) + .setExecutionAttribute(APPID, appId) + .setExecutionAttribute(CONTAINER_ID_STR, containerIdStr) + .setExecutionAttribute(CONTAINER_WORK_DIR, containerWorkDir) + .setExecutionAttribute(NM_PRIVATE_CONTAINER_SCRIPT_PATH, + nmPrivateContainerScriptPath) + .setExecutionAttribute(NM_PRIVATE_TOKENS_PATH, nmPrivateTokensPath) + .setExecutionAttribute(PID_FILE_PATH, pidFilePath) + .setExecutionAttribute(LOCAL_DIRS, localDirs) + .setExecutionAttribute(LOG_DIRS, logDirs) + .setExecutionAttribute(RESOURCES_OPTIONS, resourcesOptions); + + runtime.launchContainer(builder.build()); + + ArgumentCaptor opCaptor = ArgumentCaptor.forClass( + PrivilegedOperation.class); + + //single invocation expected + //due to type erasure + mocking, this verification requires a suppress + // warning annotation on the entire method + verify(mockExecutor, times(1)) + .executePrivilegedOperation(anyList(), opCaptor.capture(), any( + File.class), any(Map.class), eq(false)); + + PrivilegedOperation op = opCaptor.getValue(); + + Assert.assertEquals(PrivilegedOperation.OperationType + .LAUNCH_DOCKER_CONTAINER, op.getOperationType()); + + List args = op.getArguments(); + + //This invocation of container-executor should use 13 arguments in a + // specific order (sigh.) + Assert.assertEquals(13, args.size()); + + //verify arguments + Assert.assertEquals(runAsUser, args.get(0)); + Assert.assertEquals(user, args.get(1)); + Assert.assertEquals(Integer.toString(PrivilegedOperation.RunAsUserCommand + .LAUNCH_DOCKER_CONTAINER.getValue()), args.get(2)); + Assert.assertEquals(appId, args.get(3)); + Assert.assertEquals(containerId, args.get(4)); + Assert.assertEquals(containerWorkDir.toString(), args.get(5)); + Assert.assertEquals(nmPrivateContainerScriptPath.toUri() + .toString(), args.get(6)); + Assert.assertEquals(nmPrivateTokensPath.toUri().getPath(), args.get(7)); + Assert.assertEquals(pidFilePath.toString(), args.get(8)); + Assert.assertEquals(localDirs.get(0), args.get(9)); + Assert.assertEquals(logDirs.get(0), args.get(10)); + Assert.assertEquals(resourcesOptions, args.get(12)); + + String dockerCommandFile = args.get(11); + + //This is the expected docker invocation for this case + StringBuffer expectedCommandTemplate = new StringBuffer(""run --name=%1$s "") + .append(""--user=%2$s -d "") + .append(""--workdir=%3$s "") + .append(""--net=host -v /etc/passwd:/etc/password:ro "") + .append(""-v %4$s:%4$s "") + .append(""-v %5$s:%5$s "") + .append(""-v %6$s:%6$s "") + .append(""%7$s "") + .append(""bash %8$s/launch_container.sh""); + + String expectedCommand = String.format(expectedCommandTemplate.toString(), + containerId, runAsUser, containerWorkDir, localDirs.get(0), + containerWorkDir, logDirs.get(0), image, containerWorkDir); + + List dockerCommands = Files.readAllLines(Paths.get + (dockerCommandFile), Charset.forName(""UTF-8"")); + + Assert.assertEquals(1, dockerCommands.size()); + Assert.assertEquals(expectedCommand, dockerCommands.get(0)); + } +}" 5dfc5a6dff7de7cdff1743a628ee3bb586f6d003,orientdb,last attempt of fixing test failing on ci.--,c,https://github.com/orientechnologies/orientdb,"diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java index 91dca4b5700..de83629074a 100644 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java @@ -20,8 +20,8 @@ package com.orientechnologies.orient.graph; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import com.tinkerpop.blueprints.impls.orient.OrientGraph; @@ -31,7 +31,7 @@ * @author Luca Garulli */ public abstract class GraphTxAbstractTest { - protected OrientGraph graph; + protected static OrientGraph graph; public static enum ENV { DEV, RELEASE, CI @@ -58,8 +58,8 @@ public static String getStorageType() { return ""plocal""; } - @Before - public void beforeClass() { + @BeforeClass + public static void beforeClass() { if (graph == null) { final String dbName = GraphTxAbstractTest.class.getSimpleName(); final String storageType = getStorageType(); @@ -71,9 +71,10 @@ public void beforeClass() { } - @After - public void afterClass() throws Exception { + @AfterClass + public static void afterClass() throws Exception { graph.shutdown(); graph = null; } + } diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java index 2034cc9e7b8..f8bb970d069 100755 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java @@ -20,14 +20,64 @@ package com.orientechnologies.orient.graph.sql; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import com.orientechnologies.orient.core.exception.OTransactionException; import com.orientechnologies.orient.graph.GraphTxAbstractTest; -import org.junit.Test; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +public class RequireTransactionTest { + + protected static OrientGraph graph; + + public static enum ENV { + DEV, RELEASE, CI + } -public class RequireTransactionTest extends GraphTxAbstractTest { + public static ENV getEnvironment() { + String envName = System.getProperty(""orientdb.test.env"", ""dev"").toUpperCase(); + ENV result = null; + try { + result = ENV.valueOf(envName); + } catch (IllegalArgumentException e) { + } + + if (result == null) + result = ENV.DEV; + + return result; + } + + public static String getStorageType() { + if (getEnvironment().equals(ENV.DEV)) + return ""memory""; + + return ""plocal""; + } + + @BeforeClass + public static void beforeClass() { + if (graph == null) { + final String dbName = GraphTxAbstractTest.class.getSimpleName(); + final String storageType = getStorageType(); + final String buildDirectory = System.getProperty(""buildDirectory"", "".""); + graph = new OrientGraph(storageType + "":"" + buildDirectory + ""/"" + dbName); + graph.drop(); + graph = new OrientGraph(storageType + "":"" + buildDirectory + ""/"" + dbName); + } + + } + + @AfterClass + public static void afterClass() throws Exception { + graph.shutdown(); + graph = null; + } @Test public void requireTxEnable() { diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java index 54cc8294ea5..74cbf4750ef 100755 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java @@ -21,6 +21,7 @@ package com.orientechnologies.orient.graph.sql; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; import com.orientechnologies.common.util.OCallable; @@ -34,13 +35,14 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType; public class SQLMoveVertexCommandInTxTest extends GraphTxAbstractTest { - private OrientVertexType customer; - private OrientVertexType provider; - private OrientEdgeType knows; - private int customerGeniusCluster; - - public void beforeClass() { - super.beforeClass(); + private static OrientVertexType customer; + private static OrientVertexType provider; + private static OrientEdgeType knows; + private static int customerGeniusCluster; + + @BeforeClass + public static void beforeClass() { + GraphTxAbstractTest.beforeClass(); graph.executeOutsideTx(new OCallable() { @Override public Object call(OrientBaseGraph iArgument) {" 006b5cd1ab45f53321ff664f46b1335ec018c807,intellij-community,IDEA-78863 Live templates are not accessible in- read-only file (e.g. versioned in Perforce or TFS)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java index 6831a726575d9..7ce8a60063e86 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java @@ -29,6 +29,7 @@ import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.util.EditorUtil; +import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; @@ -40,7 +41,9 @@ public class ListTemplatesHandler implements CodeInsightActionHandler { public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull PsiFile file) { - if (!file.isWritable()) return; + if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) { + return; + } EditorUtil.fillVirtualSpaceUntilCaret(editor); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());" 7ccd3abb7942553d5b1dc6c6c18cdbe9d6ecc129,intellij-community,fix indefinite loop (IDEA-67750)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java index 3c5b1ca1cc100..6ba74f07083f4 100644 --- a/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java +++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/OutputParser.java @@ -251,11 +251,13 @@ public String getCurrentLine() { } public String getNextLine() { - final int next = myIndex + 1; - if (next >= javacMessages.size()) { + final int size = javacMessages.size(); + final int next = Math.min(myIndex + 1, javacMessages.size()); + myIndex = next; + if (next >= size) { return null; } - return javacMessages.get(myIndex = next); + return javacMessages.get(next); } @Override" 72894b26c24b1ea31c6dda4634cfde67e7dc3050,spring-framework,"Fix conversion of Message payload for replies--If a custom MessageConverter is set, it is not used for replies defined-via the Message abstraction. This commit harmonizes the behaviour of the-`MessagingMessageConverter` so that the conversion of the payload can-be converted for both incoming and outgoing messages.--Issue: SPR-12912-",c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java index f910fd430828..cd0516de6d57 100644 --- a/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java +++ b/spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -396,6 +396,15 @@ private class MessagingMessageConverterAdapter extends MessagingMessageConverter protected Object extractPayload(Message message) throws JMSException { return extractMessage(message); } + + @Override + protected Message createMessageForPayload(Object payload, Session session) throws JMSException { + MessageConverter converter = getMessageConverter(); + if (converter != null) { + return converter.toMessage(payload, session); + } + throw new IllegalStateException(""No message converter, cannot handle '"" + payload + ""'""); + } } diff --git a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java index aefa45877e47..a4db74313e9c 100644 --- a/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java +++ b/spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -93,7 +93,7 @@ public javax.jms.Message toMessage(Object object, Session session) throws JMSExc Message.class.getName() + ""] is handled by this converter""); } Message input = (Message) object; - javax.jms.Message reply = this.payloadConverter.toMessage(input.getPayload(), session); + javax.jms.Message reply = createMessageForPayload(input.getPayload(), session); this.headerMapper.fromHeaders(input.getHeaders(), reply); return reply; } @@ -119,4 +119,12 @@ protected Object extractPayload(javax.jms.Message message) throws JMSException { return this.payloadConverter.fromMessage(message); } + /** + * Create a JMS message for the specified payload. + * @see MessageConverter#toMessage(Object, Session) + */ + protected javax.jms.Message createMessageForPayload(Object payload, Session session) throws JMSException { + return this.payloadConverter.toMessage(payload, session); + } + } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java index 5fc400e8bb0d..f5f38d787d33 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -17,6 +17,8 @@ package org.springframework.jms.listener.adapter; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Session; @@ -28,6 +30,7 @@ import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.jms.StubTextMessage; import org.springframework.jms.support.JmsHeaders; +import org.springframework.jms.support.converter.MessageConverter; import org.springframework.messaging.Message; import org.springframework.messaging.converter.MessageConversionException; import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory; @@ -111,6 +114,38 @@ public void exceptionInInvocation() { } } + @Test + public void incomingMessageUsesMessageConverter() throws JMSException { + javax.jms.Message jmsMessage = mock(javax.jms.Message.class); + Session session = mock(Session.class); + MessageConverter messageConverter = mock(MessageConverter.class); + given(messageConverter.fromMessage(jmsMessage)).willReturn(""FooBar""); + MessagingMessageListenerAdapter listener = getSimpleInstance(""simple"", Message.class); + listener.setMessageConverter(messageConverter); + listener.onMessage(jmsMessage, session); + verify(messageConverter, times(1)).fromMessage(jmsMessage); + assertEquals(1, sample.simples.size()); + assertEquals(""FooBar"", sample.simples.get(0).getPayload()); + } + + @Test + public void replyUsesMessageConverterForPayload() throws JMSException { + Session session = mock(Session.class); + MessageConverter messageConverter = mock(MessageConverter.class); + given(messageConverter.toMessage(""Response"", session)).willReturn(new StubTextMessage(""Response"")); + + Message result = MessageBuilder.withPayload(""Response"") + .build(); + + MessagingMessageListenerAdapter listener = getSimpleInstance(""echo"", Message.class); + listener.setMessageConverter(messageConverter); + javax.jms.Message replyMessage = listener.buildMessage(session, result); + + verify(messageConverter, times(1)).toMessage(""Response"", session); + assertNotNull(""reply should never be null"", replyMessage); + assertEquals(""Response"", ((TextMessage) replyMessage).getText()); + } + protected MessagingMessageListenerAdapter getSimpleInstance(String methodName, Class... parameterTypes) { Method m = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes); return createInstance(m); @@ -131,6 +166,12 @@ private void initializeFactory(DefaultMessageHandlerMethodFactory factory) { @SuppressWarnings(""unused"") private static class SampleBean { + public final List> simples = new ArrayList<>(); + + public void simple(Message input) { + simples.add(input); + } + public Message echo(Message input) { return MessageBuilder.withPayload(input.getPayload()) .setHeader(JmsHeaders.TYPE, ""reply"")" cc6bd6239a2cf8db9b661e987e22c36737621db2,kotlin,Remove unused method--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java index 2f07308102b69..bc9a03f608cc9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java @@ -19,7 +19,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.intellij.lang.ASTNode; -import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; @@ -70,7 +69,7 @@ protected BasicExpressionTypingVisitor(@NotNull ExpressionTypingInternals facade public JetTypeInfo visitSimpleNameExpression(JetSimpleNameExpression expression, ExpressionTypingContext context) { // TODO : other members // TODO : type substitutions??? - JetTypeInfo typeInfo = getSelectorReturnTypeInfo(NO_RECEIVER, null, expression, context); + JetTypeInfo typeInfo = getSimpleNameExpressionTypeInfo(expression, NO_RECEIVER, null, context); JetType type = DataFlowUtils.checkType(typeInfo.getType(), expression, context); ExpressionTypingUtils.checkWrappingInRef(expression, context.trace, context.scope); return JetTypeInfo.create(type, typeInfo.getDataFlowInfo()); // TODO : Extensions to this @@ -769,7 +768,7 @@ private JetType getVariableType(@NotNull JetSimpleNameExpression nameExpression, } @NotNull - public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { + private JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { if (selectorExpression instanceof JetCallExpression) { return getCallExpressionTypeInfo((JetCallExpression) selectorExpression, receiver, callOperationNode, context); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java index df4c2a5cac081..c9b826f6d6207 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java @@ -16,20 +16,14 @@ package org.jetbrains.jet.lang.types.expressions; -import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetElement; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.jet.lang.types.JetTypeInfo; /*package*/ interface ExpressionTypingInternals extends ExpressionTypingFacade { - - @NotNull - JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context); - @NotNull JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java index 8d4d338837c9c..ee9a8737fb3cc 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java @@ -16,14 +16,12 @@ package org.jetbrains.jet.lang.types.expressions; -import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.jet.lang.types.DeferredType; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetTypeInfo; @@ -64,11 +62,6 @@ private ExpressionTypingVisitorDispatcher(WritableScope writableScope) { } } - @Override - public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { - return basic.getSelectorReturnTypeInfo(receiver, callOperationNode, selectorExpression, context); - } - @NotNull @Override public JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context) {" 2ea800d7cf8bb3d5455402af7291bac9deb2fe46,orientdb,Index in tx: Fixed issue 468 about deletion--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java index 7d58afbf789..1df1d18a50a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java @@ -886,6 +886,9 @@ public ORecordAbstract setDirty() { e.setDirty(); } } + // THIS IS IMPORTANT TO BE SURE THAT FIELDS ARE LOADED BEFORE IT'S TOO LATE AND THE RECORD _SOURCE IS NULL + checkForFields(); + return super.setDirty(); }" bbb3b5a0d37545dc714d3f95cb7e4650b29db622,intellij-community,IDEA-94048 Maven run configuration - profiles- list gets randomly re-ordered after closing and opening project--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/util/src/com/intellij/util/xmlb/MapBinding.java b/platform/util/src/com/intellij/util/xmlb/MapBinding.java index 98d637e610b32..04435889b5259 100644 --- a/platform/util/src/com/intellij/util/xmlb/MapBinding.java +++ b/platform/util/src/com/intellij/util/xmlb/MapBinding.java @@ -74,7 +74,11 @@ public Object serialize(Object o, Object context, SerializationFilter filter) { final Set keySet = map.keySet(); final Object[] keys = ArrayUtil.toObjectArray(keySet); - Arrays.sort(keys, KEY_COMPARATOR); + + if (myMapAnnotation == null || myMapAnnotation.sortBeforeSave()) { + Arrays.sort(keys, KEY_COMPARATOR); + } + for (Object k : keys) { Object v = map.get(k); diff --git a/platform/util/src/com/intellij/util/xmlb/annotations/MapAnnotation.java b/platform/util/src/com/intellij/util/xmlb/annotations/MapAnnotation.java index 8918ef534b23c..7c11c28b19c04 100644 --- a/platform/util/src/com/intellij/util/xmlb/annotations/MapAnnotation.java +++ b/platform/util/src/com/intellij/util/xmlb/annotations/MapAnnotation.java @@ -34,4 +34,6 @@ boolean surroundKeyWithTag() default true; boolean surroundValueWithTag() default true; + + boolean sortBeforeSave() default true; } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java index e8785146877dc..d0dc2a0c922f5 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerParameters.java @@ -17,6 +17,7 @@ import com.google.common.base.Predicates; import com.google.common.collect.Maps; +import com.intellij.util.xmlb.annotations.MapAnnotation; import com.intellij.util.xmlb.annotations.OptionTag; import com.intellij.util.xmlb.annotations.Transient; import org.jetbrains.annotations.NotNull; @@ -141,6 +142,7 @@ public void fixAfterLoadingFromOldFormat() { } @OptionTag(""profilesMap"") + @MapAnnotation(sortBeforeSave = false) public Map getProfilesMap() { return myProfilesMap; } diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java index 7bc6cb286da51..de2c2adf9627c 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java @@ -28,7 +28,7 @@ public void testSaveLoadRunnerParameters() { MavenRunConfiguration.MavenSettings s = new MavenRunConfiguration.MavenSettings(myProject); s.myRunnerParameters.setWorkingDirPath(""some path""); s.myRunnerParameters.setGoals(Arrays.asList(""clean"", ""validate"")); - s.myRunnerParameters.setProfilesMap(ImmutableMap.of(""prof1"", true, ""prof2"", true, ""prof3"", false)); + s.myRunnerParameters.setProfilesMap(ImmutableMap.of(""prof1"", true, ""prof2"", true, ""prof3"", false, ""aaa"", true)); s.myGeneralSettings = new MavenGeneralSettings(); s.myGeneralSettings.setChecksumPolicy(MavenExecutionOptions.ChecksumPolicy.WARN); @@ -45,6 +45,7 @@ public void testSaveLoadRunnerParameters() { assertEquals(s.myRunnerParameters.getWorkingDirPath(), loaded.myRunnerParameters.getWorkingDirPath()); assertEquals(s.myRunnerParameters.getGoals(), loaded.myRunnerParameters.getGoals()); assertEquals(s.myRunnerParameters.getProfilesMap(), loaded.myRunnerParameters.getProfilesMap()); + assertOrderedEquals(s.myRunnerParameters.getProfilesMap().keySet(), loaded.myRunnerParameters.getProfilesMap().keySet()); // Compare ordering of profiles. assertEquals(s.myGeneralSettings, loaded.myGeneralSettings); assertEquals(s.myRunnerSettings, loaded.myRunnerSettings);" b8acac413b1c85a29a86026b984591fdc9c333fa,camel,CAMEL-2510 Fixed the issue of Mixing jetty/http- in a route screws up the URI used by HttpClient--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@917529 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java b/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java index bc7b7c9e42b24..e553352cdafd2 100644 --- a/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java +++ b/components/camel-http/src/main/java/org/apache/camel/component/http/helper/HttpProducerHelper.java @@ -16,7 +16,11 @@ */ package org.apache.camel.component.http.helper; +import java.net.URI; +import java.net.URISyntaxException; + import org.apache.camel.Exchange; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.component.http.HttpEndpoint; import org.apache.camel.component.http.HttpMethods; @@ -47,18 +51,44 @@ public static String createURL(Exchange exchange, HttpEndpoint endpoint) { } // append HTTP_PATH to HTTP_URI if it is provided in the header - // when the endpoint is not working as a bridge String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); if (path != null) { - // make sure that there is exactly one ""/"" between HTTP_URI and - // HTTP_PATH - if (!uri.endsWith(""/"")) { - uri = uri + ""/""; - } if (path.startsWith(""/"")) { - path = path.substring(1); + URI baseURI; + String baseURIString = exchange.getIn().getHeader(Exchange.HTTP_BASE_URI, String.class); + try { + if (baseURIString == null) { + if (exchange.getFromEndpoint() != null) { + baseURIString = exchange.getFromEndpoint().getEndpointUri(); + } else { + // will set a default one for it + baseURIString = ""/""; + } + } + baseURI = new URI(baseURIString); + String basePath = baseURI.getPath(); + if (path.startsWith(basePath)) { + path = path.substring(basePath.length()); + if (path.startsWith(""/"")) { + path = path.substring(1); + } + } else { + throw new RuntimeCamelException(""Can't anylze the Exchange.HTTP_PATH header, due to: can't find the right HTTP_BASE_URI""); + } + } catch (Throwable t) { + throw new RuntimeCamelException(""Can't anylze the Exchange.HTTP_PATH header, due to: "" + + t.getMessage(), t); + } + + } + if (path.length() > 0) { + // make sure that there is exactly one ""/"" between HTTP_URI and + // HTTP_PATH + if (!uri.endsWith(""/"")) { + uri = uri + ""/""; + } + uri = uri.concat(path); } - uri = uri.concat(path); } return uri; diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java index beeda57af817e..8b24da62d2501 100644 --- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java +++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpBridgeRouteTest.java @@ -31,7 +31,7 @@ public void testHttpClient() throws Exception { String response = template.requestBodyAndHeader(""http://localhost:9090/test/hello"", new ByteArrayInputStream(""This is a test"".getBytes()), ""Content-Type"", ""application/xml"", String.class); - assertEquals(""Get a wrong response"", ""/test/hello"", response); + assertEquals(""Get a wrong response"", ""/"", response); response = template.requestBody(""http://localhost:9080/hello/world"", ""hello"", String.class); diff --git a/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java new file mode 100644 index 0000000000000..0931cc819cad3 --- /dev/null +++ b/tests/camel-itest/src/test/java/org/apache/camel/itest/issues/JettyHttpTest.java @@ -0,0 +1,86 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.itest.issues; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.builder.xml.Namespaces; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Ignore; +import org.junit.Test; + +/** + * @version $Revision$ + */ +public class JettyHttpTest extends CamelTestSupport { + + private String targetProducerUri = ""http://localhost:8542/someservice?bridgeEndpoint=true&throwExceptionOnFailure=false""; + private String targetConsumerUri = ""jetty:http://localhost:8542/someservice?matchOnUriPrefix=true""; + private String sourceUri = ""jetty:http://localhost:6323/myservice?matchOnUriPrefix=true""; + private String sourceProducerUri = ""http://localhost:6323/myservice""; + + @Test + public void testGetRootPath() throws Exception { + MockEndpoint mock = getMockEndpoint(""mock:result""); + mock.expectedBodiesReceived(""Hi! /someservice""); + + template.sendBody(""direct:root"", """"); + + assertMockEndpointsSatisfied(); + } + + @Test + public void testGetWithRelativePath() throws Exception { + MockEndpoint mock = getMockEndpoint(""mock:result""); + mock.expectedBodiesReceived(""Hi! /someservice/relative""); + + template.sendBody(""direct:relative"", """"); + assertMockEndpointsSatisfied(); + + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + + from(targetConsumerUri) + .process(new Processor() { + public void process(Exchange exchange) throws Exception { + String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); + exchange.getOut().setBody(""Hi! "" + path); + } + }); + + from(sourceUri) + .to(targetProducerUri); + + from(""direct:root"") + .to(sourceProducerUri) + .to(""mock:result""); + + from(""direct:relative"") + .to(sourceProducerUri + ""/relative"") + .to(""mock:result""); + + } + }; + } +}" 5fa9cbdf7684922da39b6b6fdaaa5c89a108b8a8,kotlin,rename--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java index ac115746064ef..6c88e27e4481e 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/descriptors/FunctionDescriptorUtil.java @@ -89,7 +89,7 @@ public static void initializeFromFunctionType(@NotNull FunctionDescriptorImpl fu ReceiverDescriptor.NO_RECEIVER, Collections.emptyList(), JetStandardClasses.getValueParameters(functionDescriptor, functionType), - JetStandardClasses.obtainReturnTypeFromFunctionType(functionType), + JetStandardClasses.getReturnTypeFromFunctionType(functionType), Modality.FINAL, Visibility.LOCAL); } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java index fb299e1c86eeb..55908afd1b6af 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/JetStandardClasses.java @@ -385,7 +385,7 @@ public static List getValueParameters(@NotNull Functio } @NotNull - public static JetType obtainReturnTypeFromFunctionType(@NotNull JetType type) { + public static JetType getReturnTypeFromFunctionType(@NotNull JetType type) { assert isFunctionType(type); List arguments = type.getArguments(); return arguments.get(arguments.size() - 1).getType(); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java index d6e5645c5fb09..41f0705f6aae4 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ClosureExpressionsTypingVisitor.java @@ -88,7 +88,7 @@ public JetType visitFunctionLiteralExpression(JetFunctionLiteralExpression expre } else { if (functionTypeExpected) { - returnType = JetStandardClasses.obtainReturnTypeFromFunctionType(expectedType); + returnType = JetStandardClasses.getReturnTypeFromFunctionType(expectedType); } returnType = context.getServices().getBlockReturnedType(functionInnerScope, bodyExpression, CoercionStrategy.COERCION_TO_UNIT, context.replaceExpectedType(returnType).replaceExpectedReturnType(returnType)); @@ -98,7 +98,7 @@ public JetType visitFunctionLiteralExpression(JetFunctionLiteralExpression expre boolean hasDeclaredValueParameters = functionLiteral.getValueParameterList() != null; if (!hasDeclaredValueParameters && functionTypeExpected) { - JetType expectedReturnType = JetStandardClasses.obtainReturnTypeFromFunctionType(expectedType); + JetType expectedReturnType = JetStandardClasses.getReturnTypeFromFunctionType(expectedType); if (JetStandardClasses.isUnit(expectedReturnType)) { functionDescriptor.setReturnType(JetStandardClasses.getUnitType()); return DataFlowUtils.checkType(JetStandardClasses.getFunctionType(Collections.emptyList(), receiver, parameterTypes, JetStandardClasses.getUnitType()), expression, context);" 2bf53a9a3c6ddd9051a50fdbf9600a2e585f7a35,ReactiveX-RxJava,"Spare a few redundant calls in SleepingAction- around determining the delay value (-3903)--- Remove redundant outer conditional.-- Skip calling into System.currentTimeMillis(), which could potentially result in different values.-",p,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/internal/schedulers/SleepingAction.java b/src/main/java/rx/internal/schedulers/SleepingAction.java index c41c01caf0..e3bdeb16ba 100644 --- a/src/main/java/rx/internal/schedulers/SleepingAction.java +++ b/src/main/java/rx/internal/schedulers/SleepingAction.java @@ -34,15 +34,14 @@ public void call() { if (innerScheduler.isUnsubscribed()) { return; } - if (execTime > innerScheduler.now()) { - long delay = execTime - innerScheduler.now(); - if (delay > 0) { - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(e); - } + + long delay = execTime - innerScheduler.now(); + if (delay > 0) { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); } }" b3f039ae5f0b54a325cdb23f6720e5002b054cee,spring-framework,Servlet/PortletRequestDataBinder perform- unwrapping for MultipartRequest as well (SPR-7795)--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java index 26c3a5b55fae..a63b894d17c5 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import org.springframework.validation.BindException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.multipart.MultipartRequest; +import org.springframework.web.portlet.util.PortletUtils; /** * Special {@link org.springframework.validation.DataBinder} to perform data binding @@ -105,8 +106,8 @@ public PortletRequestDataBinder(Object target, String objectName) { */ public void bind(PortletRequest request) { MutablePropertyValues mpvs = new PortletRequestParameterPropertyValues(request); - if (request instanceof MultipartRequest) { - MultipartRequest multipartRequest = (MultipartRequest) request; + MultipartRequest multipartRequest = PortletUtils.getNativeRequest(request, MultipartRequest.class); + if (multipartRequest != null) { bindMultipart(multipartRequest.getMultiFileMap(), mpvs); } doBind(mpvs); diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java index 3eedfb651b60..d407f40fa9ec 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -23,13 +23,12 @@ import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; import javax.portlet.PortletSession; -import javax.portlet.filter.PortletRequestWrapper; -import javax.portlet.filter.PortletResponseWrapper; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.portlet.util.PortletUtils; /** * {@link org.springframework.web.context.request.WebRequest} adapter @@ -79,40 +78,12 @@ public Object getNativeResponse() { @SuppressWarnings(""unchecked"") public T getNativeRequest(Class requiredType) { - if (requiredType != null) { - PortletRequest request = getRequest(); - while (request != null) { - if (requiredType.isInstance(request)) { - return (T) request; - } - else if (request instanceof PortletRequestWrapper) { - request = ((PortletRequestWrapper) request).getRequest(); - } - else { - request = null; - } - } - } - return null; + return PortletUtils.getNativeRequest(getRequest(), requiredType); } @SuppressWarnings(""unchecked"") public T getNativeResponse(Class requiredType) { - if (requiredType != null) { - PortletResponse response = getResponse(); - while (response != null) { - if (requiredType.isInstance(response)) { - return (T) response; - } - else if (response instanceof PortletResponseWrapper) { - response = ((PortletResponseWrapper) response).getResponse(); - } - else { - response = null; - } - } - } - return null; + return PortletUtils.getNativeResponse(getResponse(), requiredType); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java index cd9040b1b545..968229c7538f 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -32,6 +32,9 @@ import javax.portlet.PortletSession; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; +import javax.portlet.PortletResponse; +import javax.portlet.filter.PortletRequestWrapper; +import javax.portlet.filter.PortletResponseWrapper; import javax.servlet.http.Cookie; import org.springframework.util.Assert; @@ -276,6 +279,48 @@ public static Object getSessionMutex(PortletSession session) { } + /** + * Return an appropriate request object of the specified type, if available, + * unwrapping the given request as far as necessary. + * @param request the portlet request to introspect + * @param requiredType the desired type of request object + * @return the matching request object, or null if none + * of that type is available + */ + @SuppressWarnings(""unchecked"") + public static T getNativeRequest(PortletRequest request, Class requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(request)) { + return (T) request; + } + else if (request instanceof PortletRequestWrapper) { + return getNativeRequest(((PortletRequestWrapper) request).getRequest(), requiredType); + } + } + return null; + } + + /** + * Return an appropriate response object of the specified type, if available, + * unwrapping the given response as far as necessary. + * @param response the portlet response to introspect + * @param requiredType the desired type of response object + * @return the matching response object, or null if none + * of that type is available + */ + @SuppressWarnings(""unchecked"") + public static T getNativeResponse(PortletResponse response, Class requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(response)) { + return (T) response; + } + else if (response instanceof PortletResponseWrapper) { + return getNativeResponse(((PortletResponseWrapper) response).getResponse(), requiredType); + } + } + return null; + } + /** * Expose the given Map as request attributes, using the keys as attribute names * and the values as corresponding attribute values. Keys must be Strings. @@ -293,7 +338,7 @@ public static void exposeRequestAttributes(PortletRequest request, Mapnull if none is found */ diff --git a/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java b/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java index 2edc899cfa98..f488024d9b6e 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java +++ b/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import org.springframework.beans.MutablePropertyValues; import org.springframework.validation.BindException; import org.springframework.web.multipart.MultipartRequest; +import org.springframework.web.util.WebUtils; /** * Special {@link org.springframework.validation.DataBinder} to perform data binding @@ -103,8 +104,8 @@ public ServletRequestDataBinder(Object target, String objectName) { */ public void bind(ServletRequest request) { MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request); - if (request instanceof MultipartRequest) { - MultipartRequest multipartRequest = (MultipartRequest) request; + MultipartRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartRequest.class); + if (multipartRequest != null) { bindMultipart(multipartRequest.getMultiFileMap(), mpvs); } doBind(mpvs); diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java index 1caf21e48db4..9cb56566ed18 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java @@ -20,10 +20,6 @@ import java.util.Iterator; import java.util.Locale; import java.util.Map; -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestWrapper; -import javax.servlet.ServletResponse; -import javax.servlet.ServletResponseWrapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -31,6 +27,7 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import org.springframework.web.util.WebUtils; /** * {@link WebRequest} adapter for an {@link javax.servlet.http.HttpServletRequest}. @@ -92,40 +89,12 @@ public Object getNativeResponse() { @SuppressWarnings(""unchecked"") public T getNativeRequest(Class requiredType) { - if (requiredType != null) { - ServletRequest request = getRequest(); - while (request != null) { - if (requiredType.isInstance(request)) { - return (T) request; - } - else if (request instanceof ServletRequestWrapper) { - request = ((ServletRequestWrapper) request).getRequest(); - } - else { - request = null; - } - } - } - return null; + return WebUtils.getNativeRequest(getRequest(), requiredType); } @SuppressWarnings(""unchecked"") public T getNativeResponse(Class requiredType) { - if (requiredType != null) { - ServletResponse response = getResponse(); - while (response != null) { - if (requiredType.isInstance(response)) { - return (T) response; - } - else if (response instanceof ServletResponseWrapper) { - response = ((ServletResponseWrapper) response).getResponse(); - } - else { - response = null; - } - } - } - return null; + return WebUtils.getNativeResponse(getResponse(), requiredType); } diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java index c11df93a05f0..8e19d7092668 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -23,6 +23,9 @@ import java.util.TreeMap; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; +import javax.servlet.ServletRequestWrapper; +import javax.servlet.ServletResponse; +import javax.servlet.ServletResponseWrapper; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -366,6 +369,48 @@ public static Object getSessionMutex(HttpSession session) { } + /** + * Return an appropriate request object of the specified type, if available, + * unwrapping the given request as far as necessary. + * @param request the servlet request to introspect + * @param requiredType the desired type of request object + * @return the matching request object, or null if none + * of that type is available + */ + @SuppressWarnings(""unchecked"") + public static T getNativeRequest(ServletRequest request, Class requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(request)) { + return (T) request; + } + else if (request instanceof ServletRequestWrapper) { + return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType); + } + } + return null; + } + + /** + * Return an appropriate response object of the specified type, if available, + * unwrapping the given response as far as necessary. + * @param response the servlet response to introspect + * @param requiredType the desired type of response object + * @return the matching response object, or null if none + * of that type is available + */ + @SuppressWarnings(""unchecked"") + public static T getNativeResponse(ServletResponse response, Class requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(response)) { + return (T) response; + } + else if (response instanceof ServletResponseWrapper) { + return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType); + } + } + return null; + } + /** * Determine whether the given request is an include request, * that is, not a top-level HTTP request coming in from the outside." f1ac1054e3fc59f52237fb83da52c53dffe71de3,intellij-community,use common ExceptionUtil--,p,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java index 174bfa908c9bf..8119b1510d404 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/IteratorNextDoesNotThrowNoSuchElementExceptionInspection.java @@ -15,17 +15,17 @@ */ package com.siyeh.ig.bugs; +import com.intellij.codeInsight.ExceptionUtil; import com.intellij.psi.*; import com.siyeh.HardcodedMethodConstants; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; -import com.siyeh.ig.psiutils.ExceptionUtils; import com.siyeh.ig.psiutils.IteratorUtils; import com.siyeh.ig.psiutils.MethodUtils; import org.jetbrains.annotations.NotNull; -import java.util.Set; +import java.util.List; public class IteratorNextDoesNotThrowNoSuchElementExceptionInspection extends BaseInspection { @@ -65,9 +65,7 @@ public void visitMethod(@NotNull PsiMethod method) { HardcodedMethodConstants.NEXT)) { return; } - final Set exceptions = - ExceptionUtils.calculateExceptionsThrown(method); - for (final PsiType exception : exceptions) { + for (final PsiType exception : ExceptionUtil.getThrownExceptions(method)) { if (exception.equalsToText( ""java.util.NoSuchElementException"")) { return; @@ -103,8 +101,7 @@ public void visitMethodCallExpression( if (method == null) { return; } - final Set exceptions = - ExceptionUtils.calculateExceptionsThrown(method); + final List exceptions = ExceptionUtil.getThrownExceptions(method); for (final PsiType exception : exceptions) { if (exception.equalsToText( ""java.util.NoSuchElementException"")) { diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java index 98ec40b4dd996..86d83dc25e35a 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java @@ -16,6 +16,7 @@ package com.siyeh.ig.junit; import com.intellij.codeInsight.AnnotationUtil; +import com.intellij.codeInsight.ExceptionUtil; import com.intellij.psi.*; import com.intellij.psi.util.InheritanceUtil; import com.siyeh.InspectionGadgetsBundle; @@ -25,6 +26,7 @@ import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; +import java.util.List; import java.util.Set; public class ExpectedExceptionNeverThrownInspection extends BaseInspection { @@ -84,7 +86,7 @@ public void visitMethod(PsiMethod method) { InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_ERROR)) { return; } - final Set exceptionsThrown = ExceptionUtils.calculateExceptionsThrown(body); + final List exceptionsThrown = ExceptionUtil.getThrownExceptions(body); if (exceptionsThrown.contains(classType)) { return; }" 74f300d7a9e2f0e43dc5e517cc2acc8a4fcde701,camel,resource class refactoring; introducing a- reusable base class for sub-resources - also added a new RoutesResource to- simplify the root resource further--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@745556 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelChildResourceSupport.java b/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelChildResourceSupport.java new file mode 100644 index 0000000000000..b4935dd88459c --- /dev/null +++ b/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelChildResourceSupport.java @@ -0,0 +1,46 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.rest.resources; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import com.sun.jersey.api.view.ImplicitProduces; + +/** + * A useful base class for any sub resource of the root {@link org.apache.camel.rest.resources.CamelContextResource} + * + * @version $Revision: 1.1 $ + */ +@ImplicitProduces(Constants.HTML_MIME_TYPES) +public class CamelChildResourceSupport { + protected final CamelContext camelContext; + protected final ProducerTemplate template; + + public CamelChildResourceSupport(CamelContextResource contextResource) { + camelContext = contextResource.getCamelContext(); + template = contextResource.getTemplate(); + } + + public CamelContext getCamelContext() { + return camelContext; + } + + public ProducerTemplate getTemplate() { + return template; + } +} diff --git a/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelContextResource.java b/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelContextResource.java index b2261218f658c..0310c8ced27f3 100644 --- a/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelContextResource.java +++ b/components/camel-web/src/main/java/org/apache/camel/rest/resources/CamelContextResource.java @@ -73,7 +73,7 @@ public void close() throws Exception { } } - // XML / JSON representations + // representations //------------------------------------------------------------------------- @GET @@ -89,31 +89,16 @@ public EndpointsResource getEndpointsResource() { return new EndpointsResource(this); } - public List getEndpoints() { - return getEndpointsResource().getDTO().getEndpoints(); - } - - /** - * Returns the routes currently active within this context - * - * @return - */ - @GET @Path(""routes"") - @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - public RoutesType getRouteDefinitions() { - RoutesType answer = new RoutesType(); - if (camelContext != null) { - List list = camelContext.getRouteDefinitions(); - answer.setRoutes(list); - } - return answer; + public RoutesResource getRoutesResource() { + return new RoutesResource(this); } +/* - // Properties - //------------------------------------------------------------------------- - public List getRoutes() { - return getRouteDefinitions().getRoutes(); + public List getEndpoints() { + return getEndpointsResource().getDTO().getEndpoints(); } +*/ + } diff --git a/components/camel-web/src/main/java/org/apache/camel/rest/resources/EndpointsResource.java b/components/camel-web/src/main/java/org/apache/camel/rest/resources/EndpointsResource.java index f266485718a7a..2d0769d021e07 100644 --- a/components/camel-web/src/main/java/org/apache/camel/rest/resources/EndpointsResource.java +++ b/components/camel-web/src/main/java/org/apache/camel/rest/resources/EndpointsResource.java @@ -43,16 +43,13 @@ /** * @version $Revision: 1.1 $ */ -@ImplicitProduces(Constants.HTML_MIME_TYPES) -public class EndpointsResource { - private final CamelContext camelContext; - private final ProducerTemplate template; +//@ImplicitProduces(Constants.HTML_MIME_TYPES) +public class EndpointsResource extends CamelChildResourceSupport { private String error = """"; private String newUri = ""mock:someName""; public EndpointsResource(CamelContextResource contextResource) { - this.camelContext = contextResource.getCamelContext(); - this.template = contextResource.getTemplate(); + super(contextResource); } /** diff --git a/components/camel-web/src/main/java/org/apache/camel/rest/resources/RoutesResource.java b/components/camel-web/src/main/java/org/apache/camel/rest/resources/RoutesResource.java new file mode 100644 index 0000000000000..eae32f663ac15 --- /dev/null +++ b/components/camel-web/src/main/java/org/apache/camel/rest/resources/RoutesResource.java @@ -0,0 +1,60 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.rest.resources; + +import org.apache.camel.model.RoutesType; +import org.apache.camel.model.RouteType; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + * @version $Revision: 1.1 $ + */ +public class RoutesResource extends CamelChildResourceSupport { + + public RoutesResource(CamelContextResource contextResource) { + super(contextResource); + } + /** + * Returns the routes currently active within this context + * + * @return + */ + @GET + @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + public RoutesType getRouteDefinitions() { + RoutesType answer = new RoutesType(); + if (camelContext != null) { + List list = camelContext.getRouteDefinitions(); + answer.setRoutes(list); + } + return answer; + } + + + + // Properties + //------------------------------------------------------------------------- + public List getRoutes() { + return getRouteDefinitions().getRoutes(); + } +} \ No newline at end of file diff --git a/components/camel-web/src/main/webapp/org/apache/camel/rest/resources/CamelContextResource/routes.jsp b/components/camel-web/src/main/webapp/org/apache/camel/rest/resources/RoutesResource/index.jsp similarity index 99% rename from components/camel-web/src/main/webapp/org/apache/camel/rest/resources/CamelContextResource/routes.jsp rename to components/camel-web/src/main/webapp/org/apache/camel/rest/resources/RoutesResource/index.jsp index 8bef2902acb64..258b7ab477dae 100644 --- a/components/camel-web/src/main/webapp/org/apache/camel/rest/resources/CamelContextResource/routes.jsp +++ b/components/camel-web/src/main/webapp/org/apache/camel/rest/resources/RoutesResource/index.jsp @@ -7,7 +7,6 @@

Routes

-
  • ${i.shortName} ${i.description} diff --git a/components/camel-web/src/test/java/org/apache/camel/rest/spring/CamelRouteTest.java b/components/camel-web/src/test/java/org/apache/camel/rest/spring/CamelRouteTest.java index 78a4b4f969531..9054f0f0aa760 100644 --- a/components/camel-web/src/test/java/org/apache/camel/rest/spring/CamelRouteTest.java +++ b/components/camel-web/src/test/java/org/apache/camel/rest/spring/CamelRouteTest.java @@ -38,7 +38,7 @@ public class CamelRouteTest extends TestCase { public void testCanMarshalRoutes() throws Exception { CamelContextResource resource = new CamelContextResource(camelContext); - RoutesType routes = resource.getRouteDefinitions(); + RoutesType routes = resource.getRoutesResource().getRouteDefinitions(); List list = routes.getRoutes(); System.out.println(""Found routes: "" + list);" 08894a81b8ba840c6966aec9d7304769d8412b9d,orientdb,Fix failed WAL test.--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java index e04e3aa39b5..27178b452c8 100755 --- a/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java +++ b/core/src/test/java/com/orientechnologies/orient/core/storage/impl/local/paginated/wal/WriteAheadLogTest.java @@ -6,18 +6,10 @@ import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Random; +import java.util.*; import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import org.testng.annotations.*; import com.orientechnologies.common.serialization.types.OIntegerSerializer; import com.orientechnologies.common.serialization.types.OLongSerializer; @@ -1385,6 +1377,7 @@ public void testThirdPageCRCWasIncorrect() throws Exception { RandomAccessFile rndFile = new RandomAccessFile(new File(testDir, ""WriteAheadLogTest.0.wal""), ""rw""); rndFile.seek(2 * OWALPage.PAGE_SIZE); int bt = rndFile.read(); + rndFile.seek(2 * OWALPage.PAGE_SIZE); rndFile.write(bt + 1); rndFile.close();" 663d9f43b0f5b49088102781ae8ce7123932e97b,intellij-community,"Cheaper ProgressManager.checkCanceled().- Mostly, it's call to abstract method eliminated.--",p,https://github.com/JetBrains/intellij-community,"diff --git a/python/src/com/jetbrains/python/inspections/PyUnresolvedReferencesInspection.java b/python/src/com/jetbrains/python/inspections/PyUnresolvedReferencesInspection.java index 4772e6ae4abe0..d4ba0adc9abd6 100644 --- a/python/src/com/jetbrains/python/inspections/PyUnresolvedReferencesInspection.java +++ b/python/src/com/jetbrains/python/inspections/PyUnresolvedReferencesInspection.java @@ -149,7 +149,7 @@ static List proposeImportFixes(final PyElement node, String ref_t } } // maybe some unimported file has it, too - ProgressManager.getInstance().checkCanceled(); // before expensive index searches + ProgressManager.checkCanceled(); // before expensive index searches // NOTE: current indices have limitations, only finding direct definitions of classes and functions. Project project = node.getProject(); GlobalSearchScope scope = null; // GlobalSearchScope.projectScope(project); diff --git a/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java b/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java index e391f31c07b11..73cd77033c9f1 100644 --- a/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java +++ b/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java @@ -121,7 +121,7 @@ public static PsiElement treeCrawlUp(PsiScopeProcessor processor, boolean fromun PsiElement seeker = elt; PsiElement cap = getConcealingParent(elt); do { - ProgressManager.getInstance().checkCanceled(); + ProgressManager.checkCanceled(); if (!seeker.isValid()) return null; if (fromunder) { fromunder = false; // only honour fromunder once per call diff --git a/python/src/com/jetbrains/python/testing/PythonUnitTestTestIdUrlProvider.java b/python/src/com/jetbrains/python/testing/PythonUnitTestTestIdUrlProvider.java index 05db4a5916bcd..6d6b1ec3f401c 100644 --- a/python/src/com/jetbrains/python/testing/PythonUnitTestTestIdUrlProvider.java +++ b/python/src/com/jetbrains/python/testing/PythonUnitTestTestIdUrlProvider.java @@ -54,7 +54,7 @@ public List getLocation(@NotNull final String protocolId, @NotNull fin final List locations = new ArrayList(); for (PyClass cls : getClassesByName(project, className)) { - ProgressManager.getInstance().checkCanceled(); + ProgressManager.checkCanceled(); final PyFunction method = locateMethodInHierarchy(cls, methodName); if (method == null) {" 3beef9a92e78ca6da4f41dbb0c3c858ac85b10cb,spring-framework,"SPR-8883 - RestTemplate.headForHeaders throws- ""IllegalArgumentException: No InputStream specified"" on server resource which- status code are 4xx--",c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java b/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java index 2aea01f187b2..0615f7a823a9 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java +++ b/org.springframework.web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java @@ -17,6 +17,7 @@ package org.springframework.web.client; import java.io.IOException; +import java.io.InputStream; import java.nio.charset.Charset; import org.springframework.http.HttpStatus; @@ -82,11 +83,15 @@ public void handleError(ClientHttpResponse response) throws IOException { private byte[] getResponseBody(ClientHttpResponse response) { try { - return FileCopyUtils.copyToByteArray(response.getBody()); + InputStream responseBody = response.getBody(); + if (responseBody != null) { + return FileCopyUtils.copyToByteArray(responseBody); + } } catch (IOException ex) { - return new byte[0]; + // ignore } + return new byte[0]; } } diff --git a/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java b/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java index 67a11a7c8de3..0c9866c19bee 100644 --- a/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java +++ b/org.springframework.web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java @@ -19,16 +19,17 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import org.junit.Before; -import org.junit.Test; - import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; +import org.junit.Before; +import org.junit.Test; + import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; /** @author Arjen Poutsma */ public class DefaultResponseErrorHandlerTests { @@ -96,4 +97,21 @@ public void handleErrorIOException() throws Exception { verify(response); } + + @Test(expected = HttpClientErrorException.class) + public void handleErrorNullResponse() throws Exception { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.TEXT_PLAIN); + + expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND); + expect(response.getStatusText()).andReturn(""Not Found""); + expect(response.getHeaders()).andReturn(headers); + expect(response.getBody()).andReturn(null); + + replay(response); + + handler.handleError(response); + + verify(response); + } }" 610c4bbad87af05da8ebd7581f64c8fb3d2388a7,restlet-framework-java,Fixed potential infinite loops while reading- headers (issues -599 and -656). Reported by weiweiwang.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet/src/org/restlet/engine/header/HeaderReader.java b/modules/org.restlet/src/org/restlet/engine/header/HeaderReader.java index ee42dc4cee..e0ad1aafd3 100644 --- a/modules/org.restlet/src/org/restlet/engine/header/HeaderReader.java +++ b/modules/org.restlet/src/org/restlet/engine/header/HeaderReader.java @@ -303,6 +303,8 @@ public void addValues(Collection values) { skipSpaces(); do { + int i = index; + // Read the first value V nextValue = readValue(); if (canAdd(nextValue, values)) { @@ -312,6 +314,11 @@ public void addValues(Collection values) { // Attempt to skip the value separator skipValueSeparator(); + if (i == index) { + // Infinite loop + throw new IOException( + ""The reading of one header initiates an infinite loop""); + } } while (peek() != -1); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.INFO," 85ec6bc6d7cd0904757b596627fd3666de7738dd,camel,added fix for- https://issues.apache.org/activemq/browse/CAMEL-347 to enable JUEL to invoke- methods in expressions--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@631503 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/camel,"diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java new file mode 100644 index 0000000000000..2412b27fa96a3 --- /dev/null +++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java @@ -0,0 +1,84 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.language.juel; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import javax.el.BeanELResolver; +import javax.el.ELContext; +import javax.el.PropertyNotFoundException; + +/** + * An extension of the JUEL {@link BeanELResolver} which also supports the resolving of methods + * + * @version $Revision: 1.1 $ + */ +public class BeanAndMethodELResolver extends BeanELResolver { + public BeanAndMethodELResolver() { + super(false); + } + + @Override + public Object getValue(ELContext elContext, Object base, Object property) { + try { + return super.getValue(elContext, base, property); + } + catch (PropertyNotFoundException e) { + // lets see if its a method call... + Method method = findMethod(elContext, base, property); + if (method != null) { + elContext.setPropertyResolved(true); + return method; + } + else { + throw e; + } + } + } + + protected Method findMethod(ELContext elContext, Object base, Object property) { + if (base != null && property instanceof String) { + Method[] methods = base.getClass().getMethods(); + List matching = new ArrayList(); + for (Method method : methods) { + if (method.getName().equals(property) && Modifier.isPublic(method.getModifiers())) { + matching.add(method); + } + } + int size = matching.size(); + if (size > 0) { + if (size > 1) { + // TODO there's currently no way for JUEL to tell us how many parameters there are + // so lets just pick the first one that has a single param by default + for (Method method : matching) { + Class[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1) { + return method; + } + } + } + // lets default to the first one + return matching.get(0); + } + } + return null; + } +} diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java index dbeb68dc43ba8..a2d5e80e14c4f 100644 --- a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java +++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java @@ -16,12 +16,11 @@ */ package org.apache.camel.language.juel; -import javax.el.ELContext; -import javax.el.ExpressionFactory; -import javax.el.ValueExpression; +import java.util.Properties; -import de.odysseus.el.util.SimpleContext; +import javax.el.*; +import de.odysseus.el.util.SimpleContext; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.impl.ExpressionSupport; @@ -29,14 +28,14 @@ /** * The EL Language from JSP and JSF * using the JUEL library - * + * * @version $Revision$ */ public class JuelExpression extends ExpressionSupport { - private final String expression; private final Class type; private ExpressionFactory expressionFactory; + private Properties expressionFactoryProperties; public JuelExpression(String expression, Class type) { this.expression = expression; @@ -57,7 +56,8 @@ public Object evaluate(Exchange exchange) { public ExpressionFactory getExpressionFactory() { if (expressionFactory == null) { - expressionFactory = ExpressionFactory.newInstance(); + Properties properties = getExpressionFactoryProperties(); + expressionFactory = ExpressionFactory.newInstance(properties); } return expressionFactory; } @@ -66,6 +66,18 @@ public void setExpressionFactory(ExpressionFactory expressionFactory) { this.expressionFactory = expressionFactory; } + public Properties getExpressionFactoryProperties() { + if (expressionFactoryProperties == null) { + expressionFactoryProperties = new Properties(); + populateDefaultExpressionProperties(expressionFactoryProperties); + } + return expressionFactoryProperties; + } + + public void setExpressionFactoryProperties(Properties expressionFactoryProperties) { + this.expressionFactoryProperties = expressionFactoryProperties; + } + protected ELContext populateContext(ELContext context, Exchange exchange) { setVariable(context, ""exchange"", exchange, Exchange.class); setVariable(context, ""in"", exchange.getIn(), Message.class); @@ -74,6 +86,14 @@ protected ELContext populateContext(ELContext context, Exchange exchange) { return context; } + /** + * A Strategy Method to populate the default properties used to create the expression factory + */ + protected void populateDefaultExpressionProperties(Properties properties) { + // lets enable method invocations + properties.setProperty(""javax.el.methodInvocations"", ""true""); + } + protected void setVariable(ELContext context, String name, Object value, Class type) { ValueExpression valueExpression = getExpressionFactory().createValueExpression(value, type); SimpleContext simpleContext = (SimpleContext) context; @@ -84,7 +104,17 @@ protected void setVariable(ELContext context, String name, Object value, Classworld!""); } + public void testElPredicates() throws Exception { + assertPredicate(""${in.headers.foo.startsWith('a')}""); + } + protected String getLanguageName() { return ""el""; }" fd86b5d80c25c8a6e4ac6d2aa7c7db0c758c2cef,drools,[DROOLS-336] avoid to share a LeftInputAdapterNode- if it has 2 sinks with different property reactive masks--,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java index 04dc28a90c9..9726a25049c 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java @@ -4151,4 +4151,229 @@ public void testInsertModifyInteractionsWithNoloop() { assertEquals( ""Two"", m2.getMessage2() ); // r1 does not fire for m2 assertEquals( ""msg3"", m2.getMessage3() ); } + + @Test + public void testWumpus1() { + String drl = ""import org.drools.compiler.integrationtests.Misc2Test.Hero;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.StepForwardCommand;\n"" + + ""global java.util.List list; \n "" + + ""\n"" + + ""\n"" + + ""rule StepLeft when\n"" + + "" $h : Hero( goingRight == false )\n"" + + "" $sc : StepForwardCommand()\n"" + + ""then\n"" + + "" modify ( $h ) { setPos( $h.getPos()-1 ) };\n"" + + "" list.add( 'StepLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""rule StepRight when\n"" + + "" $h : Hero( goingRight == true )\n"" + + "" $sc : StepForwardCommand()\n"" + + ""then\n"" + + "" modify ( $h ) { setPos( $h.getPos()+1 ) };\n"" + + "" list.add( 'StepRight' );\n"" + + ""end\n""; + + KnowledgeBuilderConfiguration kbConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); + KnowledgeBase kbase = loadKnowledgeBaseFromString( kbConf, drl ); + + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + List list = new ArrayList(); + ksession.setGlobal( ""list"", list ); + + Hero hero = new Hero(1); + ksession.insert(hero); + ksession.fireAllRules(); + + ksession.insert(new StepForwardCommand()); + assertEquals( 1, ksession.fireAllRules() ); + assertEquals(2, hero.getPos()); + } + + @Test + public void testWumpus2() { + String drl = ""import org.drools.compiler.integrationtests.Misc2Test.Hero;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.StepForwardCommand;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.ChangeDirectionCommand;\n"" + + ""global java.util.List list; \n "" + + ""\n"" + + ""\n"" + + ""rule StepLeft when\n"" + + "" $sc : StepForwardCommand()\n"" + + "" $h : Hero( goingRight == false )\n"" + + ""then\n"" + + "" modify ( $h ) { setPos( $h.getPos()-1 ) };\n"" + + "" list.add( 'StepLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""rule StepRight when\n"" + + "" $sc : StepForwardCommand()\n"" + + "" $h : Hero( goingRight == true )\n"" + + ""then\n"" + + "" modify ( $h ) { setPos( $h.getPos()+1 ) };\n"" + + "" list.add( 'StepRight' );\n"" + + ""end\n""; + + KnowledgeBuilderConfiguration kbConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); + KnowledgeBase kbase = loadKnowledgeBaseFromString( kbConf, drl ); + + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + List list = new ArrayList(); + ksession.setGlobal( ""list"", list ); + + Hero hero = new Hero(1); + ksession.insert(hero); + ksession.fireAllRules(); + + ksession.insert(new StepForwardCommand()); + assertEquals( 1, ksession.fireAllRules() ); + assertEquals(2, hero.getPos()); + } + + @Test + public void testWumpus3() { + String drl = ""import org.drools.compiler.integrationtests.Misc2Test.Hero;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.StepForwardCommand;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.ChangeDirectionCommand;\n"" + + ""global java.util.List list; \n "" + + ""\n"" + + ""rule RotateLeft when\n"" + + "" $h : Hero( goingRight == true )\n"" + + "" $dc : ChangeDirectionCommand()\n"" + + ""then\n"" + + "" retract ( $dc ); \n"" + + "" modify ( $h ) { setGoingRight( false ) };\n"" + + "" list.add( 'RotateLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""\n"" + + ""rule StepLeft when\n"" + + "" $h : Hero( goingRight == false )\n"" + + "" $sc : StepForwardCommand()\n"" + + ""then\n"" + + "" retract ( $sc ); \n"" + + "" modify ( $h ) { setPos( $h.getPos()-1 ) };\n"" + + "" list.add( 'StepLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""rule StepRight when\n"" + + "" $h : Hero( goingRight == true )\n"" + + "" $sc : StepForwardCommand()\n"" + + ""then\n"" + + "" retract ( $sc );\n"" + + "" modify ( $h ) { setPos( $h.getPos()+1 ) };\n"" + + "" list.add( 'StepRight' );\n"" + + ""end\n""; + + KnowledgeBuilderConfiguration kbConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); + KnowledgeBase kbase = loadKnowledgeBaseFromString( kbConf, drl ); + + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + List list = new ArrayList(); + ksession.setGlobal( ""list"", list ); + + Hero hero = new Hero(1); + ksession.insert(hero); + ksession.fireAllRules(); + + ksession.insert(new StepForwardCommand()); + ksession.fireAllRules(); + assertEquals(2, hero.getPos()); + + ksession.insert(new ChangeDirectionCommand()); + ksession.fireAllRules(); + ksession.insert(new StepForwardCommand()); + ksession.fireAllRules(); + assertEquals(1, hero.getPos()); + } + + @Test + public void testWumpus4() { + String drl = ""import org.drools.compiler.integrationtests.Misc2Test.Hero;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.StepForwardCommand;\n"" + + ""import org.drools.compiler.integrationtests.Misc2Test.ChangeDirectionCommand;\n"" + + ""global java.util.List list; \n "" + + ""\n"" + + ""rule RotateLeft when\n"" + + "" $dc : ChangeDirectionCommand()\n"" + + "" $h : Hero( goingRight == true )\n"" + + ""then\n"" + + "" retract ( $dc ); \n"" + + "" modify ( $h ) { setGoingRight( false ) };\n"" + + "" list.add( 'RotateLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""\n"" + + ""rule StepLeft when\n"" + + "" $sc : StepForwardCommand()\n"" + + "" $h : Hero( goingRight == false )\n"" + + ""then\n"" + + "" retract ( $sc ); \n"" + + "" modify ( $h ) { setPos( $h.getPos()-1 ) };\n"" + + "" list.add( 'StepLeft' );\n"" + + ""end\n"" + + ""\n"" + + ""rule StepRight when\n"" + + "" $sc : StepForwardCommand()\n"" + + "" $h : Hero( goingRight == true )\n"" + + ""then\n"" + + "" retract ( $sc );\n"" + + "" modify ( $h ) { setPos( $h.getPos()+1 ) };\n"" + + "" list.add( 'StepRight' );\n"" + + ""end\n""; + + KnowledgeBuilderConfiguration kbConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(); + KnowledgeBase kbase = loadKnowledgeBaseFromString( kbConf, drl ); + + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + List list = new ArrayList(); + ksession.setGlobal( ""list"", list ); + + Hero hero = new Hero(1); + ksession.insert(hero); + ksession.fireAllRules(); + + ksession.insert(new StepForwardCommand()); + ksession.fireAllRules(); + assertEquals(2, hero.getPos()); + + + + ksession.insert(new ChangeDirectionCommand()); + ksession.fireAllRules(); + ksession.insert(new StepForwardCommand()); + ksession.fireAllRules(); + assertEquals(1, hero.getPos()); + } + + @PropertyReactive + public static class Hero { + private int pos = 1; + private boolean goingRight = true; + + public Hero(int pos) { + this.pos = pos; + } + + public int getPos() { + return pos; + } + + public void setPos(int pos) { + this.pos = pos; + } + + public boolean isGoingRight() { + return goingRight; + } + + public void setGoingRight(boolean goingRight) { + this.goingRight = goingRight; + } + + } + + public static class ChangeDirectionCommand { } + public static class StepForwardCommand { } } diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/PropertySpecificTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/PropertySpecificTest.java index 278f3fbc500..7fc27134972 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/PropertySpecificTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/PropertySpecificTest.java @@ -2071,9 +2071,10 @@ public void test2DifferentAlphaWatchBeforeSameBeta() { BetaNode betaNodeC1 = ( BetaNode ) otnC.getSinkPropagator().getSinks()[0]; BetaNode betaNodeC2 = ( BetaNode ) otnC.getSinkPropagator().getSinks()[1]; - LeftInputAdapterNode lia = (LeftInputAdapterNode)alphaNode.getSinkPropagator().getSinks()[0]; - assertSame(betaNodeC1, lia.getSinkPropagator().getSinks()[0]); - assertSame(betaNodeC2, lia.getSinkPropagator().getSinks()[1]); + LeftInputAdapterNode lia1 = (LeftInputAdapterNode)alphaNode.getSinkPropagator().getSinks()[0]; + assertSame(betaNodeC1, lia1.getSinkPropagator().getSinks()[0]); + LeftInputAdapterNode lia2 = (LeftInputAdapterNode)alphaNode.getSinkPropagator().getSinks()[1]; + assertSame(betaNodeC2, lia2.getSinkPropagator().getSinks()[0]); assertEquals( 0L, betaNodeC1.getRightDeclaredMask() ); assertEquals( 0L, betaNodeC1.getRightInferredMask() ); @@ -2089,8 +2090,8 @@ public void test2DifferentAlphaWatchBeforeSameBeta() { assertEquals( calculatePositiveMask(list(""a""), sp), alphaNode.getDeclaredMask( ) ); assertEquals( calculatePositiveMask(list(""a"", ""c""), sp), alphaNode.getInferredMask()); - assertEquals( 1, lia.getSinkPropagator().getSinks().length ); - BetaNode betaNodeC = ( BetaNode ) lia.getSinkPropagator().getSinks()[0]; + assertEquals( 1, lia2.getSinkPropagator().getSinks().length ); + BetaNode betaNodeC = ( BetaNode ) lia2.getSinkPropagator().getSinks()[0]; assertEquals( 0L, betaNodeC2.getRightDeclaredMask() ); assertEquals( 0L, betaNodeC2.getRightInferredMask() ); diff --git a/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java b/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java index dd03b41d718..a017d1fc786 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/AccumulateNode.java @@ -388,42 +388,4 @@ public void doRemove(RuleRemovalContext context, ReteooBuilder builder, Internal getRightInput().removeObjectSink( this ); } } - - @Override - public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory wm) { - RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); - - // if the peek is for a different OTN we assume that it is after the current one and then this is an assert - while ( rightTuple != null && - (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().before( getRightInputOtnId() ) ) { - modifyPreviousTuples.removeRightTuple(); - - // we skipped this node, due to alpha hashing, so retract now - rightTuple.setPropagationContext( context ); - BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getRightTupleSink(), wm ); - (( BetaNode ) rightTuple.getRightTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); - rightTuple = modifyPreviousTuples.peekRightTuple(); - } - - if ( rightTuple != null && (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().equals(getRightInputOtnId()) ) { - modifyPreviousTuples.removeRightTuple(); - rightTuple.reAdd(); - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple previously existed, so continue as modify - rightTuple.setPropagationContext( context ); // only update, if the mask intersects - - BetaMemory bm = getBetaMemory( this, wm ); - rightTuple.setPropagationContext( context ); - doUpdateRightTuple(rightTuple, wm, bm); - } - } else { - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple does not exist for this node, so create and continue as assert - assertObject( factHandle, - context, - wm ); - } - } - } - } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java b/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java index 37d12a3c3b7..23e9d7595bb 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/BetaNode.java @@ -20,6 +20,7 @@ import static org.drools.core.reteoo.PropertySpecificUtil.calculatePositiveMask; import static org.drools.core.reteoo.PropertySpecificUtil.getSettableProperties; import static org.drools.core.reteoo.PropertySpecificUtil.isPropertyReactive; +import static org.drools.core.util.BitMaskUtil.intersect; import static org.drools.core.util.ClassUtils.areNullSafeEquals; import java.io.IOException; @@ -316,10 +317,43 @@ public void assertObject( final InternalFactHandle factHandle, MarshallerReaderContext mrc = (MarshallerReaderContext) pctx.getReaderContext(); mrc.filter.fireRNEAs( wm ); } + } + public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory wm) { + RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); - } + // if the peek is for a different OTN we assume that it is after the current one and then this is an assert + while ( rightTuple != null && + (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().before( getRightInputOtnId() ) ) { + modifyPreviousTuples.removeRightTuple(); + + // we skipped this node, due to alpha hashing, so retract now + rightTuple.setPropagationContext( context ); + BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getRightTupleSink(), wm ); + (( BetaNode ) rightTuple.getRightTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); + rightTuple = modifyPreviousTuples.peekRightTuple(); + } + + if ( rightTuple != null && (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().equals(getRightInputOtnId()) ) { + modifyPreviousTuples.removeRightTuple(); + rightTuple.reAdd(); + if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { + // RightTuple previously existed, so continue as modify + rightTuple.setPropagationContext( context ); // only update, if the mask intersects + BetaMemory bm = getBetaMemory( this, wm ); + rightTuple.setPropagationContext( context ); + doUpdateRightTuple(rightTuple, wm, bm); + } + } else { + if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { + // RightTuple does not exist for this node, so create and continue as assert + assertObject( factHandle, + context, + wm ); + } + } + } public void doDeleteRightTuple(final RightTuple rightTuple, final InternalWorkingMemory wm, diff --git a/drools-core/src/main/java/org/drools/core/reteoo/ExistsNode.java b/drools-core/src/main/java/org/drools/core/reteoo/ExistsNode.java index 9f5d177f579..7cd2550338e 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/ExistsNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/ExistsNode.java @@ -175,43 +175,6 @@ public void doRemove(RuleRemovalContext context, ReteooBuilder builder, Internal } } - @Override - public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory wm) { - RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); - - // if the peek is for a different OTN we assume that it is after the current one and then this is an assert - while ( rightTuple != null && - (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().before( getRightInputOtnId() ) ) { - modifyPreviousTuples.removeRightTuple(); - - // we skipped this node, due to alpha hashing, so retract now - rightTuple.setPropagationContext( context ); - BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getRightTupleSink(), wm ); - (( BetaNode ) rightTuple.getRightTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); - rightTuple = modifyPreviousTuples.peekRightTuple(); - } - - if ( rightTuple != null && (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().equals(getRightInputOtnId()) ) { - modifyPreviousTuples.removeRightTuple(); - rightTuple.reAdd(); - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple previously existed, so continue as modify - rightTuple.setPropagationContext( context ); // only update, if the mask intersects - - BetaMemory bm = getBetaMemory( this, wm ); - rightTuple.setPropagationContext( context ); - doUpdateRightTuple(rightTuple, wm, bm); - } - } else { - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple does not exist for this node, so create and continue as assert - assertObject( factHandle, - context, - wm ); - } - } - } - public boolean isLeftUpdateOptimizationAllowed() { return getRawConstraints().isLeftUpdateOptimizationAllowed(); } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/JoinNode.java b/drools-core/src/main/java/org/drools/core/reteoo/JoinNode.java index ce02590c4ec..82de0c13200 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/JoinNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/JoinNode.java @@ -155,42 +155,4 @@ public void doRemove(RuleRemovalContext context, ReteooBuilder builder, Internal getRightInput().removeObjectSink( this ); } } - - @Override - public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory wm) { - RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); - - // if the peek is for a different OTN we assume that it is after the current one and then this is an assert - while ( rightTuple != null && - (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().before( getRightInputOtnId() ) ) { - modifyPreviousTuples.removeRightTuple(); - - // we skipped this node, due to alpha hashing, so retract now - rightTuple.setPropagationContext( context ); - BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getRightTupleSink(), wm ); - (( BetaNode ) rightTuple.getRightTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); - rightTuple = modifyPreviousTuples.peekRightTuple(); - } - - if ( rightTuple != null && (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().equals(getRightInputOtnId()) ) { - modifyPreviousTuples.removeRightTuple(); - rightTuple.reAdd(); - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple previously existed, so continue as modify - rightTuple.setPropagationContext( context ); // only update, if the mask intersects - - BetaMemory bm = getBetaMemory( this, wm ); - rightTuple.setPropagationContext( context ); - doUpdateRightTuple(rightTuple, wm, bm); - } - } else { - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple does not exist for this node, so create and continue as assert - assertObject( factHandle, - context, - wm ); - } - } - } - } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java b/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java index fee09c46c47..d91bdcda9a0 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/LeftInputAdapterNode.java @@ -16,12 +16,16 @@ package org.drools.core.reteoo; +import static org.drools.core.reteoo.PropertySpecificUtil.calculatePositiveMask; +import static org.drools.core.reteoo.PropertySpecificUtil.getSettableProperties; +import static org.drools.core.reteoo.PropertySpecificUtil.isPropertyReactive; import static org.drools.core.util.BitMaskUtil.intersect; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Deque; +import java.util.List; import java.util.Map; import org.drools.core.RuleBaseConfiguration; @@ -39,7 +43,11 @@ import org.drools.core.marshalling.impl.MarshallerReaderContext; import org.drools.core.phreak.LeftTupleEntry; import org.drools.core.phreak.SegmentUtilities; +import org.drools.core.reteoo.ObjectTypeNode.Id; import org.drools.core.reteoo.builder.BuildContext; +import org.drools.core.rule.Pattern; +import org.drools.core.spi.ClassWireable; +import org.drools.core.spi.ObjectType; import org.drools.core.spi.PropagationContext; import org.drools.core.spi.RuleComponent; import org.drools.core.util.AbstractBaseLinkedListNode; @@ -54,9 +62,9 @@ * of a BetaNode. */ public class LeftInputAdapterNode extends LeftTupleSource - implements - ObjectSinkNode, - MemoryFactory { + implements + ObjectSinkNode, + MemoryFactory { protected static transient Logger log = LoggerFactory.getLogger(LeftInputAdapterNode.class); @@ -72,6 +80,8 @@ public class LeftInputAdapterNode extends LeftTupleSource private int segmentMemoryIndex; + private long sinkMask; + public LeftInputAdapterNode() { } @@ -101,14 +111,34 @@ public LeftInputAdapterNode(final int id, rootQueryNode = ClassObjectType.DroolsQuery_ObjectType.isAssignableFrom(otn.getObjectType()); streamMode = context.isStreamMode() && context.getRootObjectTypeNode().getObjectType().isEvent(); + sinkMask = calculateSinkMask(context); + } + + private long calculateSinkMask(BuildContext context) { + Pattern pattern = context.getLastBuiltPatterns() != null ? context.getLastBuiltPatterns()[0] : null; + if (pattern == null) { + return -1L; + } + ObjectType objectType = pattern.getObjectType(); + if ( !(objectType instanceof ClassObjectType) ) { + // Only ClassObjectType can use property specific + return -1L; + } + + Class objectClass = ((ClassWireable) objectType).getClassType(); + return isPropertyReactive( context, objectClass ) ? + calculatePositiveMask( pattern.getListenedProperties(), + getSettableProperties( context.getRuleBase(), objectClass ) ) : + -1L; } public void readExternal(ObjectInput in) throws IOException, - ClassNotFoundException { + ClassNotFoundException { super.readExternal(in); objectSource = (ObjectSource) in.readObject(); leftTupleMemoryEnabled = in.readBoolean(); rootQueryNode = in.readBoolean(); + sinkMask = in.readLong(); } public void writeExternal(ObjectOutput out) throws IOException { @@ -116,6 +146,7 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(objectSource); out.writeBoolean(leftTupleMemoryEnabled); out.writeBoolean(rootQueryNode); + out.writeLong(sinkMask); } public ObjectSource getObjectSource() { @@ -129,11 +160,11 @@ public int getSegmentMemoryIndex() { public void setSegmentMemoryIndex(int segmentMemoryIndex) { this.segmentMemoryIndex = segmentMemoryIndex; } - + public short getType() { return NodeTypeEnums.LeftInputAdapterNode; } - + public boolean isRootQueryNode() { return this.rootQueryNode; } @@ -142,11 +173,11 @@ public boolean isRootQueryNode() { public boolean isLeftTupleMemoryEnabled() { return leftTupleMemoryEnabled; } - + public ObjectSource getParentObjectSource() { return this.objectSource; - } - + } + public void attach( BuildContext context ) { this.objectSource.addObjectSink( this ); } @@ -171,12 +202,12 @@ public void assertObject(final InternalFactHandle factHandle, } public static void doInsertObject(final InternalFactHandle factHandle, - final PropagationContext context, - final LeftInputAdapterNode liaNode, - final InternalWorkingMemory wm, - final LiaNodeMemory lm, - boolean linkOrNotify, - boolean useLeftMemory) { + final PropagationContext context, + final LeftInputAdapterNode liaNode, + final InternalWorkingMemory wm, + final LiaNodeMemory lm, + boolean linkOrNotify, + boolean useLeftMemory) { SegmentMemory sm = lm.getSegmentMemory(); if ( sm.getTipNode() == liaNode) { // liaNode in it's own segment and child segments not yet created @@ -197,18 +228,16 @@ public static void doInsertObject(final InternalFactHandle factHandle, LeftTupleSink sink = liaNode.getSinkPropagator().getFirstLeftTupleSink(); LeftTuple leftTuple = sink.createLeftTuple( factHandle, sink, useLeftMemory ); leftTuple.setPropagationContext( context ); - long mask = sink.getLeftInferredMask(); - doInsertSegmentMemory(context, wm, notifySegment, lm, sm, leftTuple, liaNode, mask); + doInsertSegmentMemory(context, wm, notifySegment, lm, sm, leftTuple, liaNode); if ( sm.getRootNode() != liaNode ) { - // sm points to lia child sm, so iterate for all remaining children - + // sm points to lia child sm, so iterate for all remaining children + for ( sm = sm.getNext(); sm != null; sm = sm.getNext() ) { - sink = sm.getSinkFactory(); + sink = sm.getSinkFactory(); leftTuple = sink.createPeer( leftTuple ); // pctx is set during peer cloning - mask = ((LeftTupleSink)sm.getRootNode()).getLeftInferredMask(); - doInsertSegmentMemory(context, wm, notifySegment, lm, sm, leftTuple, liaNode, mask); - } + doInsertSegmentMemory(context, wm, notifySegment, lm, sm, leftTuple, liaNode); + } } if ( counter == 0) { @@ -231,27 +260,24 @@ public static void doInsertObject(final InternalFactHandle factHandle, } private static void doInsertSegmentMemory(PropagationContext pctx, InternalWorkingMemory wm, boolean linkOrNotify, final LiaNodeMemory lm, - SegmentMemory sm, LeftTuple leftTuple, LeftInputAdapterNode liaNode, long mask) { - if ( pctx.getType() == PropagationContext.INSERTION || - intersect( pctx.getModificationMask(), mask) ) { - boolean stagedInsertWasEmpty = false; - - // mask check is necessary if insert is a result of a modify - if ( liaNode.isStreamMode() && sm.getTupleQueue() != null ) { - stagedInsertWasEmpty = sm.getTupleQueue().isEmpty(); - int propagationType = pctx.getType() == PropagationContext.MODIFICATION ? PropagationContext.INSERTION : pctx.getType(); - sm.getTupleQueue().add(new LeftTupleEntry(leftTuple, pctx, sm.getNodeMemories().getFirst(), propagationType)); - - if ( log.isTraceEnabled() ) { - log.trace( ""LeftInputAdapterNode insert size={} queue={} pctx={} lt={}"", System.identityHashCode( sm.getTupleQueue() ), sm.getTupleQueue().size(), PhreakPropagationContext.intEnumToString(pctx), leftTuple); - } - } else { - stagedInsertWasEmpty = sm.getStagedLeftTuples().addInsert( leftTuple ); - } - if ( stagedInsertWasEmpty && linkOrNotify ) { - // staged is empty, so notify rule, to force re-evaluation. - lm.setNodeDirty(wm); + SegmentMemory sm, LeftTuple leftTuple, LeftInputAdapterNode liaNode) { + boolean stagedInsertWasEmpty = false; + + // mask check is necessary if insert is a result of a modify + if ( liaNode.isStreamMode() && sm.getTupleQueue() != null ) { + stagedInsertWasEmpty = sm.getTupleQueue().isEmpty(); + int propagationType = pctx.getType() == PropagationContext.MODIFICATION ? PropagationContext.INSERTION : pctx.getType(); + sm.getTupleQueue().add(new LeftTupleEntry(leftTuple, pctx, sm.getNodeMemories().getFirst(), propagationType)); + + if ( log.isTraceEnabled() ) { + log.trace( ""LeftInputAdapterNode insert size={} queue={} pctx={} lt={}"", System.identityHashCode( sm.getTupleQueue() ), sm.getTupleQueue().size(), PhreakPropagationContext.intEnumToString(pctx), leftTuple); } + } else { + stagedInsertWasEmpty = sm.getStagedLeftTuples().addInsert( leftTuple ); + } + if ( stagedInsertWasEmpty && linkOrNotify ) { + // staged is empty, so notify rule, to force re-evaluation. + lm.setNodeDirty(wm); } } @@ -332,9 +358,9 @@ public static void doUpdateObject(LeftTuple leftTuple, } sm = sm.getFirst(); // repoint to the child sm } - + LeftTupleSets leftTuples = sm.getStagedLeftTuples(); - + LeftTupleSink sink = liaNode.getSinkPropagator().getFirstLeftTupleSink() ; doUpdateSegmentMemory(leftTuple, context, wm, linkOrNotify, lm, sm, leftTuples, sink); @@ -357,25 +383,18 @@ private static void doUpdateSegmentMemory(LeftTuple leftTuple, PropagationContex // @TODO I synchronized this, as I'm not 100% of the thread interactions here, it might be possible to remove this later. if ( leftTuple.getStagedType() == LeftTuple.NONE ) { // if LeftTuple is already staged, leave it there - long mask = sink.getLeftInferredMask(); - - if ( intersect( pctx.getModificationMask(), mask) ) { - leftTuple.setPropagationContext( pctx ); // only update, if the mask intersects - - // only add to staging if masks match - - boolean stagedUpdateWasEmpty = false; - if ( ((BaseNode)sm.getRootNode()).isStreamMode() && sm.getTupleQueue() != null ) { - stagedUpdateWasEmpty = sm.getTupleQueue().isEmpty(); - sm.getTupleQueue().add(new LeftTupleEntry(leftTuple, pctx, sm.getNodeMemories().getFirst(), pctx.getType())); - } else { - stagedUpdateWasEmpty = leftTuples.addUpdate(leftTuple); - } + leftTuple.setPropagationContext( pctx ); + boolean stagedUpdateWasEmpty = false; + if ( ((BaseNode)sm.getRootNode()).isStreamMode() && sm.getTupleQueue() != null ) { + stagedUpdateWasEmpty = sm.getTupleQueue().isEmpty(); + sm.getTupleQueue().add(new LeftTupleEntry(leftTuple, pctx, sm.getNodeMemories().getFirst(), pctx.getType())); + } else { + stagedUpdateWasEmpty = leftTuples.addUpdate(leftTuple); + } - if ( stagedUpdateWasEmpty && linkOrNotify ) { - // staged is empty, so notify rule, to force re-evaluation - lm.setNodeDirty(wm); - } + if ( stagedUpdateWasEmpty && linkOrNotify ) { + // staged is empty, so notify rule, to force re-evaluation + lm.setNodeDirty(wm); } } } @@ -400,19 +419,9 @@ public void modifyObject(InternalFactHandle factHandle, final ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { - LeftTuple leftTuple = modifyPreviousTuples.peekLeftTuple(); - ObjectTypeNode.Id otnId = this.sink.getFirstLeftTupleSink().getLeftInputOtnId(); - while ( leftTuple != null && leftTuple.getLeftTupleSink().getLeftInputOtnId().before( otnId ) ) { - modifyPreviousTuples.removeLeftTuple(); - - LeftInputAdapterNode prevLiaNode = (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource(); - LiaNodeMemory prevLm = ( LiaNodeMemory ) workingMemory.getNodeMemory( prevLiaNode ); - SegmentMemory prevSm = prevLm.getSegmentMemory(); - doDeleteObject( leftTuple, context, prevSm, workingMemory, prevLiaNode, true, prevLm ); - leftTuple = modifyPreviousTuples.peekLeftTuple(); - } + LeftTuple leftTuple = processDeletesFromModify(modifyPreviousTuples, context, workingMemory, otnId); LiaNodeMemory lm = ( LiaNodeMemory ) workingMemory.getNodeMemory( this ); if ( lm.getSegmentMemory() == null ) { @@ -422,24 +431,64 @@ public void modifyObject(InternalFactHandle factHandle, if ( leftTuple != null && leftTuple.getLeftTupleSink().getLeftInputOtnId().equals( otnId ) ) { modifyPreviousTuples.removeLeftTuple(); leftTuple.reAdd(); - doUpdateObject( leftTuple, context, workingMemory, (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource(), true, lm, lm.getSegmentMemory() ); - + LeftTupleSink sink = getSinkPropagator().getFirstLeftTupleSink(); + long mask = sink.getLeftInferredMask(); + if ( intersect( context.getModificationMask(), mask) ) { + doUpdateObject( leftTuple, context, workingMemory, (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource(), true, lm, lm.getSegmentMemory() ); + } } else { - doInsertObject(factHandle, context, this, - workingMemory, - lm, true, true); + LeftTupleSink sink = getSinkPropagator().getFirstLeftTupleSink(); + long mask = sink.getLeftInferredMask(); + if ( intersect( context.getModificationMask(), mask) ) { + doInsertObject(factHandle, context, this, + workingMemory, + lm, true, true); + } + + } + } + + private static LeftTuple processDeletesFromModify(ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory, Id otnId) { + LeftTuple leftTuple = modifyPreviousTuples.peekLeftTuple(); + while ( leftTuple != null && leftTuple.getLeftTupleSink().getLeftInputOtnId().before( otnId ) ) { + modifyPreviousTuples.removeLeftTuple(); + + LeftInputAdapterNode prevLiaNode = (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource(); + LiaNodeMemory prevLm = ( LiaNodeMemory ) workingMemory.getNodeMemory( prevLiaNode ); + SegmentMemory prevSm = prevLm.getSegmentMemory(); + doDeleteObject( leftTuple, context, prevSm, workingMemory, prevLiaNode, true, prevLm ); + + leftTuple = modifyPreviousTuples.peekLeftTuple(); } + return leftTuple; } - + public void byPassModifyToBetaNode(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) { - modifyObject(factHandle, modifyPreviousTuples, context, workingMemory); + modifyObject(factHandle, modifyPreviousTuples, context, workingMemory ); +// ObjectTypeNode.Id otnId = this.sink.getFirstLeftTupleSink().getLeftInputOtnId(); +// +// LeftTuple leftTuple = processDeletesFromModify(modifyPreviousTuples, context, workingMemory, otnId); +// +// LiaNodeMemory lm = ( LiaNodeMemory ) workingMemory.getNodeMemory( this ); +// if ( lm.getSegmentMemory() == null ) { +// SegmentUtilities.createSegmentMemory( this, workingMemory ); +// } +// +// if ( leftTuple != null && leftTuple.getLeftTupleSink().getLeftInputOtnId().equals( otnId ) ) { +// modifyPreviousTuples.removeLeftTuple(); +// leftTuple.reAdd(); +// doUpdateObject( leftTuple, context, workingMemory, (LeftInputAdapterNode) leftTuple.getLeftTupleSink().getLeftTupleSource(), true, lm, lm.getSegmentMemory() ); +// } else { +// throw new RuntimeException(""no""); +// } } + protected void doRemove(final RuleRemovalContext context, final ReteooBuilder builder, final InternalWorkingMemory[] workingMemories) { @@ -447,7 +496,7 @@ protected void doRemove(final RuleRemovalContext context, objectSource.removeObjectSink(this); } } - + public LeftTuple createPeer(LeftTuple original) { return null; @@ -509,7 +558,7 @@ public boolean equals(final Object object) { final LeftInputAdapterNode other = (LeftInputAdapterNode) object; - return this.objectSource.equals(other.objectSource); + return this.sinkMask == other.sinkMask && this.objectSource.equals(other.objectSource); } protected ObjectTypeNode getObjectTypeNode() { @@ -525,8 +574,8 @@ protected ObjectTypeNode getObjectTypeNode() { public Memory createMemory(RuleBaseConfiguration config, InternalWorkingMemory wm) { return new LiaNodeMemory(); - } - + } + public static class LiaNodeMemory extends AbstractBaseLinkedListNode implements Memory { private int counter; @@ -655,7 +704,7 @@ public void writeExternal(ObjectOutput out) throws IOException { } public void readExternal(ObjectInput in) throws IOException, - ClassNotFoundException { + ClassNotFoundException { // this is a short living adapter class used only during an update operation, and // as so, no need for serialization code } @@ -676,4 +725,4 @@ public Map getAssociations() { } } -} +} \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/core/reteoo/NotNode.java b/drools-core/src/main/java/org/drools/core/reteoo/NotNode.java index f40c0197688..91ab52407b4 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/NotNode.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/NotNode.java @@ -231,43 +231,6 @@ public void doRemove(RuleRemovalContext context, ReteooBuilder builder, Internal } } - @Override - public void modifyObject(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory wm) { - RightTuple rightTuple = modifyPreviousTuples.peekRightTuple(); - - // if the peek is for a different OTN we assume that it is after the current one and then this is an assert - while ( rightTuple != null && - (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().before( getRightInputOtnId() ) ) { - modifyPreviousTuples.removeRightTuple(); - - // we skipped this node, due to alpha hashing, so retract now - rightTuple.setPropagationContext( context ); - BetaMemory bm = getBetaMemory( (BetaNode) rightTuple.getRightTupleSink(), wm ); - (( BetaNode ) rightTuple.getRightTupleSink()).doDeleteRightTuple( rightTuple, wm, bm ); - rightTuple = modifyPreviousTuples.peekRightTuple(); - } - - if ( rightTuple != null && (( BetaNode ) rightTuple.getRightTupleSink()).getRightInputOtnId().equals(getRightInputOtnId()) ) { - modifyPreviousTuples.removeRightTuple(); - rightTuple.reAdd(); - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple previously existed, so continue as modify - rightTuple.setPropagationContext( context ); // only update, if the mask intersects - - BetaMemory bm = getBetaMemory( this, wm ); - rightTuple.setPropagationContext( context ); - doUpdateRightTuple(rightTuple, wm, bm); - } - } else { - if ( intersect( context.getModificationMask(), getRightInferredMask() ) ) { - // RightTuple does not exist for this node, so create and continue as assert - assertObject( factHandle, - context, - wm ); - } - } - } - public boolean isLeftUpdateOptimizationAllowed() { return getRawConstraints().isLeftUpdateOptimizationAllowed(); }" 3be0759b44c97834e6fd96ac189500aa4d58dcc1,orientdb,Fixed issue -1445 providing the new TIMEOUT in- most of the commands--,a,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java index e8f9485d140..1f87da6be4c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java @@ -15,6 +15,7 @@ */ package com.orientechnologies.orient.core.command; +import java.util.Locale; import java.util.Map; import com.orientechnologies.common.listener.OProgressListener; @@ -35,8 +36,9 @@ public abstract class OCommandExecutorAbstract extends OBaseParser implements OC protected Map parameters; protected OCommandContext context; - public OCommandExecutorAbstract init(final String iText) { - parserText = iText; + public OCommandExecutorAbstract init(final OCommandRequestText iRequest) { + parserText = iRequest.getText().trim(); + parserTextUpperCase = parserText.toUpperCase(Locale.ENGLISH); return this; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java index 1fb1d707de0..920c9fbc76e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java @@ -23,6 +23,10 @@ * @param */ public interface OCommandRequest { + public enum TIMEOUT_STRATEGY { + EXCEPTION, RETURN + } + public RET execute(Object... iArgs); /** @@ -40,6 +44,27 @@ public interface OCommandRequest { */ public OCommandRequest setLimit(int iLimit); + /** + * Returns the command timeout. 0 means no timeout. + * + * @return + */ + public long getTimeoutTime(); + + /** + * Returns the command timeout strategy between the defined ones. + * + * @return + */ + public TIMEOUT_STRATEGY getTimeoutStrategy(); + + /** + * Sets the command timeout. When the command execution time is major than the timeout the command returns + * + * @param timeout + */ + public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy); + /** * Returns true if the command doesn't change the database, otherwise false. */ diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java index 4c52a5849e5..fa21df7fc00 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java @@ -19,6 +19,7 @@ import java.util.Map; import com.orientechnologies.common.listener.OProgressListener; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** @@ -31,10 +32,12 @@ public abstract class OCommandRequestAbstract implements OCommandRequestInternal { protected OCommandResultListener resultListener; protected OProgressListener progressListener; - protected int limit = -1; + protected int limit = -1; + protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; protected Map parameters; - protected String fetchPlan = null; - protected boolean useCache = false; + protected String fetchPlan = null; + protected boolean useCache = false; protected OCommandContext context; protected OCommandRequestAbstract() { @@ -128,4 +131,17 @@ public OCommandRequestAbstract setContext(final OCommandContext iContext) { context = iContext; return this; } + + public long getTimeoutTime() { + return timeoutMs; + } + + public void setTimeout(final long timeout, TIMEOUT_STRATEGY strategy) { + this.timeoutMs = timeout; + this.timeoutStrategy = strategy; + } + + public TIMEOUT_STRATEGY getTimeoutStrategy() { + return timeoutStrategy; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java index 5352ec9cbfc..04752630f1c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java @@ -28,15 +28,18 @@ * @param */ public interface OCommandRequestInternal extends OCommandRequest, OSerializableStream { - public Map getParameters(); - public OCommandResultListener getResultListener(); + public static final String EXECUTION_BEGUN = ""EXECUTION_BEGUN""; - public void setResultListener(OCommandResultListener iListener); + public Map getParameters(); - public OProgressListener getProgressListener(); + public OCommandResultListener getResultListener(); - public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener); + public void setResultListener(OCommandResultListener iListener); - public void reset(); + public OProgressListener getProgressListener(); + + public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener); + + public void reset(); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java index 732f46bece5..b4598281c83 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java @@ -125,6 +125,11 @@ protected byte[] toStream(final OMemoryStream buffer) { buffer.set(compositeKey.toStream()); } } + + // TIMEOUT + buffer.set(timeoutMs); + buffer.set((byte) timeoutStrategy.ordinal()); + return buffer.toByteArray(); } @@ -177,6 +182,9 @@ protected void fromStream(final OMemoryStream buffer) { parameters.put(p.getKey(), value); } } + + timeoutMs = buffer.getAsLong(); + timeoutStrategy = TIMEOUT_STRATEGY.values()[buffer.getAsByte()]; } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java index 087cd68f410..dd6fc79dfea 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java +++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java @@ -355,6 +355,9 @@ public void change(final Object iCurrentValue, final Object iNewValue) { } }), + // COMMAND + COMMAND_TIMEOUT(""command.timeout"", ""Default timeout for commands expressed in milliseconds"", Long.class, 0), + // CLIENT CLIENT_CHANNEL_MIN_POOL(""client.channel.minPool"", ""Minimum pool size"", Integer.class, 1), diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java index 16807468731..c9801165f66 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java @@ -15,9 +15,9 @@ */ package com.orientechnologies.orient.core.sql; -import java.util.Locale; - import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; +import com.orientechnologies.orient.core.command.OCommandRequest.TIMEOUT_STRATEGY; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; /** * SQL abstract Command Executor implementation. @@ -32,6 +32,7 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra public static final String KEYWORD_WHERE = ""WHERE""; public static final String KEYWORD_LIMIT = ""LIMIT""; public static final String KEYWORD_SKIP = ""SKIP""; + public static final String KEYWORD_TIMEOUT = ""TIMEOUT""; public static final String KEYWORD_KEY = ""key""; public static final String KEYWORD_RID = ""rid""; public static final String CLUSTER_PREFIX = ""CLUSTER:""; @@ -39,6 +40,9 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra public static final String INDEX_PREFIX = ""INDEX:""; public static final String DICTIONARY_PREFIX = ""DICTIONARY:""; + protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; + protected void throwSyntaxErrorException(final String iText) { throw new OCommandSQLParsingException(iText + "". Use "" + getSyntax(), parserText, parserGetPreviousPosition()); } @@ -47,14 +51,40 @@ protected void throwParsingException(final String iText) { throw new OCommandSQLParsingException(iText, parserText, parserGetPreviousPosition()); } - @Override - public OCommandExecutorSQLAbstract init(String iText) { - iText = iText.trim(); - parserTextUpperCase = iText.toUpperCase(Locale.ENGLISH); - return (OCommandExecutorSQLAbstract) super.init(iText); - } - public boolean isIdempotent() { return false; } + + /** + * Parses the timeout keyword if found. + */ + protected boolean parseTimeout(final String w) throws OCommandSQLParsingException { + if (!w.equals(KEYWORD_TIMEOUT)) + return false; + + parserNextWord(true); + String word = parserGetLastWord(); + + try { + timeoutMs = Long.parseLong(word); + } catch (Exception e) { + throwParsingException(""Invalid "" + KEYWORD_TIMEOUT + "" value setted to '"" + word + + ""' but it should be a valid long. Example: "" + KEYWORD_TIMEOUT + "" 3000""); + } + + if (timeoutMs < 0) + throwParsingException(""Invalid "" + KEYWORD_TIMEOUT + "": value setted to less than ZERO. Example: "" + timeoutMs + "" 10""); + + parserNextWord(true); + word = parserGetLastWord(); + + if (word.equals(TIMEOUT_STRATEGY.EXCEPTION.toString())) + timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; + else if (word.equals(TIMEOUT_STRATEGY.RETURN.toString())) + timeoutStrategy = TIMEOUT_STRATEGY.RETURN; + else + parserGoBack(); + + return true; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java index 47ad969ef18..3e04a79279f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java @@ -49,7 +49,7 @@ public OCommandExecutorSQLAlterClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java index a3366c5213e..07558bf140f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java @@ -52,7 +52,8 @@ public OCommandExecutorSQLAlterCluster parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java index d53bbfa2be6..2bdbe49bfd2 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java @@ -47,7 +47,8 @@ public OCommandExecutorSQLAlterDatabase parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java index 912bd6a0d00..0ada27949a8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLAlterProperty extends OCommandExecutorSQLAbstrac public OCommandExecutorSQLAlterProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java index c1388936a59..ae245b405e7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java @@ -50,7 +50,8 @@ public OCommandExecutorSQLCreateClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java index 4514ff84338..6f48a91e28c 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java @@ -53,7 +53,8 @@ public OCommandExecutorSQLCreateCluster parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(KEYWORD_CREATE); parserRequiredKeyword(KEYWORD_CLUSTER); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java index 287469ef3d0..4f1f3543687 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java @@ -52,7 +52,8 @@ public OCommandExecutorSQLCreateEdge parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(""CREATE""); parserRequiredKeyword(""EDGE""); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java index 82950427733..efc5b507b80 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java @@ -47,7 +47,8 @@ public OCommandExecutorSQLCreateFunction parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(""CREATE""); parserRequiredKeyword(""FUNCTION""); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java index d67a679f924..c902be41839 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java @@ -63,7 +63,8 @@ public class OCommandExecutorSQLCreateIndex extends OCommandExecutorSQLAbstract public OCommandExecutorSQLCreateIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java index 04b6e2da030..6090b6e1fe0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java @@ -65,7 +65,8 @@ public class OCommandExecutorSQLCreateLink extends OCommandExecutorSQLAbstract { public OCommandExecutorSQLCreateLink parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java index 2e6167d0aa4..280f24236f5 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLCreateProperty extends OCommandExecutorSQLAbstra public OCommandExecutorSQLCreateProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java index 2b6d136e260..bdb2f69200e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java @@ -45,7 +45,8 @@ public OCommandExecutorSQLCreateVertex parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + String className = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java index 0accc30b62c..e25c500a2ba 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java @@ -66,7 +66,8 @@ public OCommandExecutorSQLDelete parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + query = null; recordCount = 0; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java index b0f9c72477d..6b32adedae2 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java @@ -56,7 +56,8 @@ public OCommandExecutorSQLDeleteEdge parse(final OCommandRequest iRequest) { database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(""DELETE""); parserRequiredKeyword(""EDGE""); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java index 513141f9f82..230164bfbca 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java @@ -49,7 +49,8 @@ public OCommandExecutorSQLDeleteVertex parse(final OCommandRequest iRequest) { database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(""DELETE""); parserRequiredKeyword(""VERTEX""); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java index 7df6e5af21e..4e92bd50125 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java @@ -47,7 +47,8 @@ public class OCommandExecutorSQLDropClass extends OCommandExecutorSQLAbstract im public OCommandExecutorSQLDropClass parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java index 27200afee76..1c582d974a6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java @@ -42,7 +42,8 @@ public class OCommandExecutorSQLDropCluster extends OCommandExecutorSQLAbstract public OCommandExecutorSQLDropCluster parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java index d65e6b02665..81aee786a74 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java @@ -40,7 +40,8 @@ public class OCommandExecutorSQLDropIndex extends OCommandExecutorSQLAbstract im public OCommandExecutorSQLDropIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java index 49dafedc3c4..b37cd35408f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLDropProperty extends OCommandExecutorSQLAbstract public OCommandExecutorSQLDropProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java index 5778546619c..c1b35b5e073 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java @@ -48,7 +48,8 @@ public class OCommandExecutorSQLFindReferences extends OCommandExecutorSQLEarlyR public OCommandExecutorSQLFindReferences parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(KEYWORD_FIND); parserRequiredKeyword(KEYWORD_REFERENCES); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java index b8407910728..1931a9fa5fa 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java @@ -37,7 +37,8 @@ public class OCommandExecutorSQLGrant extends OCommandExecutorSQLPermissionAbstr public OCommandExecutorSQLGrant parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + privilege = ORole.PERMISSION_NONE; resource = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java index 4e755e62348..35a3c3810f8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java @@ -54,7 +54,8 @@ public OCommandExecutorSQLInsert parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + className = null; newRecords = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java index bbe7fde823d..cb40d905d96 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java @@ -42,7 +42,8 @@ public class OCommandExecutorSQLRebuildIndex extends OCommandExecutorSQLAbstract public OCommandExecutorSQLRebuildIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java index 6238be70e65..65534af6231 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java @@ -96,7 +96,7 @@ public OCommandExecutorSQLResultsetAbstract parse(final OCommandRequest iRequest OCommandRequestText textRequest = (OCommandRequestText) iRequest; - init(textRequest.getText()); + init(textRequest); if (iRequest instanceof OSQLSynchQuery) { request = (OSQLSynchQuery>) iRequest; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java index 1715ddb309b..1f008085736 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java @@ -39,7 +39,8 @@ public OCommandExecutorSQLRevoke parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + privilege = ORole.PERMISSION_NONE; resource = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java index 62702f9c0fc..c4af87e5648 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java @@ -31,10 +31,12 @@ import com.orientechnologies.common.collection.OCompositeKey; import com.orientechnologies.common.collection.OMultiValue; +import com.orientechnologies.common.concur.OTimeoutException; import com.orientechnologies.common.concur.resource.OSharedResource; import com.orientechnologies.common.util.OPair; import com.orientechnologies.orient.core.command.OBasicCommandContext; import com.orientechnologies.orient.core.command.OCommandRequest; +import com.orientechnologies.orient.core.command.OCommandRequestInternal; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; @@ -92,7 +94,8 @@ public class OCommandExecutorSQLSelect extends OCommandExecutorSQLResultsetAbstr public static final String KEYWORD_GROUP = ""GROUP""; private Map projectionDefinition = null; - private Map projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S USED THE + private Map projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S + // USED THE // PROJECTIONS IN GROUPED-RESULTS private List> orderedFields; private List groupByFields; @@ -153,6 +156,8 @@ else if (w.equals(KEYWORD_LIMIT)) parseLimit(w); else if (w.equals(KEYWORD_SKIP)) parseSkip(w); + else if (w.equals(KEYWORD_TIMEOUT)) + parseTimeout(w); else throwParsingException(""Invalid keyword '"" + w + ""'""); } @@ -355,6 +360,10 @@ protected boolean assignTarget(Map iArgs) { } protected boolean executeSearchRecord(final OIdentifiable id) { + + if (!checkTimeout()) + return false; + final ORecordInternal record = id.getRecord(); context.updateMetric(""recordReads"", +1); @@ -373,6 +382,24 @@ protected boolean executeSearchRecord(final OIdentifiable id) { return true; } + protected boolean checkTimeout() { + if (timeoutMs > 0) { + final Long begun = (Long) context.getVariable(OCommandRequestInternal.EXECUTION_BEGUN); + if (begun != null) { + if (System.currentTimeMillis() - begun.longValue() > timeoutMs) { + // TIMEOUT! + switch (timeoutStrategy) { + case RETURN: + return false; + case EXCEPTION: + throw new OTimeoutException(""Command execution timeout exceed ("" + timeoutMs + ""ms)""); + } + } + } + } + return true; + } + protected boolean handleResult(final OIdentifiable iRecord) { lastRecord = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java index b063c16579e..02a2fa91f0f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java @@ -104,6 +104,8 @@ public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) { parseLimit(w); else if (w.equals(KEYWORD_SKIP)) parseSkip(w); + else if (w.equals(KEYWORD_TIMEOUT)) + parseTimeout(w); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java index 63d4adc916e..bc713db2775 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java @@ -43,7 +43,8 @@ public OCommandExecutorSQLTruncateClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java index 7c3079e5083..77d30763ca8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java @@ -44,7 +44,8 @@ public OCommandExecutorSQLTruncateCluster parse(final OCommandRequest iRequest) final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java index 5d581d20360..49768ec3f0a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java @@ -46,7 +46,8 @@ public class OCommandExecutorSQLTruncateRecord extends OCommandExecutorSQLAbstra public OCommandExecutorSQLTruncateRecord parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java index cc0fcfdf968..5d95038cb44 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java @@ -76,7 +76,8 @@ public OCommandExecutorSQLUpdate parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + setEntries.clear(); addEntries.clear(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java index b03f1d3f998..13567cf999a 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java @@ -23,6 +23,7 @@ import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.OCommandExecutor; import com.orientechnologies.orient.core.command.OCommandManager; +import com.orientechnologies.orient.core.command.OCommandRequestInternal; import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; @@ -92,6 +93,8 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE throw new OCommandExecutionException(""Cannot execute non idempotent command""); long beginTime = Orient.instance().getProfiler().startChrono(); + executor.getContext().setVariable(OCommandRequestInternal.EXECUTION_BEGUN, System.currentTimeMillis()); + try { final Object result = executor.execute(iCommand.getParameters()); @@ -104,11 +107,12 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE throw new OCommandExecutionException(""Error on execution of command: "" + iCommand, e); } finally { - Orient - .instance() - .getProfiler() - .stopChrono(""db."" + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + "".command."" + iCommand.toString(), - ""Command executed against the database"", beginTime, ""db.*.command.*""); + if (Orient.instance().getProfiler().isRecording()) + Orient + .instance() + .getProfiler() + .stopChrono(""db."" + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + "".command."" + iCommand.toString(), + ""Command executed against the database"", beginTime, ""db.*.command.*""); } } diff --git a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java index e7a62a66c34..2e29005b6de 100644 --- a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java +++ b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java @@ -109,4 +109,20 @@ public OCommandRequest setContext(final OCommandContext iContext) { command.setContext(iContext); return this; } + + @Override + public long getTimeoutTime() { + return command.getTimeoutTime(); + } + + @Override + public TIMEOUT_STRATEGY getTimeoutStrategy() { + return command.getTimeoutStrategy(); + } + + @Override + public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy) { + command.setTimeout(timeout, strategy); + + } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index 3b44b781188..99feabfd001 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -24,6 +24,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; + import com.orientechnologies.common.io.OIOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.OConstants; @@ -326,15 +327,15 @@ protected boolean executeRequest() throws IOException { releaseDatabase(); break; - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: - freezeCluster(); - break; + case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: + freezeCluster(); + break; - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: - releaseCluster(); - break; + case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: + releaseCluster(); + break; - case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: + case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: cleanOutRecord(); break; @@ -1125,6 +1126,12 @@ protected void command() throws IOException { final Map fetchPlan = command != null ? OFetchHelper.buildFetchPlan(command.getFetchPlan()) : null; command.setResultListener(new AsyncResultListener(empty, clientTxId, fetchPlan, recordsToSend)); + final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + + if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout) + // FORCE THE SERVER'S TIMEOUT + command.setTimeout(serverTimeout, command.getTimeoutStrategy()); + ((OCommandRequestInternal) connection.database.command(command)).execute(); if (empty.get())" ae360480a9a955030a6621721a649bbf360d3c9a,orientdb,Improved performance by handling begin and end of- offsets in cluster data.--,p,https://github.com/orientechnologies/orientdb,"diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java index 94ebc0eea54..035501bda04 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java @@ -310,19 +310,19 @@ public long count(final int iClusterId) { return count(new int[] { iClusterId }); } - public long getClusterLastEntryPosition(final int iClusterId) { + public long[] getClusterDataRange(final int iClusterId) { checkConnection(); do { boolean locked = acquireExclusiveLock(); try { - network.writeByte(OChannelBinaryProtocol.CLUSTER_LASTPOS); + network.writeByte(OChannelBinaryProtocol.CLUSTER_DATARANGE); network.writeShort((short) iClusterId); network.flush(); readStatus(); - return network.readLong(); + return new long[]{ network.readLong(), network.readLong()}; } catch (Exception e) { if (handleException(""Error on getting last entry position count in cluster: "" + iClusterId, e)) break; @@ -331,7 +331,7 @@ public long getClusterLastEntryPosition(final int iClusterId) { releaseExclusiveLock(locked); } } while (true); - return -1; + return null; } public long count(final int[] iClusterIds) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java index 2c05c811838..3eed86bd954 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java +++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java @@ -31,140 +31,146 @@ */ @SuppressWarnings(""serial"") public class OCacheRecord extends OSharedResourceAdaptive { - private final int maxSize; - private LinkedHashMap cache; - - /** - * Create the cache of iMaxSize size. - * - * @param iMaxSize - * Maximum number of elements for the cache - */ - public OCacheRecord(final int iMaxSize) { - maxSize = iMaxSize; - - cache = new LinkedHashMap(iMaxSize, 0.75f, true) { - @Override - protected boolean removeEldestEntry(java.util.Map.Entry iEldest) { - return size() > maxSize; - } - }; - } - - public void pushRecord(final String iRecord, ORawBuffer iContent) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.put(iRecord, iContent); - - } finally { - releaseExclusiveLock(locked); - } - } - - /** - * Find a record in cache by String - * - * @param iRecord - * String instance - * @return The record buffer if found, otherwise null - */ - public ORawBuffer getRecord(final String iRecord) { - if (maxSize == 0) - return null; - - final boolean locked = acquireSharedLock(); - - try { - return cache.get(iRecord); - - } finally { - releaseSharedLock(locked); - } - } - - public ORawBuffer popRecord(final String iRecord) { - if (maxSize == 0) - return null; - - final boolean locked = acquireExclusiveLock(); - - try { - ORawBuffer buffer = cache.remove(iRecord); - - if (buffer != null) - OProfiler.getInstance().updateStatistic(""Cache.reused"", +1); - - return buffer; - } finally { - releaseExclusiveLock(locked); - } - } - - public void removeRecord(final String iRecord) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.remove(iRecord); - - } finally { - releaseExclusiveLock(locked); - } - } - - /** - * Remove multiple records from the cache in one shot saving the cost of locking for each record. - * - * @param iRecords - * List of Strings - */ - public void removeRecords(final List iRecords) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - for (String id : iRecords) - cache.remove(id); - - } finally { - releaseExclusiveLock(locked); - } - } - - public void clear() { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.clear(); - - } finally { - releaseExclusiveLock(locked); - } - } + private final int maxSize; + private LinkedHashMap cache; + + /** + * Create the cache of iMaxSize size. + * + * @param iMaxSize + * Maximum number of elements for the cache + */ + public OCacheRecord(final int iMaxSize) { + maxSize = iMaxSize; + + cache = new LinkedHashMap(iMaxSize, 0.75f, true) { + @Override + protected boolean removeEldestEntry(java.util.Map.Entry iEldest) { + return size() > maxSize; + } + }; + } + + public void pushRecord(final String iRecord, ORawBuffer iContent) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + cache.put(iRecord, iContent); + + } finally { + releaseExclusiveLock(locked); + } + } + + /** + * Find a record in cache by String + * + * @param iRecord + * String instance + * @return The record buffer if found, otherwise null + */ + public ORawBuffer getRecord(final String iRecord) { + if (maxSize == 0) + return null; + + final boolean locked = acquireSharedLock(); + + try { + return cache.get(iRecord); + + } finally { + releaseSharedLock(locked); + } + } + + public ORawBuffer popRecord(final String iRecord) { + if (maxSize == 0) + return null; + + final boolean locked = acquireExclusiveLock(); + + try { + ORawBuffer buffer = cache.remove(iRecord); + + if (buffer != null) + OProfiler.getInstance().updateStatistic(""Cache.reused"", +1); + + return buffer; + } finally { + releaseExclusiveLock(locked); + } + } + + public void removeRecord(final String iRecord) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + cache.remove(iRecord); + + } finally { + releaseExclusiveLock(locked); + } + } + + /** + * Remove multiple records from the cache in one shot saving the cost of locking for each record. + * + * @param iRecords + * List of Strings + */ + public void removeRecords(final List iRecords) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + for (String id : iRecords) + cache.remove(id); + + } finally { + releaseExclusiveLock(locked); + } + } + + public void clear() { + if (maxSize == 0) + return; - public int getMaxSize() { - return maxSize; - } + final boolean locked = acquireExclusiveLock(); + + try { + cache.clear(); + + } finally { + releaseExclusiveLock(locked); + } + } + + public int getMaxSize() { + return maxSize; + } + + public int size() { + final boolean locked = acquireSharedLock(); + + try { + return cache.size(); + + } finally { + releaseSharedLock(locked); + } + } + + @Override + public String toString() { + return ""Cached items="" + cache.size() + "", maxSize="" + maxSize; + } - public int size() { - final boolean locked = acquireSharedLock(); - - try { - return cache.size(); - - } finally { - releaseSharedLock(locked); - } - } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java index a35381ad97e..07f25a81db7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java @@ -89,7 +89,7 @@ public OGraphElement load(final OGraphElement iObject) { public OGraphElement load(final ORID iRecordId) { if (iRecordId == null) return null; - + // TRY IN LOCAL CACHE ODocument doc = getRecordById(iRecordId); if (doc == null) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java index b99c0b8d103..6bf75ecfd91 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java @@ -144,7 +144,7 @@ public static void delete(final ODatabaseGraphTx iDatabase, final ODocument iEdg targetVertex.setDirty(); targetVertex.save(); - if (iDatabase.existsUserObjectByRecord(sourceVertex)) { + if (iDatabase.existsUserObjectByRecord(iEdge)) { final OGraphEdge edge = (OGraphEdge) iDatabase.getUserObjectByRecord(iEdge, null); iDatabase.unregisterPojo(edge, iEdge); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java index 0c7e5a4381b..c722dffa7b1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java @@ -17,6 +17,7 @@ import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; import com.orientechnologies.orient.core.db.graph.OGraphEdge; +import com.orientechnologies.orient.core.record.impl.ODocument; /** * Iterator to browse all the edges. @@ -31,7 +32,13 @@ public OGraphEdgeIterator(final ODatabaseGraphTx iDatabase) { } public OGraphEdge next(final String iFetchPlan) { - return new OGraphEdge(database, underlying.next()); + final ODocument doc = underlying.next(); + + OGraphEdge v = (OGraphEdge) database.getUserObjectByRecord(doc, null); + if (v != null) + return v; + + return new OGraphEdge(database, doc); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java index 2d14bd4998c..52d529ac016 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java @@ -17,6 +17,7 @@ import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; import com.orientechnologies.orient.core.db.graph.OGraphVertex; +import com.orientechnologies.orient.core.record.impl.ODocument; /** * Iterator to browse all the vertexes. @@ -31,6 +32,13 @@ public OGraphVertexIterator(final ODatabaseGraphTx iDatabase) { } public OGraphVertex next(final String iFetchPlan) { - return new OGraphVertex(database, underlying.next()); + final ODocument doc = underlying.next(); + + final OGraphVertex v = (OGraphVertex) database.getUserObjectByRecord(doc, + null); + if (v != null) + return v; + + return new OGraphVertex(database, doc); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java index 815f1cc9077..9f6e7b936ea 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java @@ -28,16 +28,19 @@ * @author Luca Garulli * * @param - * Record Type + * Record Type */ -public class ORecordIteratorCluster> extends ORecordIterator { - protected int currentClusterId; - protected long rangeFrom; - protected long rangeTo; - protected long lastClusterPosition; - protected long totalAvailableRecords; - - public ORecordIteratorCluster(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase, +public class ORecordIteratorCluster> extends + ORecordIterator { + protected int currentClusterId; + protected long rangeFrom; + protected long rangeTo; + protected long firstClusterPosition; + protected long lastClusterPosition; + protected long totalAvailableRecords; + + public ORecordIteratorCluster(final ODatabaseRecord iDatabase, + final ODatabaseRecordAbstract iLowLevelDatabase, final int iClusterId) { super(iDatabase, iLowLevelDatabase); if (iClusterId == ORID.CLUSTER_ID_INVALID) @@ -47,7 +50,13 @@ public ORecordIteratorCluster(final ODatabaseRecord iDatabase, final ODatab rangeFrom = -1; rangeTo = -1; - lastClusterPosition = database.getStorage().getClusterLastEntryPosition(currentClusterId); + long[] range = database.getStorage().getClusterDataRange( + currentClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + +// currentClusterPosition = firstClusterPosition - 1; + totalAvailableRecords = database.countClusterElements(currentClusterId); } @@ -72,9 +81,11 @@ public boolean hasNext() { } /** - * Return the element at the current position and move backward the cursor to the previous position available. + * Return the element at the current position and move backward the cursor + * to the previous position available. * - * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + * @return the previous record found, otherwise the NoSuchElementException + * exception is thrown when no more records are found. */ @Override public REC previous() { @@ -91,9 +102,11 @@ public REC previous() { } /** - * Return the element at the current position and move forward the cursor to the next position available. + * Return the element at the current position and move forward the cursor to + * the next position available. * - * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + * @return the next record found, otherwise the NoSuchElementException + * exception is thrown when no more records are found. */ public REC next() { // ITERATE UNTIL THE NEXT GOOD RECORD @@ -115,7 +128,8 @@ public REC current() { } /** - * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. + * Move the iterator to the begin of the range. If no range was specified + * move to the first record of the cluster. * * @return The object itself */ @@ -126,7 +140,8 @@ public ORecordIterator begin() { } /** - * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. + * Move the iterator to the end of the range. If no range was specified move + * to the last record of the cluster. * * @return The object itself */ @@ -140,14 +155,16 @@ public ORecordIterator last() { * Define the range where move the iterator forward and backward. * * @param iFrom - * Lower bound limit of the range + * Lower bound limit of the range * @param iEnd - * Upper bound limit of the range + * Upper bound limit of the range * @return */ - public ORecordIteratorCluster setRange(final long iFrom, final long iEnd) { - currentClusterPosition = iFrom; + public ORecordIteratorCluster setRange(final long iFrom, + final long iEnd) { + firstClusterPosition = iFrom; rangeTo = iEnd; + currentClusterPosition = firstClusterPosition; return this; } @@ -157,11 +174,19 @@ public ORecordIteratorCluster setRange(final long iFrom, final long iEnd) { * @return */ public long getRangeFrom() { - return Math.max(rangeFrom, -1); + if (!liveUpdated) + return firstClusterPosition - 1; + + final long limit = database.getStorage().getClusterDataRange( + currentClusterId)[0] - 1; + if (rangeFrom > -1) + return Math.max(rangeFrom, limit); + return limit; } /** - * Return the upper bound limit of the range if any, otherwise the last record. + * Return the upper bound limit of the range if any, otherwise the last + * record. * * @return */ @@ -169,33 +194,45 @@ public long getRangeTo() { if (!liveUpdated) return lastClusterPosition + 1; - final long limit = database.getStorage().getClusterLastEntryPosition(currentClusterId) + 1; + final long limit = database.getStorage().getClusterDataRange( + currentClusterId)[1] + 1; if (rangeTo > -1) return Math.min(rangeTo, limit); return limit; } /** - * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change - * the size of the cluster while you're browsing it. Default is false. + * Tell to the iterator that the upper limit must be checked at every cycle. + * Useful when concurrent deletes or additions change the size of the + * cluster while you're browsing it. Default is false. * * @param iLiveUpdated - * True to activate it, otherwise false (default) + * True to activate it, otherwise false (default) * @see #isLiveUpdated() */ @Override public ORecordIterator setLiveUpdated(boolean iLiveUpdated) { super.setLiveUpdated(iLiveUpdated); - // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED - lastClusterPosition = iLiveUpdated ? -1 : database.getStorage().getClusterLastEntryPosition(currentClusterId); + // SET THE RANGE LIMITS + if (iLiveUpdated) { + firstClusterPosition = -1; + lastClusterPosition = -1; + } else { + long[] range = database.getStorage().getClusterDataRange( + currentClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + } + totalAvailableRecords = database.countClusterElements(currentClusterId); return this; } /** - * Read the current record and increment the counter if the record was found. + * Read the current record and increment the counter if the record was + * found. * * @param iRecord * @return @@ -207,7 +244,8 @@ private REC readCurrentRecord(REC iRecord, final int iMovement) { currentClusterPosition += iMovement; - iRecord = lowLevelDatabase.executeReadRecord(currentClusterId, currentClusterPosition, iRecord, fetchPlan); + iRecord = lowLevelDatabase.executeReadRecord(currentClusterId, + currentClusterPosition, iRecord, fetchPlan); if (iRecord != null) browsedRecords++; diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java index 90e5fbe1e53..bbeb67113f1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java @@ -33,177 +33,194 @@ * Record Type */ public class ORecordIteratorMultiCluster> extends ORecordIterator { - protected final int[] clusterIds; - protected int currentClusterIdx; - - protected int lastClusterId; - protected long lastClusterPosition; - protected long totalAvailableRecords; - - public ORecordIteratorMultiCluster(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase, - final int[] iClusterIds) { - super(iDatabase, iLowLevelDatabase); - - clusterIds = iClusterIds; - - currentClusterIdx = 0; // START FROM THE FIRST CLUSTER - currentClusterPosition = -1; // DEFAULT = START FROM THE BEGIN - - lastClusterId = clusterIds[clusterIds.length - 1]; - lastClusterPosition = database.getStorage().getClusterLastEntryPosition(lastClusterId); - - totalAvailableRecords = database.countClusterElements(iClusterIds); - } - - @Override - public boolean hasPrevious() { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return false; - - return currentClusterPosition > 0; - } - - public boolean hasNext() { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return false; - - if (browsedRecords >= totalAvailableRecords) - return false; - - if (currentClusterIdx < clusterIds.length - 1) - // PRESUME THAT IF IT'S NOT AT THE LAST CLUSTER THERE COULD BE OTHER ELEMENTS - return true; - - if (liveUpdated) - return currentClusterPosition < database.getStorage().getClusterLastEntryPosition(lastClusterId); - - return currentClusterPosition < lastClusterPosition; - } - - /** - * Return the element at the current position and move backward the cursor to the previous position available. - * - * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. - */ - @Override - public REC previous() { - final REC record = getRecord(); - - // ITERATE UNTIL THE PREVIOUS GOOD RECORD - while (currentClusterIdx > -1) { - - // MOVE BACKWARD IN THE CURRENT CLUSTER - while (hasPrevious()) { - if (readCurrentRecord(record, -1) != null) - // FOUND - return record; - } - - // CLUSTER EXHAUSTED, TRY WITH THE PREVIOUS ONE - currentClusterIdx--; - } - - throw new NoSuchElementException(); - } - - /** - * Return the element at the current position and move forward the cursor to the next position available. - * - * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. - */ - public REC next() { - final REC record = getRecord(); - - // ITERATE UNTIL THE NEXT GOOD RECORD - while (currentClusterIdx < clusterIds.length) { - - // MOVE FORWARD IN THE CURRENT CLUSTER - while (hasNext()) { - if (readCurrentRecord(record, +1) != null) - // FOUND - return record; - } - - // CLUSTER EXHAUSTED, TRY WITH THE NEXT ONE - currentClusterIdx++; - } - - throw new NoSuchElementException(); - } - - public REC current() { - final REC record = getRecord(); - return readCurrentRecord(record, 0); - } - - /** - * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. - * - * @return The object itself - */ - @Override - public ORecordIterator begin() { - currentClusterIdx = 0; - currentClusterPosition = -1; - return this; - } - - /** - * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. - * - * @return The object itself - */ - @Override - public ORecordIterator last() { - currentClusterIdx = clusterIds.length - 1; - currentClusterPosition = liveUpdated ? database.countClusterElements(clusterIds[currentClusterIdx]) : lastClusterPosition + 1; - return this; - } - - /** - * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change - * the size of the cluster while you're browsing it. Default is false. - * - * @param iLiveUpdated - * True to activate it, otherwise false (default) - * @see #isLiveUpdated() - */ - @Override - public ORecordIterator setLiveUpdated(boolean iLiveUpdated) { - super.setLiveUpdated(iLiveUpdated); - - // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED - lastClusterPosition = iLiveUpdated ? -1 : database.countClusterElements(lastClusterId); - - return this; - } - - /** - * Read the current record and increment the counter if the record was found. - * - * @param iRecord - * @return - */ - private REC readCurrentRecord(REC iRecord, final int iMovement) { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return null; - - currentClusterPosition += iMovement; - - iRecord = loadRecord(iRecord); - - if (iRecord != null) { - browsedRecords++; - return iRecord; - } - - return null; - } - - protected REC loadRecord(final REC iRecord) { - return lowLevelDatabase.executeReadRecord(clusterIds[currentClusterIdx], currentClusterPosition, iRecord, fetchPlan); - } + protected final int[] clusterIds; + protected int currentClusterIdx; + + protected int lastClusterId; + protected long firstClusterPosition; + protected long lastClusterPosition; + protected long totalAvailableRecords; + + public ORecordIteratorMultiCluster(final ODatabaseRecord iDatabase, final ODatabaseRecordAbstract iLowLevelDatabase, + final int[] iClusterIds) { + super(iDatabase, iLowLevelDatabase); + + clusterIds = iClusterIds; + + currentClusterIdx = 0; // START FROM THE FIRST CLUSTER + + lastClusterId = clusterIds[clusterIds.length - 1]; + + long[] range = database.getStorage().getClusterDataRange(lastClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + + currentClusterPosition = firstClusterPosition - 1; + + totalAvailableRecords = database.countClusterElements(iClusterIds); + } + + @Override + public boolean hasPrevious() { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return false; + + if (liveUpdated) + return currentClusterPosition > database.getStorage().getClusterDataRange(lastClusterId)[0]; + + return currentClusterPosition > firstClusterPosition; + } + + public boolean hasNext() { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return false; + + if (browsedRecords >= totalAvailableRecords) + return false; + + if (currentClusterIdx < clusterIds.length - 1) + // PRESUME THAT IF IT'S NOT AT THE LAST CLUSTER THERE COULD BE OTHER ELEMENTS + return true; + + if (liveUpdated) + return currentClusterPosition < database.getStorage().getClusterDataRange(lastClusterId)[1]; + + return currentClusterPosition < lastClusterPosition; + } + + /** + * Return the element at the current position and move backward the cursor to the previous position available. + * + * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + */ + @Override + public REC previous() { + final REC record = getRecord(); + + // ITERATE UNTIL THE PREVIOUS GOOD RECORD + while (currentClusterIdx > -1) { + + // MOVE BACKWARD IN THE CURRENT CLUSTER + while (hasPrevious()) { + if (readCurrentRecord(record, -1) != null) + // FOUND + return record; + } + + // CLUSTER EXHAUSTED, TRY WITH THE PREVIOUS ONE + currentClusterIdx--; + } + + throw new NoSuchElementException(); + } + + /** + * Return the element at the current position and move forward the cursor to the next position available. + * + * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + */ + public REC next() { + final REC record = getRecord(); + + // ITERATE UNTIL THE NEXT GOOD RECORD + while (currentClusterIdx < clusterIds.length) { + + // MOVE FORWARD IN THE CURRENT CLUSTER + while (hasNext()) { + if (readCurrentRecord(record, +1) != null) + // FOUND + return record; + } + + // CLUSTER EXHAUSTED, TRY WITH THE NEXT ONE + currentClusterIdx++; + } + + throw new NoSuchElementException(); + } + + public REC current() { + final REC record = getRecord(); + return readCurrentRecord(record, 0); + } + + /** + * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. + * + * @return The object itself + */ + @Override + public ORecordIterator begin() { + currentClusterIdx = 0; + currentClusterPosition = -1; + return this; + } + + /** + * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. + * + * @return The object itself + */ + @Override + public ORecordIterator last() { + currentClusterIdx = clusterIds.length - 1; + currentClusterPosition = liveUpdated ? database.countClusterElements(clusterIds[currentClusterIdx]) : lastClusterPosition + 1; + return this; + } + + /** + * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change + * the size of the cluster while you're browsing it. Default is false. + * + * @param iLiveUpdated + * True to activate it, otherwise false (default) + * @see #isLiveUpdated() + */ + @Override + public ORecordIterator setLiveUpdated(boolean iLiveUpdated) { + super.setLiveUpdated(iLiveUpdated); + + // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED + lastClusterPosition = iLiveUpdated ? -1 : database.countClusterElements(lastClusterId); + + if (iLiveUpdated) { + firstClusterPosition = -1; + lastClusterPosition = -1; + } else { + long[] range = database.getStorage().getClusterDataRange(lastClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + } + + return this; + } + + /** + * Read the current record and increment the counter if the record was found. + * + * @param iRecord + * @return + */ + private REC readCurrentRecord(REC iRecord, final int iMovement) { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return null; + + currentClusterPosition += iMovement; + + iRecord = loadRecord(iRecord); + + if (iRecord != null) { + browsedRecords++; + return iRecord; + } + + return null; + } + + protected REC loadRecord(final REC iRecord) { + return lowLevelDatabase.executeReadRecord(clusterIds[currentClusterIdx], currentClusterPosition, iRecord, fetchPlan); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java index 8d15f48b4d9..7735ecbc05d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java @@ -68,6 +68,8 @@ public interface OCluster { public long getEntries() throws IOException; + public long getFirstEntryPosition() throws IOException; + public long getLastEntryPosition() throws IOException; /** diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java index 4708ba92f51..221ffc997d7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java @@ -19,17 +19,18 @@ import java.util.Iterator; public class OClusterPositionIterator implements Iterator { - private final OCluster cluster; - private long current = 0; - private final long max; + private final OCluster cluster; + private long current; + private final long max; public OClusterPositionIterator(final OCluster iCluster) throws IOException { cluster = iCluster; + current = cluster.getFirstEntryPosition(); max = cluster.getLastEntryPosition(); } public boolean hasNext() { - return current <= max; + return max > -1 && current <= max; } public Long next() { diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java index 1ba05194a04..a737fee6d10 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java @@ -142,10 +142,10 @@ public int updateRecord(int iRequesterId, int iClusterId, long iPosition, byte[] public Object command(OCommandRequestText iCommand); /** - * Returns the last entry position in the requested cluster. Useful to know the range of the records. + * Returns a pair of long values telling the begin and end positions of data in the requested cluster. Useful to know the range of the records. * * @param iCurrentClusterId * Cluster id */ - public long getClusterLastEntryPosition(int currentClusterId); + public long[] getClusterDataRange(int currentClusterId); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java index 615963520bd..5ed13ce0378 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java @@ -26,7 +26,7 @@ public abstract class OStorageAbstract extends OSharedResourceAdaptive implement protected String name; protected String url; protected String mode; - protected OCacheRecord cache = new OCacheRecord(2000); + protected OCacheRecord cache = new OCacheRecord(20000); protected boolean open = false; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java index 6316e93582a..00840b32fc0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java @@ -56,6 +56,7 @@ public abstract class OFile { protected String mode; protected static final int HEADER_SIZE = 1024; + protected static final int HEADER_DATA_OFFSET = 128; protected static final int DEFAULT_SIZE = 15000000; protected static final int DEFAULT_INCREMENT_SIZE = -50; // NEGATIVE NUMBER MEANS AS PERCENT OF CURRENT SIZE @@ -67,6 +68,10 @@ public OFile(final String iFileName, final String iMode) throws IOException { protected abstract void readHeader() throws IOException; + public abstract void writeHeaderLong(int iPosition, long iValue) throws IOException; + + public abstract long readHeaderLong(int iPosition) throws IOException; + protected abstract void setSoftlyClosed(boolean b) throws IOException; protected abstract boolean isSoftlyClosed() throws IOException; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java index 0b4936b6be0..231949d77ae 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java @@ -34,7 +34,7 @@ *
    */ public class OFileClassic extends OFile { - protected ByteBuffer internalWriteBuffer = getBuffer(OConstants.SIZE_LONG); + protected ByteBuffer internalWriteBuffer = getBuffer(OConstants.SIZE_LONG); public OFileClassic(String iFileName, String iMode) throws IOException { super(iFileName, iMode); @@ -50,7 +50,8 @@ public void close() throws IOException { } @Override - public void read(int iOffset, byte[] iDestBuffer, int iLenght) throws IOException { + public void read(int iOffset, byte[] iDestBuffer, int iLenght) + throws IOException { iOffset = checkRegions(iOffset, iLenght); ByteBuffer buffer = ByteBuffer.wrap(iDestBuffer); @@ -129,7 +130,9 @@ public void changeSize(int iSize) { openChannel(iSize); } catch (IOException e) { - OLogManager.instance().error(this, ""Error on changing the file size to "" + iSize + "" bytes"", e, OIOException.class); + OLogManager.instance().error(this, + ""Error on changing the file size to "" + iSize + "" bytes"", + e, OIOException.class); } } @@ -145,7 +148,8 @@ public void synch() { @Override protected void readHeader() throws IOException { size = readData(0, OConstants.SIZE_INT).getInt(); - filledUpTo = readData(OConstants.SIZE_INT, OConstants.SIZE_INT).getInt(); + filledUpTo = readData(OConstants.SIZE_INT, OConstants.SIZE_INT) + .getInt(); } @Override @@ -156,6 +160,19 @@ protected void writeHeader() throws IOException { writeData(buffer, 0); } + @Override + public void writeHeaderLong(int iPosition, long iValue) + throws IOException { + ByteBuffer buffer = getWriteBuffer(OConstants.SIZE_LONG); + buffer.putLong(iValue); + writeData(buffer, HEADER_DATA_OFFSET + iPosition); + } + + @Override + public long readHeaderLong(int iPosition) throws IOException { + return readData(HEADER_DATA_OFFSET + iPosition, OConstants.SIZE_LONG).getLong(); + } + @Override public boolean isSoftlyClosed() throws IOException { return readData(SOFTLY_CLOSED_OFFSET, OConstants.SIZE_BYTE).get() == 1; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java index bc658c21bf9..def18923117 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java @@ -36,9 +36,9 @@ *
    */ public class OFileMMap extends OFile { - protected MappedByteBuffer headerBuffer; - protected int bufferBeginOffset = -1; - protected int bufferSize = 0; + protected MappedByteBuffer headerBuffer; + protected int bufferBeginOffset = -1; + protected int bufferSize = 0; public OFileMMap(String iFileName, String iMode) throws IOException { super(iFileName, iMode); @@ -48,7 +48,8 @@ public OFileMMap(String iFileName, String iMode) throws IOException { public void read(int iOffset, final byte[] iDestBuffer, final int iLenght) { iOffset = checkRegions(iOffset, iLenght); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, iLenght); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + iLenght); entry.buffer.position(iOffset - entry.beginOffset); entry.buffer.get(iDestBuffer, 0, iLenght); } @@ -56,56 +57,64 @@ public void read(int iOffset, final byte[] iDestBuffer, final int iLenght) { @Override public int readInt(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_INT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT); return entry.buffer.getInt(iOffset - entry.beginOffset); } @Override public long readLong(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_LONG); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_LONG); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_LONG); return entry.buffer.getLong(iOffset - entry.beginOffset); } @Override public short readShort(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_SHORT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_SHORT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_SHORT); return entry.buffer.getShort(iOffset - entry.beginOffset); } @Override public byte readByte(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_BYTE); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_BYTE); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_BYTE); return entry.buffer.get(iOffset - entry.beginOffset); } @Override public void writeInt(int iOffset, final int iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_INT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT); entry.buffer.putInt(iOffset - entry.beginOffset, iValue); } @Override public void writeLong(int iOffset, final long iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_LONG); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_LONG); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_LONG); entry.buffer.putLong(iOffset - entry.beginOffset, iValue); } @Override public void writeShort(int iOffset, final short iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_SHORT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_SHORT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_SHORT); entry.buffer.putShort(iOffset - entry.beginOffset, iValue); } @Override public void writeByte(int iOffset, final byte iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_BYTE); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_BYTE); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_BYTE); entry.buffer.put(iOffset - entry.beginOffset, iValue); } @@ -114,13 +123,16 @@ public void write(int iOffset, final byte[] iSourceBuffer) { iOffset = checkRegions(iOffset, iSourceBuffer.length); try { - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT + iSourceBuffer.length); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT + iSourceBuffer.length); entry.buffer.position(iOffset - entry.beginOffset); entry.buffer.put(iSourceBuffer); } catch (BufferOverflowException e) { - OLogManager.instance() - .error(this, ""Error on write in the range "" + iOffset + ""-"" + iOffset + iSourceBuffer.length + ""."" + toString(), e, - OIOException.class); + OLogManager.instance().error( + this, + ""Error on write in the range "" + iOffset + ""-"" + iOffset + + iSourceBuffer.length + ""."" + toString(), e, + OIOException.class); } } @@ -131,7 +143,7 @@ public void changeSize(final int iSize) { } /** - * Do nothing. Use OFileSecure to be sure the file is saved + * Synchronize buffered changes to the file. * * @see OFileMMapSecure */ @@ -160,7 +172,8 @@ protected void readHeader() { // check.append('R'); // check.append('<'); // - // OIntegrityFileManager.instance().check(check.toString(), securityCode); + // OIntegrityFileManager.instance().check(check.toString(), + // securityCode); } @Override @@ -181,11 +194,22 @@ protected void writeHeader() { // check.append('R'); // check.append('<'); // - // securityCode = OIntegrityFileManager.instance().digest(check.toString()); + // securityCode = + // OIntegrityFileManager.instance().digest(check.toString()); // for (int i = 0; i < securityCode.length; ++i) // buffer.put(securityCode[i]); } + @Override + public void writeHeaderLong(final int iPosition, final long iValue) { + headerBuffer.putLong(HEADER_DATA_OFFSET + iPosition, iValue); + } + + @Override + public long readHeaderLong(final int iPosition) { + return headerBuffer.getLong(HEADER_DATA_OFFSET + iPosition); + } + @Override public void close() throws IOException { if (headerBuffer != null) { @@ -210,14 +234,18 @@ protected void setSoftlyClosed(final boolean iValue) { synch(); } - MappedByteBuffer map(final int iBeginOffset, final int iSize) throws IOException { - return channel.map(mode.equals(""r"") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, iBeginOffset - + HEADER_SIZE, iSize); + MappedByteBuffer map(final int iBeginOffset, final int iSize) + throws IOException { + return channel.map(mode.equals(""r"") ? FileChannel.MapMode.READ_ONLY + : FileChannel.MapMode.READ_WRITE, iBeginOffset + HEADER_SIZE, + iSize); } @Override protected void openChannel(final int iNewSize) throws IOException { super.openChannel(iNewSize); - headerBuffer = channel.map(mode.equals(""r"") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, 0, HEADER_SIZE); + headerBuffer = channel.map( + mode.equals(""r"") ? FileChannel.MapMode.READ_ONLY + : FileChannel.MapMode.READ_WRITE, 0, HEADER_SIZE); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java index b2cd4216694..d8df65005fa 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java @@ -30,260 +30,342 @@ *
    * Record structure:
    *
    - * +----------------------+----------------------+-------------+----------------------+
    + * +----------------------+----------------------+-------------+---------------- ------+
    * | DATA SEGMENT........ | DATA OFFSET......... | RECORD TYPE | VERSION............. |
    * | 2 bytes = max 2^15-1 | 8 bytes = max 2^63-1 | 1 byte..... | 4 bytes = max 2^31-1 |
    - * +----------------------+----------------------+-------------+----------------------+
    + * +----------------------+----------------------+-------------+---------------- ------+
    * = 15 bytes
    */ public class OClusterLocal extends OMultiFileSegment implements OCluster { - private static final String DEF_EXTENSION = "".ocl""; - private static final int RECORD_SIZE = 15; - private static final int DEF_SIZE = 1000000; - public static final String TYPE = ""PHYSICAL""; + private static final String DEF_EXTENSION = "".ocl""; + private static final int RECORD_SIZE = 15; + private static final int DEF_SIZE = 1000000; + public static final String TYPE = ""PHYSICAL""; - private int id; + private int id; + private long beginOffsetData = -1; + private long endOffsetData = -1; // end of data offset. -1 = latest - protected final OClusterLocalHole holeSegment; + protected final OClusterLocalHole holeSegment; - public OClusterLocal(final OStorageLocal iStorage, final OStoragePhysicalClusterConfiguration iConfig) throws IOException { - super(iStorage, iConfig, DEF_EXTENSION, RECORD_SIZE); - id = iConfig.getId(); + public OClusterLocal(final OStorageLocal iStorage, final OStoragePhysicalClusterConfiguration iConfig) throws IOException { + super(iStorage, iConfig, DEF_EXTENSION, RECORD_SIZE); + id = iConfig.getId(); - iConfig.holeFile = new OStorageClusterHoleConfiguration(iConfig, OStorageVariableParser.DB_PATH_VARIABLE + ""/"" + iConfig.name, - iConfig.fileType, iConfig.fileMaxSize); + iConfig.holeFile = new OStorageClusterHoleConfiguration(iConfig, OStorageVariableParser.DB_PATH_VARIABLE + ""/"" + iConfig.name, + iConfig.fileType, iConfig.fileMaxSize); - holeSegment = new OClusterLocalHole(this, iStorage, iConfig.holeFile); - } + holeSegment = new OClusterLocalHole(this, iStorage, iConfig.holeFile); + } - @Override - public void create(int iStartSize) throws IOException { - if (iStartSize == -1) - iStartSize = DEF_SIZE; + @Override + public void create(int iStartSize) throws IOException { + if (iStartSize == -1) + iStartSize = DEF_SIZE; - super.create(iStartSize); - holeSegment.create(); - } + super.create(iStartSize); + holeSegment.create(); - @Override - public void open() throws IOException { - try { - acquireExclusiveLock(); + files[0].writeHeaderLong(0, beginOffsetData); + files[0].writeHeaderLong(OConstants.SIZE_LONG, beginOffsetData); - super.open(); - holeSegment.open(); + } - } finally { + @Override + public void open() throws IOException { + try { + acquireExclusiveLock(); - releaseExclusiveLock(); - } - } + super.open(); + holeSegment.open(); - @Override - public void close() throws IOException { - super.close(); - holeSegment.close(); - } + beginOffsetData = files[0].readHeaderLong(0); + endOffsetData = files[0].readHeaderLong(OConstants.SIZE_LONG); - public void delete() throws IOException { - super.delete(); - holeSegment.delete(); - } + } finally { - /** - * Fill and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition - * - * @throws IOException - */ - public OPhysicalPosition getPhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { - iPosition = iPosition * RECORD_SIZE; + releaseExclusiveLock(); + } + } - try { - acquireSharedLock(); + @Override + public void close() throws IOException { + super.close(); + holeSegment.close(); + } - int[] pos = getRelativePosition(iPosition); + public void delete() throws IOException { + super.delete(); + holeSegment.delete(); + } - int p = pos[1]; + /** + * Fill and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition + * + * @throws IOException + */ + public OPhysicalPosition getPhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { + iPosition = iPosition * RECORD_SIZE; - iPPosition.dataSegment = files[pos[0]].readShort(p); - iPPosition.dataPosition = files[pos[0]].readLong(p += OConstants.SIZE_SHORT); - iPPosition.type = files[pos[0]].readByte(p += OConstants.SIZE_LONG); - iPPosition.version = files[pos[0]].readInt(p += OConstants.SIZE_BYTE); - return iPPosition; + try { + acquireSharedLock(); - } finally { - releaseSharedLock(); - } - } + int[] pos = getRelativePosition(iPosition); - /** - * Change the PhysicalPosition of the logical record iPosition. - * - * @throws IOException - */ - public void setPhysicalPosition(long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) - throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); + int p = pos[1]; - int[] pos = getRelativePosition(iPosition); - - int p = pos[1]; - - files[pos[0]].writeShort(p, (short) iDataId); - files[pos[0]].writeLong(p += OConstants.SIZE_SHORT, iDataPosition); - files[pos[0]].writeByte(p += OConstants.SIZE_LONG, iRecordType); + iPPosition.dataSegment = files[pos[0]].readShort(p); + iPPosition.dataPosition = files[pos[0]].readLong(p += OConstants.SIZE_SHORT); + iPPosition.type = files[pos[0]].readByte(p += OConstants.SIZE_LONG); + iPPosition.version = files[pos[0]].readInt(p += OConstants.SIZE_BYTE); + return iPPosition; - } finally { - releaseExclusiveLock(); - } - } + } finally { + releaseSharedLock(); + } + } - public void updateVersion(long iPosition, final int iVersion) throws IOException { - iPosition = iPosition * RECORD_SIZE; + /** + * Change the PhysicalPosition of the logical record iPosition. + * + * @throws IOException + */ + public void setPhysicalPosition(long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) + throws IOException { + iPosition = iPosition * RECORD_SIZE; - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - - files[pos[0]].writeInt(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG + OConstants.SIZE_BYTE, iVersion); - - } finally { - releaseExclusiveLock(); - } - } - - public void updateRecordType(long iPosition, final byte iRecordType) throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - - files[pos[0]].writeByte(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG, iRecordType); - - } finally { - releaseExclusiveLock(); - } - } - - /** - * Remove the Logical position entry. Add to the hole segment and change the version to -1. - * - * @throws IOException - */ - public void removePhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - OFile file = files[pos[0]]; - int p = pos[1]; - - // SAVE THE OLD DATA AND RETRIEVE THEM TO THE CALLER - iPPosition.dataSegment = file.readShort(p); - iPPosition.dataPosition = file.readLong(p += OConstants.SIZE_SHORT); - iPPosition.type = file.readByte(p += OConstants.SIZE_LONG); - iPPosition.version = file.readInt(p += OConstants.SIZE_BYTE); - - holeSegment.pushPosition(iPosition); - - file.writeInt(p, -1); - } finally { - releaseExclusiveLock(); - } - } + try { + acquireExclusiveLock(); - public boolean removeHole(long iPosition) throws IOException { - return holeSegment.removeEntryWithPosition(iPosition); - } - - /** - * Add a new entry. - * - * @throws IOException - */ - public long addPhysicalPosition(final int iDataSegmentId, final long iPosition, final byte iRecordType) throws IOException { - try { - acquireExclusiveLock(); - - long offset = holeSegment.popLastEntryPosition(); - - final int[] pos; - if (offset > -1) - // REUSE THE HOLE - pos = getRelativePosition(offset); - else { - // NO HOLES FOUND: ALLOCATE MORE SPACE - pos = allocateSpace(RECORD_SIZE); - offset = getAbsolutePosition(pos); - } + int[] pos = getRelativePosition(iPosition); - OFile file = files[pos[0]]; - int p = pos[1]; + int p = pos[1]; - file.writeShort(p, (short) iDataSegmentId); - file.writeLong(p += OConstants.SIZE_SHORT, iPosition); - file.writeByte(p += OConstants.SIZE_LONG, iRecordType); - file.writeInt(p += OConstants.SIZE_BYTE, 0); - - return offset / RECORD_SIZE; - - } finally { - releaseExclusiveLock(); - } - } + files[pos[0]].writeShort(p, (short) iDataId); + files[pos[0]].writeLong(p += OConstants.SIZE_SHORT, iDataPosition); + files[pos[0]].writeByte(p += OConstants.SIZE_LONG, iRecordType); - public long getLastEntryPosition() throws IOException { - try { - acquireSharedLock(); + } finally { + releaseExclusiveLock(); + } + } - return getFilledUpTo() / RECORD_SIZE - 1; - - } finally { - releaseSharedLock(); - } - } - - public long getEntries() { - try { - acquireSharedLock(); - - return getFilledUpTo() / RECORD_SIZE - holeSegment.getHoles(); - - } finally { - releaseSharedLock(); - } - } - - public int getId() { - return id; - } - - public OClusterPositionIterator absoluteIterator() throws IOException { - return new OClusterPositionIterator(this); - } - - @Override - public String toString() { - return name + "" (id="" + id + "")""; - } - - public void lock() { - acquireSharedLock(); - } - - public void unlock() { - releaseSharedLock(); - } - - public String getType() { - return TYPE; - } + public void updateVersion(long iPosition, final int iVersion) throws IOException { + iPosition = iPosition * RECORD_SIZE; + + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(iPosition); + + files[pos[0]].writeInt(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG + OConstants.SIZE_BYTE, iVersion); + + } finally { + releaseExclusiveLock(); + } + } + + public void updateRecordType(long iPosition, final byte iRecordType) throws IOException { + iPosition = iPosition * RECORD_SIZE; + + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(iPosition); + + files[pos[0]].writeByte(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG, iRecordType); + + } finally { + releaseExclusiveLock(); + } + } + + /** + * Remove the Logical position entry. Add to the hole segment and change the version to -1. + * + * @throws IOException + */ + public void removePhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { + final long position = iPosition * RECORD_SIZE; + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(position); + OFile file = files[pos[0]]; + int p = pos[1]; + + // SAVE THE OLD DATA AND RETRIEVE THEM TO THE CALLER + iPPosition.dataSegment = file.readShort(p); + iPPosition.dataPosition = file.readLong(p += OConstants.SIZE_SHORT); + iPPosition.type = file.readByte(p += OConstants.SIZE_LONG); + iPPosition.version = file.readInt(p += OConstants.SIZE_BYTE); + + holeSegment.pushPosition(position); + + // SET VERSION = -1 + file.writeInt(p, -1); + + if (iPosition == beginOffsetData) { + if (getEntries() == 0) + beginOffsetData = -1; + else { + // DISCOVER THE BEGIN OF DATA + beginOffsetData++; + + int[] fetchPos; + for (long currentPos = position + RECORD_SIZE; currentPos < getFilledUpTo(); currentPos += RECORD_SIZE) { + fetchPos = getRelativePosition(currentPos); + + if (files[fetchPos[0]].readShort(fetchPos[1]) != -1) + // GOOD RECORD: SET IT AS BEGIN + break; + + beginOffsetData++; + } + } + + files[0].writeHeaderLong(0, beginOffsetData); + } + + if (iPosition == endOffsetData) { + if (getEntries() == 0) + endOffsetData = -1; + else { + // DISCOVER THE END OF DATA + endOffsetData--; + + int[] fetchPos; + for (long currentPos = position - RECORD_SIZE; currentPos >= beginOffsetData; currentPos -= RECORD_SIZE) { + + fetchPos = getRelativePosition(currentPos); + + if (files[fetchPos[0]].readShort(fetchPos[1]) != -1) + // GOOD RECORD: SET IT AS BEGIN + break; + endOffsetData--; + } + } + + files[0].writeHeaderLong(OConstants.SIZE_LONG, endOffsetData); + } + + } finally { + releaseExclusiveLock(); + } + } + + public boolean removeHole(long iPosition) throws IOException { + return holeSegment.removeEntryWithPosition(iPosition); + } + + /** + * Add a new entry. + * + * @throws IOException + */ + public long addPhysicalPosition(final int iDataSegmentId, final long iPosition, final byte iRecordType) throws IOException { + try { + acquireExclusiveLock(); + + long offset = holeSegment.popLastEntryPosition(); + + final int[] pos; + if (offset > -1) + // REUSE THE HOLE + pos = getRelativePosition(offset); + else { + // NO HOLES FOUND: ALLOCATE MORE SPACE + pos = allocateSpace(RECORD_SIZE); + offset = getAbsolutePosition(pos); + } + + OFile file = files[pos[0]]; + int p = pos[1]; + + file.writeShort(p, (short) iDataSegmentId); + file.writeLong(p += OConstants.SIZE_SHORT, iPosition); + file.writeByte(p += OConstants.SIZE_LONG, iRecordType); + file.writeInt(p += OConstants.SIZE_BYTE, 0); + + final long returnedPosition = offset / RECORD_SIZE; + + if (returnedPosition < beginOffsetData || beginOffsetData == -1) { + // UPDATE END OF DATA + beginOffsetData = returnedPosition; + files[0].writeHeaderLong(0, beginOffsetData); + } + + if (endOffsetData > -1 && returnedPosition > endOffsetData) { + // UPDATE END OF DATA + endOffsetData = returnedPosition; + files[0].writeHeaderLong(OConstants.SIZE_LONG, endOffsetData); + } + + return returnedPosition; + + } finally { + releaseExclusiveLock(); + } + } + + public long getFirstEntryPosition() throws IOException { + try { + acquireSharedLock(); + + return beginOffsetData; + + } finally { + releaseSharedLock(); + } + } + + /** + * Returns the endOffsetData value if it's not equals to the last one, otherwise the total entries. + */ + public long getLastEntryPosition() throws IOException { + try { + acquireSharedLock(); + + return endOffsetData > -1 ? endOffsetData : getFilledUpTo() / RECORD_SIZE - 1; + + } finally { + releaseSharedLock(); + } + } + + public long getEntries() { + try { + acquireSharedLock(); + + return getFilledUpTo() / RECORD_SIZE - holeSegment.getHoles(); + + } finally { + releaseSharedLock(); + } + } + + public int getId() { + return id; + } + + public OClusterPositionIterator absoluteIterator() throws IOException { + return new OClusterPositionIterator(this); + } + + @Override + public String toString() { + return name + "" (id="" + id + "")""; + } + + public void lock() { + acquireSharedLock(); + } + + public void unlock() { + releaseSharedLock(); + } + + public String getType() { + return TYPE; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java index bd02ee333b2..5e56ddcd0de 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java @@ -21,7 +21,8 @@ import com.orientechnologies.orient.core.config.OStorageFileConfiguration; /** - * Handle the holes inside cluster segments. The synchronization is in charge to the OClusterLocal instance.
    + * Handle the holes inside cluster segments. The synchronization is in charge to + * the OClusterLocal instance.
    *
    * Record structure:
    *
    @@ -32,13 +33,14 @@ * = 8 bytes
    */ public class OClusterLocalHole extends OSingleFileSegment { - private static final int DEF_START_SIZE = 262144; - private static final int RECORD_SIZE = 8; + private static final int DEF_START_SIZE = 262144; + private static final int RECORD_SIZE = 8; - private OClusterLocal owner; + private OClusterLocal owner; - public OClusterLocalHole(final OClusterLocal iClusterLocal, final OStorageLocal iStorage, final OStorageFileConfiguration iConfig) - throws IOException { + public OClusterLocalHole(final OClusterLocal iClusterLocal, + final OStorageLocal iStorage, + final OStorageFileConfiguration iConfig) throws IOException { super(iStorage, iConfig); owner = iClusterLocal; } @@ -47,11 +49,17 @@ public OClusterLocalHole(final OClusterLocal iClusterLocal, final OStorageLocal * TODO Check values removing dirty entries (equals to -1) */ public void defrag() throws IOException { - OLogManager.instance().debug(this, ""Starting to defragment the segment %s of size=%d and filled=%d"", file, file.getFileSize(), - file.getFilledUpTo()); - - OLogManager.instance().debug(this, ""Defragmentation ended for segment %s. Current size=%d and filled=%d"", file, - file.getFileSize(), file.getFilledUpTo()); + OLogManager + .instance() + .debug(this, + ""Starting to defragment the segment %s of size=%d and filled=%d"", + file, file.getFileSize(), file.getFilledUpTo()); + + OLogManager + .instance() + .debug(this, + ""Defragmentation ended for segment %s. Current size=%d and filled=%d"", + file, file.getFileSize(), file.getFilledUpTo()); } public void create() throws IOException { @@ -70,8 +78,9 @@ public long pushPosition(final long iPosition) throws IOException { file.writeLong(position, iPosition); if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, ""Pushed new hole at #%d containing the position #%d:%d"", position / RECORD_SIZE, - owner.getId(), iPosition); + OLogManager.instance().debug(this, + ""Pushed new hole at #%d containing the position #%d:%d"", + position / RECORD_SIZE, owner.getId(), iPosition); return position; } @@ -79,7 +88,8 @@ public long pushPosition(final long iPosition) throws IOException { /** * Return the recycled position if any. * - * @return the recycled position if found, otherwise -1 that usually means to request more space. + * @return the recycled position if found, otherwise -1 that usually means + * to request more space. * @throws IOException */ public long popLastEntryPosition() throws IOException { @@ -89,8 +99,11 @@ public long popLastEntryPosition() throws IOException { if (recycledPosition > -1) { if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, ""Recycling hole #%d containing the position #%d:%d"", pos, owner.getId(), - recycledPosition); + OLogManager + .instance() + .debug(this, + ""Recycling hole #%d containing the position #%d:%d"", + pos, owner.getId(), recycledPosition); // SHRINK THE FILE file.removeTail((getHoles() - pos) * RECORD_SIZE); @@ -103,11 +116,12 @@ public long popLastEntryPosition() throws IOException { } /** - * Remove a hole. Called on transaction recover to invalidate a delete for a record. Try to shrink the file if the invalidated - * entry is not in the middle of valid entries. + * Remove a hole. Called on transaction recover to invalidate a delete for a + * record. Try to shrink the file if the invalidated entry is not in the + * middle of valid entries. * * @param iPosition - * Record position to find and invalidate + * Record position to find and invalidate * @return * @throws IOException */ @@ -119,8 +133,9 @@ public boolean removeEntryWithPosition(long iPosition) throws IOException { if (recycledPosition == iPosition) { if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, ""Removing hole #%d containing the position #%d:%d"", pos, owner.getId(), - recycledPosition); + OLogManager.instance().debug(this, + ""Removing hole #%d containing the position #%d:%d"", + pos, owner.getId(), recycledPosition); file.writeLong(pos * RECORD_SIZE, -1); if (canShrink) diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java index 2962939dc1e..d83295720ac 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java @@ -194,6 +194,10 @@ public long getEntries() { return map.size() - 1; } + public long getFirstEntryPosition() { + return 0; + } + public long getLastEntryPosition() { return total.dataPosition; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java index dcc57c1bd4c..3db5f7a5c73 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java @@ -59,1007 +59,1019 @@ import com.orientechnologies.orient.core.tx.OTransaction; public class OStorageLocal extends OStorageAbstract { - public static final String[] TYPES = { OClusterLocal.TYPE, OClusterLogical.TYPE }; + public static final String[] TYPES = { OClusterLocal.TYPE, OClusterLogical.TYPE }; + + // private final OLockManager lockManager = new + // OLockManager(); + protected final Map clusterMap = new LinkedHashMap(); + protected OCluster[] clusters = new OCluster[0]; + protected ODataLocal[] dataSegments = new ODataLocal[0]; + + private OStorageLocalTxExecuter txManager; + private String storagePath; + private OStorageVariableParser variableParser; + private int defaultClusterId = -1; + + public OStorageLocal(final String iName, final String iFilePath, final String iMode) throws IOException { + super(iName, iFilePath, iMode); + + storagePath = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getParent())); + + configuration = new OStorageConfiguration(this); + variableParser = new OStorageVariableParser(storagePath); + txManager = new OStorageLocalTxExecuter(this, configuration.txSegment); + } + + public synchronized void open(final int iRequesterId, final String iUserName, final String iUserPassword) { + final long timer = OProfiler.getInstance().startChrono(); + + addUser(); + cache.addUser(); + + final boolean locked = acquireExclusiveLock(); + + try { + if (open) + // ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS + // REUSED + return; - // private final OLockManager lockManager = new OLockManager(); - protected final Map clusterMap = new LinkedHashMap(); - protected OCluster[] clusters = new OCluster[0]; - protected ODataLocal[] dataSegments = new ODataLocal[0]; - - private OStorageLocalTxExecuter txManager; - private String storagePath; - private OStorageVariableParser variableParser; - private int defaultClusterId = -1; - - public OStorageLocal(final String iName, final String iFilePath, final String iMode) throws IOException { - super(iName, iFilePath, iMode); + if (!exists()) + throw new OStorageException(""Can't open the storage "" + name + "" because it not exists""); - storagePath = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getParent())); - - configuration = new OStorageConfiguration(this); - variableParser = new OStorageVariableParser(storagePath); - txManager = new OStorageLocalTxExecuter(this, configuration.txSegment); - } + open = true; - public synchronized void open(final int iRequesterId, final String iUserName, final String iUserPassword) { - final long timer = OProfiler.getInstance().startChrono(); + // OPEN BASIC SEGMENTS + int pos; + pos = registerDataSegment(new OStorageDataConfiguration(configuration, OStorage.DATA_DEFAULT_NAME)); + dataSegments[pos].open(); - addUser(); - cache.addUser(); + pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INTERNAL_NAME, + clusters.length)); + clusters[pos].open(); - final boolean locked = acquireExclusiveLock(); + pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INDEX_NAME, + clusters.length)); + clusters[pos].open(); - try { - if (open) - // ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS REUSED - return; + defaultClusterId = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, + OStorage.CLUSTER_DEFAULT_NAME, clusters.length)); + clusters[defaultClusterId].open(); - if (!exists()) - throw new OStorageException(""Can't open the storage "" + name + "" because it not exists""); + configuration.load(); - open = true; + if (configuration.isEmpty()) + throw new OStorageException(""Can't open storage because it not exists. Storage path: "" + url); - // OPEN BASIC SEGMENTS - int pos; - pos = registerDataSegment(new OStorageDataConfiguration(configuration, OStorage.DATA_DEFAULT_NAME)); - dataSegments[pos].open(); + // REGISTER DATA SEGMENT + OStorageDataConfiguration dataConfig; + for (int i = 0; i < configuration.dataSegments.size(); ++i) { + dataConfig = configuration.dataSegments.get(i); - pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INTERNAL_NAME, - clusters.length)); - clusters[pos].open(); + pos = registerDataSegment(dataConfig); + if (pos == -1) { + // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE + // OPENED + dataSegments[i].close(); + dataSegments[i] = new ODataLocal(this, dataConfig, pos); + dataSegments[i].open(); + } else + dataSegments[pos].open(); + } - pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INDEX_NAME, - clusters.length)); - clusters[pos].open(); + // REGISTER CLUSTER + OStorageClusterConfiguration clusterConfig; + for (int i = 0; i < configuration.clusters.size(); ++i) { + clusterConfig = configuration.clusters.get(i); - defaultClusterId = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, - OStorage.CLUSTER_DEFAULT_NAME, clusters.length)); - clusters[defaultClusterId].open(); + pos = createClusterFromConfig(clusterConfig); - configuration.load(); + if (pos == -1) { + // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE + // OPENED + clusters[i].close(); + clusters[i] = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) clusterConfig); + clusters[i].open(); + } else { + if (clusterConfig.getName().equals(OStorage.CLUSTER_DEFAULT_NAME)) + defaultClusterId = pos; - if (configuration.isEmpty()) - throw new OStorageException(""Can't open storage because it not exists. Storage path: "" + url); + clusters[pos].open(); + } + } - // REGISTER DATA SEGMENT - OStorageDataConfiguration dataConfig; - for (int i = 0; i < configuration.dataSegments.size(); ++i) { - dataConfig = configuration.dataSegments.get(i); + txManager.open(); - pos = registerDataSegment(dataConfig); - if (pos == -1) { - // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE OPENED - dataSegments[i].close(); - dataSegments[i] = new ODataLocal(this, dataConfig, pos); - dataSegments[i].open(); - } else - dataSegments[pos].open(); - } + } catch (IOException e) { + open = false; + dataSegments = new ODataLocal[0]; + clusters = new OCluster[0]; + clusterMap.clear(); + throw new OStorageException(""Can't open local storage: "" + url + "", with mode="" + mode, e); + } finally { + releaseExclusiveLock(locked); - // REGISTER CLUSTER - OStorageClusterConfiguration clusterConfig; - for (int i = 0; i < configuration.clusters.size(); ++i) { - clusterConfig = configuration.clusters.get(i); + OProfiler.getInstance().stopChrono(""OStorageLocal.open"", timer); + } + } - pos = createClusterFromConfig(clusterConfig); + public void create() { + final long timer = OProfiler.getInstance().startChrono(); - if (pos == -1) { - // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE OPENED - clusters[i].close(); - clusters[i] = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) clusterConfig); - clusters[i].open(); - } else { - if (clusterConfig.getName().equals(OStorage.CLUSTER_DEFAULT_NAME)) - defaultClusterId = pos; + addUser(); + cache.addUser(); - clusters[pos].open(); - } - } + final boolean locked = acquireExclusiveLock(); - txManager.open(); + try { + File storageFolder = new File(storagePath); + if (!storageFolder.exists()) + storageFolder.mkdir(); - } catch (IOException e) { - open = false; - dataSegments = new ODataLocal[0]; - clusters = new OCluster[0]; - clusterMap.clear(); - throw new OStorageException(""Can't open local storage: "" + url + "", with mode="" + mode, e); - } finally { - releaseExclusiveLock(locked); + if (exists()) + throw new OStorageException(""Can't create new storage "" + name + "" because it already exists""); - OProfiler.getInstance().stopChrono(""OStorageLocal.open"", timer); - } - } + open = true; - public void create() { - final long timer = OProfiler.getInstance().startChrono(); + addDataSegment(OStorage.DATA_DEFAULT_NAME); - addUser(); - cache.addUser(); + // ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF + addCluster(OStorage.CLUSTER_INTERNAL_NAME, OClusterLocal.TYPE); - final boolean locked = acquireExclusiveLock(); + // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF + // INDEXING + addCluster(OStorage.CLUSTER_INDEX_NAME, OClusterLocal.TYPE); - try { - File storageFolder = new File(storagePath); - if (!storageFolder.exists()) - storageFolder.mkdir(); + // ADD THE DEFAULT CLUSTER + defaultClusterId = addCluster(OStorage.CLUSTER_DEFAULT_NAME, OClusterLocal.TYPE); - if (exists()) - throw new OStorageException(""Can't create new storage "" + name + "" because it already exists""); + configuration.create(); - open = true; + txManager.create(); + } catch (OStorageException e) { + close(); + throw e; + } catch (IOException e) { + close(); + throw new OStorageException(""Error on creation of storage: "" + name, e); - addDataSegment(OStorage.DATA_DEFAULT_NAME); + } finally { + releaseExclusiveLock(locked); - // ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF - addCluster(OStorage.CLUSTER_INTERNAL_NAME, OClusterLocal.TYPE); + OProfiler.getInstance().stopChrono(""OStorageLocal.create"", timer); + } + } - // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF INDEXING - addCluster(OStorage.CLUSTER_INDEX_NAME, OClusterLocal.TYPE); + public boolean exists() { + return new File(storagePath + ""/"" + OStorage.DATA_DEFAULT_NAME + "".0"" + ODataLocal.DEF_EXTENSION).exists(); + } - // ADD THE DEFAULT CLUSTER - defaultClusterId = addCluster(OStorage.CLUSTER_DEFAULT_NAME, OClusterLocal.TYPE); + public void close() { + final long timer = OProfiler.getInstance().startChrono(); - configuration.create(); + final boolean locked = acquireExclusiveLock(); - txManager.create(); - } catch (OStorageException e) { - close(); - throw e; - } catch (IOException e) { - close(); - throw new OStorageException(""Error on creation of storage: "" + name, e); + if (!open) + return; - } finally { - releaseExclusiveLock(locked); + try { + for (OCluster cluster : clusters) + if (cluster != null) + cluster.close(); + clusters = new OCluster[0]; + clusterMap.clear(); - OProfiler.getInstance().stopChrono(""OStorageLocal.create"", timer); - } - } + for (ODataLocal data : dataSegments) + data.close(); + dataSegments = new ODataLocal[0]; - public boolean exists() { - return new File(storagePath + ""/"" + OStorage.DATA_DEFAULT_NAME + "".0"" + ODataLocal.DEF_EXTENSION).exists(); - } + txManager.close(); - public void close() { - final long timer = OProfiler.getInstance().startChrono(); + cache.removeUser(); + cache.clear(); + configuration = new OStorageConfiguration(this); - final boolean locked = acquireExclusiveLock(); + open = false; + } catch (IOException e) { + OLogManager.instance().error(this, ""Error on closing of the storage '"" + name, e, OStorageException.class); - if (!open) - return; + } finally { + releaseExclusiveLock(locked); - try { - for (OCluster cluster : clusters) - if (cluster != null) - cluster.close(); - clusters = new OCluster[0]; - clusterMap.clear(); + OProfiler.getInstance().stopChrono(""OStorageLocal.close"", timer); + } + } - for (ODataLocal data : dataSegments) - data.close(); - dataSegments = new ODataLocal[0]; + public ODataLocal getDataSegment(final int iDataSegmentId) { + checkOpeness(); + if (iDataSegmentId >= dataSegments.length) + throw new IllegalArgumentException(""Data segment #"" + iDataSegmentId + "" doesn't exist in current storage""); - txManager.close(); + final boolean locked = acquireSharedLock(); - cache.removeUser(); - cache.clear(); - configuration = new OStorageConfiguration(this); + try { + return dataSegments[iDataSegmentId]; - open = false; - } catch (IOException e) { - OLogManager.instance().error(this, ""Error on closing of the storage '"" + name, e, OStorageException.class); + } finally { + releaseSharedLock(locked); + } + } - } finally { - releaseExclusiveLock(locked); + /** + * Add a new data segment in the default segment directory and with filename equals to the cluster name. + */ + public int addDataSegment(final String iDataSegmentName) { + String segmentFileName = storagePath + ""/"" + iDataSegmentName; + return addDataSegment(iDataSegmentName, segmentFileName); + } - OProfiler.getInstance().stopChrono(""OStorageLocal.close"", timer); - } - } + public int addDataSegment(String iSegmentName, final String iSegmentFileName) { + checkOpeness(); - public ODataLocal getDataSegment(final int iDataSegmentId) { - checkOpeness(); - if (iDataSegmentId >= dataSegments.length) - throw new IllegalArgumentException(""Data segment #"" + iDataSegmentId + "" doesn't exist in current storage""); + iSegmentName = iSegmentName.toLowerCase(); - final boolean locked = acquireSharedLock(); + final boolean locked = acquireExclusiveLock(); - try { - return dataSegments[iDataSegmentId]; + try { + OStorageDataConfiguration conf = new OStorageDataConfiguration(configuration, iSegmentName); + configuration.dataSegments.add(conf); - } finally { - releaseSharedLock(locked); - } - } + final int pos = registerDataSegment(conf); - /** - * Add a new data segment in the default segment directory and with filename equals to the cluster name. - */ - public int addDataSegment(final String iDataSegmentName) { - String segmentFileName = storagePath + ""/"" + iDataSegmentName; - return addDataSegment(iDataSegmentName, segmentFileName); - } + if (pos == -1) + throw new OConfigurationException(""Can't add segment "" + conf.name + "" because it's already part of current storage""); - public int addDataSegment(String iSegmentName, final String iSegmentFileName) { - checkOpeness(); + dataSegments[pos].create(-1); + configuration.update(); - iSegmentName = iSegmentName.toLowerCase(); + return pos; + } catch (Throwable e) { + OLogManager.instance().error(this, ""Error on creation of new data segment '"" + iSegmentName + ""' in: "" + iSegmentFileName, e, + OStorageException.class); + return -1; - final boolean locked = acquireExclusiveLock(); + } finally { + releaseExclusiveLock(locked); + } + } - try { - OStorageDataConfiguration conf = new OStorageDataConfiguration(configuration, iSegmentName); - configuration.dataSegments.add(conf); + /** + * Add a new cluster into the storage. Type can be: ""physical"" or ""logical"". + */ + public int addCluster(String iClusterName, final String iClusterType, final Object... iParameters) { + checkOpeness(); - final int pos = registerDataSegment(conf); + final boolean locked = acquireExclusiveLock(); - if (pos == -1) - throw new OConfigurationException(""Can't add segment "" + conf.name + "" because it's already part of current storage""); + try { + iClusterName = iClusterName.toLowerCase(); - dataSegments[pos].create(-1); - configuration.update(); + if (OClusterLocal.TYPE.equalsIgnoreCase(iClusterType)) { + // GET PARAMETERS + final String clusterFileName = (String) (iParameters.length < 1 ? storagePath + ""/"" + iClusterName : iParameters[0]); + final int startSize = (iParameters.length < 2 ? -1 : (Integer) iParameters[1]); - return pos; - } catch (Throwable e) { - OLogManager.instance().error(this, ""Error on creation of new data segment '"" + iSegmentName + ""' in: "" + iSegmentFileName, e, - OStorageException.class); - return -1; + return addPhysicalCluster(iClusterName, clusterFileName, startSize); + } else if (OClusterLogical.TYPE.equalsIgnoreCase(iClusterType)) { + // GET PARAMETERS + final int physicalClusterId = (iParameters.length < 1 ? getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME) + : (Integer) iParameters[0]); - } finally { - releaseExclusiveLock(locked); - } - } + return addLogicalCluster(iClusterName, physicalClusterId); + } else + OLogManager.instance().exception( + ""Cluster type '"" + iClusterType + ""' is not supported. Supported types are: "" + Arrays.toString(TYPES), null, + OStorageException.class); - /** - * Add a new cluster into the storage. Type can be: ""physical"" or ""logical"". - */ - public int addCluster(String iClusterName, final String iClusterType, final Object... iParameters) { - checkOpeness(); + } catch (Exception e) { + OLogManager.instance().exception(""Error in creation of new cluster '"" + iClusterName + ""' of type: "" + iClusterType, e, + OStorageException.class); - final boolean locked = acquireExclusiveLock(); + } finally { - try { - iClusterName = iClusterName.toLowerCase(); + releaseExclusiveLock(locked); + } + return -1; + } - if (OClusterLocal.TYPE.equalsIgnoreCase(iClusterType)) { - // GET PARAMETERS - final String clusterFileName = (String) (iParameters.length < 1 ? storagePath + ""/"" + iClusterName : iParameters[0]); - final int startSize = (iParameters.length < 2 ? -1 : (Integer) iParameters[1]); + public boolean removeCluster(final int iClusterId) { + final boolean locked = acquireExclusiveLock(); - return addPhysicalCluster(iClusterName, clusterFileName, startSize); - } else if (OClusterLogical.TYPE.equalsIgnoreCase(iClusterType)) { - // GET PARAMETERS - final int physicalClusterId = (iParameters.length < 1 ? getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME) - : (Integer) iParameters[0]); + try { + if (iClusterId < 0 || iClusterId >= clusters.length) + throw new IllegalArgumentException(""Cluster id '"" + iClusterId + ""' is out of range of configured clusters (0-"" + + (clusters.length - 1) + "")""); - return addLogicalCluster(iClusterName, physicalClusterId); - } else - OLogManager.instance().exception( - ""Cluster type '"" + iClusterType + ""' is not supported. Supported types are: "" + Arrays.toString(TYPES), null, - OStorageException.class); + final OCluster cluster = clusters[iClusterId]; + if (cluster == null) + return false; - } catch (Exception e) { - OLogManager.instance().exception(""Error in creation of new cluster '"" + iClusterName + ""' of type: "" + iClusterType, e, - OStorageException.class); + cluster.delete(); - } finally { + clusterMap.remove(cluster.getName()); + clusters[iClusterId] = null; - releaseExclusiveLock(locked); - } - return -1; - } + // UPDATE CONFIGURATION + configuration.clusters.set(iClusterId, null); + configuration.update(); - public boolean removeCluster(final int iClusterId) { - final boolean locked = acquireExclusiveLock(); + return true; + } catch (Exception e) { + OLogManager.instance().exception(""Error while removing cluster '"" + iClusterId + ""'"", e, OStorageException.class); - try { - if (iClusterId < 0 || iClusterId >= clusters.length) - throw new IllegalArgumentException(""Cluster id '"" + iClusterId + ""' is out of range of configured clusters (0-"" - + (clusters.length - 1) + "")""); + } finally { + releaseExclusiveLock(locked); + } - final OCluster cluster = clusters[iClusterId]; - if (cluster == null) - return false; + return false; + } - cluster.delete(); + public long count(final int[] iClusterIds) { + checkOpeness(); - clusterMap.remove(cluster.getName()); - clusters[iClusterId] = null; + final long timer = OProfiler.getInstance().startChrono(); - // UPDATE CONFIGURATION - configuration.clusters.set(iClusterId, null); - configuration.update(); + final boolean locked = acquireSharedLock(); - return true; - } catch (Exception e) { - OLogManager.instance().exception(""Error while removing cluster '"" + iClusterId + ""'"", e, OStorageException.class); + try { + long tot = 0; - } finally { - releaseExclusiveLock(locked); - } + OCluster c; + for (int i = 0; i < iClusterIds.length; ++i) { + if (iClusterIds[i] >= clusters.length) + throw new OConfigurationException(""Cluster id "" + iClusterIds[i] + ""was not found""); - return false; - } + c = clusters[iClusterIds[i]]; + if (c != null) + tot += c.getEntries(); + } - public long count(final int[] iClusterIds) { - checkOpeness(); + return tot; - final long timer = OProfiler.getInstance().startChrono(); + } catch (IOException e) { - final boolean locked = acquireSharedLock(); + OLogManager.instance().error(this, ""Error on getting element counts"", e); + return -1; - try { - long tot = 0; + } finally { + releaseSharedLock(locked); - OCluster c; - for (int i = 0; i < iClusterIds.length; ++i) { - if (iClusterIds[i] >= clusters.length) - throw new OConfigurationException(""Cluster id "" + iClusterIds[i] + ""was not found""); + OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterElementCounts"", timer); + } + } - c = clusters[iClusterIds[i]]; - if (c != null) - tot += c.getEntries(); - } + public long[] getClusterDataRange(final int iClusterId) { + if (iClusterId == -1) + throw new OStorageException(""Cluster Id is invalid: "" + iClusterId); - return tot; + checkOpeness(); - } catch (IOException e) { + final long timer = OProfiler.getInstance().startChrono(); - OLogManager.instance().error(this, ""Error on getting element counts"", e); - return -1; + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + return new long[] { clusters[iClusterId].getFirstEntryPosition(), clusters[iClusterId].getLastEntryPosition() }; - OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterElementCounts"", timer); - } - } + } catch (IOException e) { - public long getClusterLastEntryPosition(final int iClusterId) { - if (iClusterId == -1) - throw new OStorageException(""Cluster Id is invalid: "" + iClusterId); + OLogManager.instance().error(this, ""Error on getting last entry position"", e); + return null; - checkOpeness(); + } finally { + releaseSharedLock(locked); - final long timer = OProfiler.getInstance().startChrono(); + OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterLastEntryPosition"", timer); + } + } - final boolean locked = acquireSharedLock(); + public long count(final int iClusterId) { + if (iClusterId == -1) + throw new OStorageException(""Cluster Id is invalid: "" + iClusterId); - try { - return clusters[iClusterId].getLastEntryPosition(); + // COUNT PHYSICAL CLUSTER IF ANY + checkOpeness(); - } catch (IOException e) { + final long timer = OProfiler.getInstance().startChrono(); - OLogManager.instance().error(this, ""Error on getting last entry position"", e); - return -1; + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + return clusters[iClusterId].getEntries(); - OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterLastEntryPosition"", timer); - } - } + } catch (IOException e) { - public long count(final int iClusterId) { - if (iClusterId == -1) - throw new OStorageException(""Cluster Id is invalid: "" + iClusterId); + OLogManager.instance().error(this, ""Error on getting element counts"", e); + return -1; - // COUNT PHYSICAL CLUSTER IF ANY - checkOpeness(); + } finally { + releaseSharedLock(locked); - final long timer = OProfiler.getInstance().startChrono(); + OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterElementCounts"", timer); + } + } - final boolean locked = acquireSharedLock(); + public long createRecord(final int iClusterId, final byte[] iContent, final byte iRecordType) { + checkOpeness(); + return createRecord(getClusterById(iClusterId), iContent, iRecordType); + } - try { - return clusters[iClusterId].getEntries(); + public ORawBuffer readRecord(final ODatabaseRecord iDatabase, final int iRequesterId, final int iClusterId, + final long iPosition, final String iFetchPlan) { + checkOpeness(); + return readRecord(iRequesterId, getClusterById(iClusterId), iPosition, true); + } - } catch (IOException e) { + public int updateRecord(final int iRequesterId, final int iClusterId, final long iPosition, final byte[] iContent, + final int iVersion, final byte iRecordType) { + checkOpeness(); + return updateRecord(iRequesterId, getClusterById(iClusterId), iPosition, iContent, iVersion, iRecordType); + } - OLogManager.instance().error(this, ""Error on getting element counts"", e); - return -1; + public boolean deleteRecord(final int iRequesterId, final int iClusterId, final long iPosition, final int iVersion) { + checkOpeness(); + return deleteRecord(iRequesterId, getClusterById(iClusterId), iPosition, iVersion); + } - } finally { - releaseSharedLock(locked); + /** + * Browse N clusters. The entire operation use a shared lock on the storage and lock the cluster from the external avoiding atomic + * lock at every record read. + * + * @param iRequesterId + * The requester of the operation. Needed to know who locks + * @param iClusterId + * Array of cluster ids + * @param iListener + * The listener to call for each record found + * @param ioRecord + */ + public void browse(final int iRequesterId, final int[] iClusterId, final ORecordBrowsingListener iListener, + ORecordInternal ioRecord, final boolean iLockEntireCluster) { + checkOpeness(); - OProfiler.getInstance().stopChrono(""OStorageLocal.getClusterElementCounts"", timer); - } - } + final long timer = OProfiler.getInstance().startChrono(); - public long createRecord(final int iClusterId, final byte[] iContent, final byte iRecordType) { - checkOpeness(); - return createRecord(getClusterById(iClusterId), iContent, iRecordType); - } + final boolean locked = acquireSharedLock(); - public ORawBuffer readRecord(final ODatabaseRecord iDatabase, final int iRequesterId, final int iClusterId, - final long iPosition, final String iFetchPlan) { - checkOpeness(); - return readRecord(iRequesterId, getClusterById(iClusterId), iPosition, true); - } + try { + OCluster cluster; - public int updateRecord(final int iRequesterId, final int iClusterId, final long iPosition, final byte[] iContent, - final int iVersion, final byte iRecordType) { - checkOpeness(); - return updateRecord(iRequesterId, getClusterById(iClusterId), iPosition, iContent, iVersion, iRecordType); - } + for (int clusterId : iClusterId) { + cluster = getClusterById(clusterId); - public boolean deleteRecord(final int iRequesterId, final int iClusterId, final long iPosition, final int iVersion) { - checkOpeness(); - return deleteRecord(iRequesterId, getClusterById(iClusterId), iPosition, iVersion); - } + ioRecord = browseCluster(iRequesterId, iListener, ioRecord, cluster, iLockEntireCluster); + } + } catch (IOException e) { - /** - * Browse N clusters. The entire operation use a shared lock on the storage and lock the cluster from the external avoiding atomic - * lock at every record read. - * - * @param iRequesterId - * The requester of the operation. Needed to know who locks - * @param iClusterId - * Array of cluster ids - * @param iListener - * The listener to call for each record found - * @param ioRecord - */ - public void browse(final int iRequesterId, final int[] iClusterId, final ORecordBrowsingListener iListener, - ORecordInternal ioRecord, final boolean iLockEntireCluster) { - checkOpeness(); + OLogManager.instance().error(this, ""Error on browsing elements of cluster: "" + iClusterId, e); - final long timer = OProfiler.getInstance().startChrono(); + } finally { + releaseSharedLock(locked); - final boolean locked = acquireSharedLock(); + OProfiler.getInstance().stopChrono(""OStorageLocal.foreach"", timer); + } + } - try { - OCluster cluster; + private ORecordInternal browseCluster(final int iRequesterId, final ORecordBrowsingListener iListener, + ORecordInternal ioRecord, OCluster cluster, final boolean iLockEntireCluster) throws IOException { + ORawBuffer recordBuffer; + long positionInPhyCluster; - for (int clusterId : iClusterId) { - cluster = getClusterById(clusterId); + try { + if (iLockEntireCluster) + // LOCK THE ENTIRE CLUSTER AVOIDING TO LOCK EVERY SINGLE RECORD + cluster.lock(); - ioRecord = browseCluster(iRequesterId, iListener, ioRecord, cluster, iLockEntireCluster); - } - } catch (IOException e) { + OClusterPositionIterator iterator = cluster.absoluteIterator(); - OLogManager.instance().error(this, ""Error on browsing elements of cluster: "" + iClusterId, e); + // BROWSE ALL THE RECORDS + while (iterator.hasNext()) { + positionInPhyCluster = iterator.next(); - } finally { - releaseSharedLock(locked); + // READ THE RAW RECORD. IF iLockEntireCluster THEN THE READ WILL + // BE NOT-LOCKING, OTHERWISE YES + recordBuffer = readRecord(iRequesterId, cluster, positionInPhyCluster, !iLockEntireCluster); + if (recordBuffer == null) + continue; - OProfiler.getInstance().stopChrono(""OStorageLocal.foreach"", timer); - } - } + if (recordBuffer.recordType != ODocument.RECORD_TYPE && recordBuffer.recordType != ORecordColumn.RECORD_TYPE) + // WRONG RECORD TYPE: JUMP IT + continue; - private ORecordInternal browseCluster(final int iRequesterId, final ORecordBrowsingListener iListener, - ORecordInternal ioRecord, OCluster cluster, final boolean iLockEntireCluster) throws IOException { - ORawBuffer recordBuffer; - long positionInPhyCluster; + if (ioRecord == null) + // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE + ioRecord = ORecordFactory.newInstance(recordBuffer.recordType); + else if (ioRecord.getRecordType() != recordBuffer.recordType) { + // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE + final ORecordInternal newRecord = ORecordFactory.newInstance(recordBuffer.recordType); + newRecord.setDatabase(ioRecord.getDatabase()); + ioRecord = newRecord; + } else + // RESET CURRENT RECORD + ioRecord.reset(); - try { - if (iLockEntireCluster) - // LOCK THE ENTIRE CLUSTER AVOIDING TO LOCK EVERY SINGLE RECORD - cluster.lock(); + ioRecord.setVersion(recordBuffer.version); + ioRecord.setIdentity(cluster.getId(), positionInPhyCluster); + ioRecord.fromStream(recordBuffer.buffer); + if (!iListener.foreach(ioRecord)) + // LISTENER HAS INTERRUPTED THE EXECUTION + break; + } + } finally { - OClusterPositionIterator iterator = cluster.absoluteIterator(); + if (iLockEntireCluster) + // UNLOCK THE ENTIRE CLUSTER + cluster.unlock(); + } - // BROWSE ALL THE RECORDS - while (iterator.hasNext()) { - positionInPhyCluster = iterator.next(); + return ioRecord; + } - // READ THE RAW RECORD. IF iLockEntireCluster THEN THE READ WILL BE NOT-LOCKING, OTHERWISE YES - recordBuffer = readRecord(iRequesterId, cluster, positionInPhyCluster, !iLockEntireCluster); - if (recordBuffer == null) - continue; + public Set getClusterNames() { + checkOpeness(); - if (recordBuffer.recordType != ODocument.RECORD_TYPE && recordBuffer.recordType != ORecordColumn.RECORD_TYPE) - // WRONG RECORD TYPE: JUMP IT - continue; + final boolean locked = acquireSharedLock(); - if (ioRecord == null) - // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE - ioRecord = ORecordFactory.newInstance(recordBuffer.recordType); - else if (ioRecord.getRecordType() != recordBuffer.recordType) { - // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE - final ORecordInternal newRecord = ORecordFactory.newInstance(recordBuffer.recordType); - newRecord.setDatabase(ioRecord.getDatabase()); - ioRecord = newRecord; - } else - // RESET CURRENT RECORD - ioRecord.reset(); + try { - ioRecord.setVersion(recordBuffer.version); - ioRecord.setIdentity(cluster.getId(), positionInPhyCluster); - ioRecord.fromStream(recordBuffer.buffer); - if (!iListener.foreach(ioRecord)) - // LISTENER HAS INTERRUPTED THE EXECUTION - break; - } - } finally { + return clusterMap.keySet(); - if (iLockEntireCluster) - // UNLOCK THE ENTIRE CLUSTER - cluster.unlock(); - } + } finally { + releaseSharedLock(locked); + } + } - return ioRecord; - } + public int getClusterIdByName(final String iClusterName) { + checkOpeness(); - public Set getClusterNames() { - checkOpeness(); + if (iClusterName == null) + throw new IllegalArgumentException(""Cluster name is null""); - final boolean locked = acquireSharedLock(); + if (Character.isDigit(iClusterName.charAt(0))) + return Integer.parseInt(iClusterName); - try { + // SEARCH IT BETWEEN PHYSICAL CLUSTERS + OCluster segment; - return clusterMap.keySet(); + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); - } - } + try { + segment = clusterMap.get(iClusterName.toLowerCase()); - public int getClusterIdByName(final String iClusterName) { - checkOpeness(); + } finally { + releaseSharedLock(locked); + } - if (iClusterName == null) - throw new IllegalArgumentException(""Cluster name is null""); + if (segment != null) + return segment.getId(); - if (Character.isDigit(iClusterName.charAt(0))) - return Integer.parseInt(iClusterName); + return -1; + } - // SEARCH IT BETWEEN PHYSICAL CLUSTERS - OCluster segment; + public String getClusterTypeByName(final String iClusterName) { + checkOpeness(); - final boolean locked = acquireSharedLock(); + if (iClusterName == null) + throw new IllegalArgumentException(""Cluster name is null""); - try { - segment = clusterMap.get(iClusterName.toLowerCase()); + // SEARCH IT BETWEEN PHYSICAL CLUSTERS + OCluster segment; - } finally { - releaseSharedLock(locked); - } + final boolean locked = acquireSharedLock(); - if (segment != null) - return segment.getId(); + try { + segment = clusterMap.get(iClusterName.toLowerCase()); - return -1; - } + } finally { + releaseSharedLock(locked); + } - public String getClusterTypeByName(final String iClusterName) { - checkOpeness(); + if (segment != null) + return segment.getType(); - if (iClusterName == null) - throw new IllegalArgumentException(""Cluster name is null""); + return null; + } - // SEARCH IT BETWEEN PHYSICAL CLUSTERS - OCluster segment; + public void commit(final int iRequesterId, final OTransaction iTx) { + final boolean locked = acquireSharedLock(); - final boolean locked = acquireSharedLock(); + try { + txManager.commitAllPendingRecords(iRequesterId, iTx); - try { - segment = clusterMap.get(iClusterName.toLowerCase()); + } catch (IOException e) { + rollback(iRequesterId, iTx); - } finally { - releaseSharedLock(locked); - } + } finally { + releaseSharedLock(locked); + } - if (segment != null) - return segment.getType(); + } - return null; - } + public void rollback(final int iRequesterId, final OTransaction iTx) { + } - public void commit(final int iRequesterId, final OTransaction iTx) { - final boolean locked = acquireSharedLock(); + public void synch() { + checkOpeness(); - try { - txManager.commitAllPendingRecords(iRequesterId, iTx); + final long timer = OProfiler.getInstance().startChrono(); - } catch (IOException e) { - rollback(iRequesterId, iTx); + final boolean locked = acquireExclusiveLock(); - } finally { - releaseSharedLock(locked); - } + try { + for (OCluster cluster : clusters) + cluster.synch(); - } + for (ODataLocal data : dataSegments) + data.synch(); - public void rollback(final int iRequesterId, final OTransaction iTx) { - } + } finally { + releaseExclusiveLock(locked); - public void synch() { - checkOpeness(); + OProfiler.getInstance().stopChrono(""OStorageLocal.synch"", timer); + } + } - final long timer = OProfiler.getInstance().startChrono(); + public String getPhysicalClusterNameById(final int iClusterId) { + checkOpeness(); - final boolean locked = acquireExclusiveLock(); + for (OCluster cluster : clusters) + if (cluster != null && cluster.getId() == iClusterId) + return cluster.getName(); - try { - for (OCluster cluster : clusters) - cluster.synch(); + return null; + } - for (ODataLocal data : dataSegments) - data.synch(); + @Override + public OStorageConfiguration getConfiguration() { + return configuration; + } - } finally { - releaseExclusiveLock(locked); + public int getDefaultClusterId() { + return defaultClusterId; + } - OProfiler.getInstance().stopChrono(""OStorageLocal.synch"", timer); - } - } + public OCluster getClusterById(int iClusterId) { + if (iClusterId == ORID.CLUSTER_ID_INVALID) + // GET THE DEFAULT CLUSTER + iClusterId = defaultClusterId; - public String getPhysicalClusterNameById(final int iClusterId) { - checkOpeness(); + checkClusterSegmentIndexRange(iClusterId); - for (OCluster cluster : clusters) - if (cluster != null && cluster.getId() == iClusterId) - return cluster.getName(); + return clusters[iClusterId]; + } - return null; - } + public OCluster getClusterByName(final String iClusterName) { + final boolean locked = acquireSharedLock(); - @Override - public OStorageConfiguration getConfiguration() { - return configuration; - } + try { + final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); - public int getDefaultClusterId() { - return defaultClusterId; - } + if (cluster == null) + throw new IllegalArgumentException(""Cluster "" + iClusterName + "" not exists""); + return cluster; - public OCluster getClusterById(int iClusterId) { - if (iClusterId == ORID.CLUSTER_ID_INVALID) - // GET THE DEFAULT CLUSTER - iClusterId = defaultClusterId; + } finally { - checkClusterSegmentIndexRange(iClusterId); + releaseSharedLock(locked); + } + } - return clusters[iClusterId]; - } + public ODictionary createDictionary(ODatabaseRecord iDatabase) throws Exception { + return new ODictionaryLocal(iDatabase); + } - public OCluster getClusterByName(final String iClusterName) { - final boolean locked = acquireSharedLock(); + public String getStoragePath() { + return storagePath; + } - try { - final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); + public String getMode() { + return mode; + } - if (cluster == null) - throw new IllegalArgumentException(""Cluster "" + iClusterName + "" not exists""); - return cluster; + public OStorageVariableParser getVariableParser() { + return variableParser; + } - } finally { + protected int registerDataSegment(final OStorageDataConfiguration iConfig) throws IOException { + checkOpeness(); - releaseSharedLock(locked); - } - } + int pos = 0; - public ODictionary createDictionary(ODatabaseRecord iDatabase) throws Exception { - return new ODictionaryLocal(iDatabase); - } + // CHECK FOR DUPLICATION OF NAMES + for (ODataLocal data : dataSegments) + if (data.getName().equals(iConfig.name)) { + // OVERWRITE CONFIG + data.config = iConfig; + return -1; + } + pos = dataSegments.length; - public String getStoragePath() { - return storagePath; - } + // CREATE AND ADD THE NEW REF SEGMENT + ODataLocal segment = new ODataLocal(this, iConfig, pos); - public String getMode() { - return mode; - } + dataSegments = OArrays.copyOf(dataSegments, dataSegments.length + 1); + dataSegments[pos] = segment; - public OStorageVariableParser getVariableParser() { - return variableParser; - } + return pos; + } - protected int registerDataSegment(final OStorageDataConfiguration iConfig) throws IOException { - checkOpeness(); + /** + * Create the cluster by reading the configuration received as argument and register it assigning it the higher serial id. + * + * @param iConfig + * A OStorageClusterConfiguration implementation, namely physical or logical + * @return The id (physical position into the array) of the new cluster just created. First is 0. + * @throws IOException + * @throws IOException + */ + private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException { + if (clusterMap.containsKey(iConfig.getName())) { + OCluster c = clusterMap.get(iConfig.getName()); + if (c instanceof OClusterLocal) + // ALREADY CONFIGURED, JUST OVERWRITE CONFIG + ((OClusterLocal) c).config = (OStorageSegmentConfiguration) iConfig; + return -1; + } - int pos = 0; + final OCluster cluster; - // CHECK FOR DUPLICATION OF NAMES - for (ODataLocal data : dataSegments) - if (data.getName().equals(iConfig.name)) { - // OVERWRITE CONFIG - data.config = iConfig; - return -1; - } - pos = dataSegments.length; + if (iConfig instanceof OStoragePhysicalClusterConfiguration) { + cluster = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) iConfig); + } else + cluster = new OClusterLogical(this, (OStorageLogicalClusterConfiguration) iConfig); - // CREATE AND ADD THE NEW REF SEGMENT - ODataLocal segment = new ODataLocal(this, iConfig, pos); + return registerCluster(cluster); + } - dataSegments = OArrays.copyOf(dataSegments, dataSegments.length + 1); - dataSegments[pos] = segment; + /** + * Register the cluster internally. + * + * @param cluster + * OCluster implementation + * @return The id (physical position into the array) of the new cluster just created. First is 0. + * @throws IOException + */ + private int registerCluster(final OCluster cluster) throws IOException { + // CHECK FOR DUPLICATION OF NAMES + if (clusterMap.containsKey(cluster.getName())) + throw new OConfigurationException(""Can't add segment "" + cluster.getName() + "" because it was already registered""); - return pos; - } + // CREATE AND ADD THE NEW REF SEGMENT + clusterMap.put(cluster.getName(), cluster); - /** - * Create the cluster by reading the configuration received as argument and register it assigning it the higher serial id. - * - * @param iConfig - * A OStorageClusterConfiguration implementation, namely physical or logical - * @return The id (physical position into the array) of the new cluster just created. First is 0. - * @throws IOException - * @throws IOException - */ - private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException { - if (clusterMap.containsKey(iConfig.getName())) { - OCluster c = clusterMap.get(iConfig.getName()); - if (c instanceof OClusterLocal) - // ALREADY CONFIGURED, JUST OVERWRITE CONFIG - ((OClusterLocal) c).config = (OStorageSegmentConfiguration) iConfig; - return -1; - } + final int id = clusters.length; - final OCluster cluster; + clusters = OArrays.copyOf(clusters, id + 1); + clusters[id] = cluster; - if (iConfig instanceof OStoragePhysicalClusterConfiguration) { - cluster = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) iConfig); - } else - cluster = new OClusterLogical(this, (OStorageLogicalClusterConfiguration) iConfig); + return id; + } - return registerCluster(cluster); - } + private void checkClusterSegmentIndexRange(final int iClusterId) { + if (iClusterId > clusters.length - 1) + throw new IllegalArgumentException(""Cluster segment #"" + iClusterId + "" not exists""); + } - /** - * Register the cluster internally. - * - * @param cluster - * OCluster implementation - * @return The id (physical position into the array) of the new cluster just created. First is 0. - * @throws IOException - */ - private int registerCluster(final OCluster cluster) throws IOException { - // CHECK FOR DUPLICATION OF NAMES - if (clusterMap.containsKey(cluster.getName())) - throw new OConfigurationException(""Can't add segment "" + cluster.getName() + "" because it was already registered""); + protected int getDataSegmentForRecord(final OCluster iCluster, final byte[] iContent) { + // TODO: CREATE POLICY & STRATEGY TO ASSIGN THE BEST-MULTIPLE DATA + // SEGMENT + return 0; + } - // CREATE AND ADD THE NEW REF SEGMENT - clusterMap.put(cluster.getName(), cluster); + protected long createRecord(final OCluster iClusterSegment, final byte[] iContent, final byte iRecordType) { + checkOpeness(); - final int id = clusters.length; + if (iContent == null) + throw new IllegalArgumentException(""Record "" + iContent + "" is null""); - clusters = OArrays.copyOf(clusters, id + 1); - clusters[id] = cluster; + final long timer = OProfiler.getInstance().startChrono(); - return id; - } + final boolean locked = acquireSharedLock(); - private void checkClusterSegmentIndexRange(final int iClusterId) { - if (iClusterId > clusters.length - 1) - throw new IllegalArgumentException(""Cluster segment #"" + iClusterId + "" not exists""); - } + try { + final int dataSegment = getDataSegmentForRecord(iClusterSegment, iContent); + ODataLocal data = getDataSegment(dataSegment); - protected int getDataSegmentForRecord(final OCluster iCluster, final byte[] iContent) { - // TODO: CREATE POLICY & STRATEGY TO ASSIGN THE BEST-MULTIPLE DATA SEGMENT - return 0; - } + final long clusterPosition = iClusterSegment.addPhysicalPosition(-1, -1, iRecordType); - protected long createRecord(final OCluster iClusterSegment, final byte[] iContent, final byte iRecordType) { - checkOpeness(); + final long dataOffset = data.addRecord(iClusterSegment.getId(), clusterPosition, iContent); - if (iContent == null) - throw new IllegalArgumentException(""Record "" + iContent + "" is null""); + // UPDATE THE POSITION IN CLUSTER WITH THE POSITION OF RECORD IN + // DATA + iClusterSegment.setPhysicalPosition(clusterPosition, dataSegment, dataOffset, iRecordType); - final long timer = OProfiler.getInstance().startChrono(); + return clusterPosition; - final boolean locked = acquireSharedLock(); + } catch (IOException e) { - try { - final int dataSegment = getDataSegmentForRecord(iClusterSegment, iContent); - ODataLocal data = getDataSegment(dataSegment); + OLogManager.instance().error(this, ""Error on creating record in cluster: "" + iClusterSegment, e); + return -1; + } finally { + releaseSharedLock(locked); - final long clusterPosition = iClusterSegment.addPhysicalPosition(-1, -1, iRecordType); + OProfiler.getInstance().stopChrono(""OStorageLocal.createRecord"", timer); + } + } - final long dataOffset = data.addRecord(iClusterSegment.getId(), clusterPosition, iContent); + protected ORawBuffer readRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, boolean iAtomicLock) { + if (iPosition < 0) + throw new IllegalArgumentException(""Can't read the record because the position #"" + iPosition + "" is invalid""); - // UPDATE THE POSITION IN CLUSTER WITH THE POSITION OF RECORD IN DATA - iClusterSegment.setPhysicalPosition(clusterPosition, dataSegment, dataOffset, iRecordType); + // NOT FOUND: SEARCH IT IN THE STORAGE + final long timer = OProfiler.getInstance().startChrono(); - return clusterPosition; + // GET LOCK ONLY IF IT'S IN ATOMIC-MODE (SEE THE PARAMETER iAtomicLock) + // USUALLY BROWSING OPERATIONS (QUERY) AVOID ATOMIC LOCKING + // TO IMPROVE PERFORMANCES BY LOCKING THE ENTIRE CLUSTER FROM THE + // OUTSIDE. + final boolean locked = iAtomicLock ? acquireSharedLock() : false; - } catch (IOException e) { + try { + // lockManager.acquireLock(iRequesterId, recId, LOCK.SHARED, + // timeout); - OLogManager.instance().error(this, ""Error on creating record in cluster: "" + iClusterSegment, e); - return -1; - } finally { - releaseSharedLock(locked); + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + if (ppos == null || !checkForRecordValidity(ppos)) + // DELETED + return null; - OProfiler.getInstance().stopChrono(""OStorageLocal.createRecord"", timer); - } - } + final ODataLocal data = getDataSegment(ppos.dataSegment); + return new ORawBuffer(data.getRecord(ppos.dataPosition), ppos.version, ppos.type); - protected ORawBuffer readRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, boolean iAtomicLock) { - if (iPosition < 0) - throw new IllegalArgumentException(""Can't read the record because the position #"" + iPosition + "" is invalid""); + } catch (IOException e) { - // NOT FOUND: SEARCH IT IN THE STORAGE - final long timer = OProfiler.getInstance().startChrono(); + OLogManager.instance().error(this, ""Error on reading record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); + return null; - // GET LOCK ONLY IF IT'S IN ATOMIC-MODE (SEE THE PARAMETER iAtomicLock) USUALLY BROWSING OPERATIONS (QUERY) AVOID ATOMIC LOCKING - // TO IMPROVE PERFORMANCES BY LOCKING THE ENTIRE CLUSTER FROM THE OUTSIDE. - final boolean locked = iAtomicLock ? acquireSharedLock() : false; + } finally { + releaseSharedLock(locked); - try { - // lockManager.acquireLock(iRequesterId, recId, LOCK.SHARED, timeout); + OProfiler.getInstance().stopChrono(""OStorageLocal.readRecord"", timer); + } + } - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - if (ppos == null || !checkForRecordValidity(ppos)) - // DELETED - return null; + protected int updateRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final byte[] iContent, + final int iVersion, final byte iRecordType) { + final long timer = OProfiler.getInstance().startChrono(); - final ODataLocal data = getDataSegment(ppos.dataSegment); - return new ORawBuffer(data.getRecord(ppos.dataPosition), ppos.version, ppos.type); + final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); - } catch (IOException e) { + final boolean locked = acquireSharedLock(); - OLogManager.instance().error(this, ""Error on reading record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); - return null; + try { + // lockManager.acquireLock(iRequesterId, recId, LOCK.EXCLUSIVE, + // timeout); - } finally { - releaseSharedLock(locked); + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + if (!checkForRecordValidity(ppos)) + // DELETED + return -1; - OProfiler.getInstance().stopChrono(""OStorageLocal.readRecord"", timer); - } - } + // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME + if (iVersion > -1 && ppos.version != iVersion) + throw new OConcurrentModificationException( + ""Can't update record #"" + + recId + + "" because it has been modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction""); - protected int updateRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final byte[] iContent, - final int iVersion, final byte iRecordType) { - final long timer = OProfiler.getInstance().startChrono(); + if (ppos.type != iRecordType) + iClusterSegment.updateRecordType(iPosition, iRecordType); - final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); + iClusterSegment.updateVersion(iPosition, ++ppos.version); - final boolean locked = acquireSharedLock(); + final long newDataSegmentOffset = getDataSegment(ppos.dataSegment).setRecord(ppos.dataPosition, iClusterSegment.getId(), + iPosition, iContent); - try { - // lockManager.acquireLock(iRequesterId, recId, LOCK.EXCLUSIVE, timeout); + if (newDataSegmentOffset != ppos.dataPosition) + // UPDATE DATA SEGMENT OFFSET WITH THE NEW PHYSICAL POSITION + iClusterSegment.setPhysicalPosition(iPosition, ppos.dataSegment, newDataSegmentOffset, iRecordType); - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - if (!checkForRecordValidity(ppos)) - // DELETED - return -1; + return ppos.version; - // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME - if (iVersion > -1 && ppos.version != iVersion) - throw new OConcurrentModificationException( - ""Can't update record #"" - + recId - + "" because it has been modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction""); + } catch (IOException e) { - if (ppos.type != iRecordType) - iClusterSegment.updateRecordType(iPosition, iRecordType); + OLogManager.instance().error(this, ""Error on updating record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); - iClusterSegment.updateVersion(iPosition, ++ppos.version); + } finally { + releaseSharedLock(locked); - final long newDataSegmentOffset = getDataSegment(ppos.dataSegment).setRecord(ppos.dataPosition, iClusterSegment.getId(), - iPosition, iContent); + OProfiler.getInstance().stopChrono(""OStorageLocal.updateRecord"", timer); + } - if (newDataSegmentOffset != ppos.dataPosition) - // UPDATE DATA SEGMENT OFFSET WITH THE NEW PHYSICAL POSITION - iClusterSegment.setPhysicalPosition(iPosition, ppos.dataSegment, newDataSegmentOffset, iRecordType); + return -1; + } - return ppos.version; + protected boolean deleteRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { + final long timer = OProfiler.getInstance().startChrono(); - } catch (IOException e) { + final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); - OLogManager.instance().error(this, ""Error on updating record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - OProfiler.getInstance().stopChrono(""OStorageLocal.updateRecord"", timer); - } + if (!checkForRecordValidity(ppos)) + // ALREADY DELETED + return false; - return -1; - } + // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME + if (iVersion > -1 && ppos.version != iVersion) + throw new OConcurrentModificationException( + ""Can't delete the record #"" + + recId + + "" because it was modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction""); - protected boolean deleteRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { - final long timer = OProfiler.getInstance().startChrono(); + iClusterSegment.removePhysicalPosition(iPosition, ppos); - final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); + getDataSegment(ppos.dataSegment).deleteRecord(ppos.dataPosition); - final boolean locked = acquireSharedLock(); + return true; - try { - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + } catch (IOException e) { - if (!checkForRecordValidity(ppos)) - // ALREADY DELETED - return false; + OLogManager.instance().error(this, ""Error on deleting record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); - // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME - if (iVersion > -1 && ppos.version != iVersion) - throw new OConcurrentModificationException( - ""Can't delete the record #"" - + recId - + "" because it was modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction""); + } finally { + releaseSharedLock(locked); - iClusterSegment.removePhysicalPosition(iPosition, ppos); + OProfiler.getInstance().stopChrono(""OStorageLocal.deleteRecord"", timer); + } - getDataSegment(ppos.dataSegment).deleteRecord(ppos.dataPosition); + return false; + } - return true; + /** + * Check if the storage is open. If it's closed an exception is raised. + */ + private void checkOpeness() { + if (!open) + throw new OStorageException(""Storage "" + name + "" is not opened.""); + } - } catch (IOException e) { + public Set getClusters() { + Set result = new HashSet(); - OLogManager.instance().error(this, ""Error on deleting record #"" + iPosition + "" in cluster: "" + iClusterSegment, e); + // ADD ALL THE CLUSTERS + for (OCluster c : clusters) + result.add(c); - } finally { - releaseSharedLock(locked); + return result; + } - OProfiler.getInstance().stopChrono(""OStorageLocal.deleteRecord"", timer); - } + /** + * Execute the command request and return the result back. + */ + public Object command(final OCommandRequestText iCommand) { + final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand); + executor.parse(iCommand); + try { + return executor.execute(); + } catch (OCommandExecutionException e) { + // PASS THROUGHT + throw e; + } catch (Exception e) { + throw new OCommandExecutionException(""Error on execution of command: "" + iCommand, e); + } + } - return false; - } + /** + * Add a new physical cluster into the storage. + * + * @throws IOException + */ + private int addPhysicalCluster(final String iClusterName, String iClusterFileName, final int iStartSize) throws IOException { + final OStoragePhysicalClusterConfiguration config = new OStoragePhysicalClusterConfiguration(configuration, iClusterName, + clusters.length); + configuration.clusters.add(config); - /** - * Check if the storage is open. If it's closed an exception is raised. - */ - private void checkOpeness() { - if (!open) - throw new OStorageException(""Storage "" + name + "" is not opened.""); - } + final OClusterLocal cluster = new OClusterLocal(this, config); + final int id = registerCluster(cluster); - public Set getClusters() { - Set result = new HashSet(); + clusters[id].create(iStartSize); + configuration.update(); + return id; + } - // ADD ALL THE CLUSTERS - for (OCluster c : clusters) - result.add(c); + private int addLogicalCluster(final String iClusterName, final int iPhysicalCluster) throws IOException { + final OStorageLogicalClusterConfiguration config = new OStorageLogicalClusterConfiguration(iClusterName, clusters.length, + iPhysicalCluster, null); - return result; - } - - /** - * Execute the command request and return the result back. - */ - public Object command(final OCommandRequestText iCommand) { - final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand); - executor.parse(iCommand); - try { - return executor.execute(); - } catch (OCommandExecutionException e) { - // PASS THROUGHT - throw e; - } catch (Exception e) { - throw new OCommandExecutionException(""Error on execution of command: "" + iCommand, e); - } - } - - /** - * Add a new physical cluster into the storage. - * - * @throws IOException - */ - private int addPhysicalCluster(final String iClusterName, String iClusterFileName, final int iStartSize) throws IOException { - final OStoragePhysicalClusterConfiguration config = new OStoragePhysicalClusterConfiguration(configuration, iClusterName, - clusters.length); - configuration.clusters.add(config); - - final OClusterLocal cluster = new OClusterLocal(this, config); - final int id = registerCluster(cluster); - - clusters[id].create(iStartSize); - configuration.update(); - return id; - } - - private int addLogicalCluster(final String iClusterName, final int iPhysicalCluster) throws IOException { - final OStorageLogicalClusterConfiguration config = new OStorageLogicalClusterConfiguration(iClusterName, clusters.length, - iPhysicalCluster, null); - - configuration.clusters.add(config); - - final OClusterLogical cluster = new OClusterLogical(this, clusters.length, iClusterName, iPhysicalCluster); - config.map = cluster.getRID(); - final int id = registerCluster(cluster); - - configuration.update(); - return id; - } - - public ODataLocal[] getDataSegments() { - return dataSegments; - } - - public OStorageLocalTxExecuter getTxManager() { - return txManager; - } + configuration.clusters.add(config); + + final OClusterLogical cluster = new OClusterLogical(this, clusters.length, iClusterName, iPhysicalCluster); + config.map = cluster.getRID(); + final int id = registerCluster(cluster); + + configuration.update(); + return id; + } + + public ODataLocal[] getDataSegments() { + return dataSegments; + } + + public OStorageLocalTxExecuter getTxManager() { + return txManager; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java index c0eedb04af3..60b1ee15859 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java @@ -25,12 +25,12 @@ import com.orientechnologies.orient.core.storage.OPhysicalPosition; public class OClusterMemory extends OSharedResource implements OCluster { - public static final String TYPE = ""MEMORY""; + public static final String TYPE = ""MEMORY""; - private int id; - private String name; - private List entries = new ArrayList(); - private int removed = 0; + private int id; + private String name; + private List entries = new ArrayList(); + private int removed = 0; public OClusterMemory(final int id, final String name) { this.id = id; @@ -57,6 +57,10 @@ public long getEntries() { return entries.size() - removed; } + public long getFirstEntryPosition() { + return 0; + } + public long getLastEntryPosition() { return entries.size(); } @@ -73,12 +77,15 @@ public long getAvailablePosition() throws IOException { return entries.size(); } - public long addPhysicalPosition(final int iDataSegmentId, final long iRecordPosition, final byte iRecordType) { - entries.add(new OPhysicalPosition(iDataSegmentId, iRecordPosition, iRecordType)); + public long addPhysicalPosition(final int iDataSegmentId, + final long iRecordPosition, final byte iRecordType) { + entries.add(new OPhysicalPosition(iDataSegmentId, iRecordPosition, + iRecordType)); return entries.size() - 1; } - public void updateRecordType(final long iPosition, final byte iRecordType) throws IOException { + public void updateRecordType(final long iPosition, final byte iRecordType) + throws IOException { entries.get((int) iPosition).type = iRecordType; } @@ -86,20 +93,23 @@ public void updateVersion(long iPosition, int iVersion) throws IOException { entries.get((int) iPosition).version = iVersion; } - public OPhysicalPosition getPhysicalPosition(final long iPosition, final OPhysicalPosition iPPosition) { + public OPhysicalPosition getPhysicalPosition(final long iPosition, + final OPhysicalPosition iPPosition) { return entries.get((int) iPosition); } public void open() throws IOException { } - public void removePhysicalPosition(final long iPosition, OPhysicalPosition iPPosition) { + public void removePhysicalPosition(final long iPosition, + OPhysicalPosition iPPosition) { if (entries.set((int) iPosition, null) != null) // ADD A REMOVED removed++; } - public void setPhysicalPosition(final long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) { + public void setPhysicalPosition(final long iPosition, final int iDataId, + final long iDataPosition, final byte iRecordType) { final OPhysicalPosition ppos = entries.get((int) iPosition); ppos.dataSegment = iDataId; ppos.dataPosition = iDataPosition; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java index 2a0a386190a..6969a6a7792 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java @@ -216,10 +216,10 @@ public long count(final int iClusterId) { } } - public long getClusterLastEntryPosition(final int iClusterId) { + public long[] getClusterDataRange(final int iClusterId) { final OCluster cluster = getClusterById(iClusterId); try { - return cluster.getLastEntryPosition(); + return new long[]{ cluster.getFirstEntryPosition(), cluster.getLastEntryPosition() }; } catch (IOException e) { throw new OStorageException(""Error on getting last entry position in cluster: "" + iClusterId, e); } diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java index bc841416dde..732c7b395af 100644 --- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java +++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java @@ -29,7 +29,7 @@ public class OChannelBinaryProtocol { public static final byte CLUSTER_ADD = 10; public static final byte CLUSTER_REMOVE = 11; public static final byte CLUSTER_COUNT = 12; - public static final byte CLUSTER_LASTPOS = 13; + public static final byte CLUSTER_DATARANGE = 13; public static final byte DATASEGMENT_ADD = 20; public static final byte DATASEGMENT_REMOVE = 21; diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index fa2f4e62c24..f45f2a79d6a 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -71,21 +71,22 @@ import com.orientechnologies.orient.server.tx.OTransactionRecordProxy; public class ONetworkProtocolBinary extends ONetworkProtocol { - protected OClientConnection connection; - protected OChannelBinary channel; - protected OUser account; + protected OClientConnection connection; + protected OChannelBinary channel; + protected OUser account; - private String user; - private String passwd; - private ODatabaseRaw underlyingDatabase; - private int commandType; + private String user; + private String passwd; + private ODatabaseRaw underlyingDatabase; + private int commandType; public ONetworkProtocolBinary() { super(OServer.getThreadGroup(), ""Binary-DB""); } @Override - public void config(final Socket iSocket, final OClientConnection iConnection) throws IOException { + public void config(final Socket iSocket, final OClientConnection iConnection) + throws IOException { channel = new OChannelBinaryServer(iSocket); connection = iConnection; @@ -127,11 +128,13 @@ protected void execute() throws Exception { passwd = channel.readString(); // SEARCH THE DB IN MEMORY FIRST - connection.database = (ODatabaseDocumentTx) OServerMain.server().getMemoryDatabases().get(dbName); + connection.database = (ODatabaseDocumentTx) OServerMain + .server().getMemoryDatabases().get(dbName); if (connection.database == null) // SEARCH THE DB IN LOCAL FS - connection.database = new ODatabaseDocumentTx(OServerMain.server().getStoragePath(dbName)); + connection.database = new ODatabaseDocumentTx(OServerMain + .server().getStoragePath(dbName)); if (connection.database.isClosed()) if (connection.database.getStorage() instanceof OStorageMemory) @@ -139,16 +142,23 @@ protected void execute() throws Exception { else connection.database.open(user, passwd); - underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying()); + underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex) connection.database + .getUnderlying()).getUnderlying()); - if (!(underlyingDatabase.getStorage() instanceof OStorageMemory) && !loadUserFromSchema(user, passwd)) { - sendError(new OSecurityAccessException(connection.database.getName(), ""Access denied to database '"" - + connection.database.getName() + ""' for user: "" + user)); + if (!(underlyingDatabase.getStorage() instanceof OStorageMemory) + && !loadUserFromSchema(user, passwd)) { + sendError(new OSecurityAccessException( + connection.database.getName(), + ""Access denied to database '"" + + connection.database.getName() + + ""' for user: "" + user)); } else { sendOk(); channel.writeString(connection.id); - channel.writeInt(connection.database.getClusterNames().size()); - for (OCluster c : (connection.database.getStorage()).getClusters()) { + channel.writeInt(connection.database.getClusterNames() + .size()); + for (OCluster c : (connection.database.getStorage()) + .getClusters()) { if (c != null) { channel.writeString(c.getName()); channel.writeInt(c.getId()); @@ -170,18 +180,25 @@ protected void execute() throws Exception { if (storageMode.equals(OEngineLocal.NAME)) { if (OServerMain.server().existsStoragePath(dbName)) - throw new IllegalArgumentException(""Database '"" + dbName + ""' already exists.""); + throw new IllegalArgumentException(""Database '"" + + dbName + ""' already exists.""); - path = storageMode + "":${ORIENTDB_HOME}/databases/"" + dbName + ""/"" + dbName; - realPath = OSystemVariableResolver.resolveSystemVariables(path); + path = storageMode + "":${ORIENTDB_HOME}/databases/"" + + dbName + ""/"" + dbName; + realPath = OSystemVariableResolver + .resolveSystemVariables(path); } else if (storageMode.equals(OEngineMemory.NAME)) { - if (OServerMain.server().getMemoryDatabases().containsKey(dbName)) - throw new IllegalArgumentException(""Database '"" + dbName + ""' already exists.""); + if (OServerMain.server().getMemoryDatabases() + .containsKey(dbName)) + throw new IllegalArgumentException(""Database '"" + + dbName + ""' already exists.""); path = storageMode + "":"" + dbName; realPath = path; } else - throw new IllegalArgumentException(""Can't create databse: storage mode '"" + storageMode + ""' is not supported.""); + throw new IllegalArgumentException( + ""Can't create databse: storage mode '"" + + storageMode + ""' is not supported.""); connection.database = new ODatabaseDocumentTx(realPath); connection.database.create(); @@ -192,10 +209,12 @@ protected void execute() throws Exception { } else if (storageMode.equals(OEngineMemory.NAME)) { // SAVE THE DB IN MEMORY - OServerMain.server().getMemoryDatabases().put(dbName, connection.database); + OServerMain.server().getMemoryDatabases() + .put(dbName, connection.database); } - underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying()); + underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex) connection.database + .getUnderlying()).getUnderlying()); sendOk(); break; @@ -223,20 +242,23 @@ protected void execute() throws Exception { for (int i = 0; i < clusterIds.length; ++i) clusterIds[i] = channel.readShort(); - long count = connection.database.countClusterElements(clusterIds); + long count = connection.database + .countClusterElements(clusterIds); sendOk(); channel.writeLong(count); break; } - case OChannelBinaryProtocol.CLUSTER_LASTPOS: { - data.commandInfo = ""Get last entry position in cluster""; + case OChannelBinaryProtocol.CLUSTER_DATARANGE: { + data.commandInfo = ""Get the begin/end range of data in cluster""; - long pos = connection.database.getStorage().getClusterLastEntryPosition(channel.readShort()); + long[] pos = connection.database.getStorage() + .getClusterDataRange(channel.readShort()); sendOk(); - channel.writeLong(pos); + channel.writeLong(pos[0]); + channel.writeLong(pos[1]); break; } @@ -248,9 +270,11 @@ protected void execute() throws Exception { final int num; if (OClusterLocal.TYPE.equals(type)) - num = connection.database.addPhysicalCluster(name, channel.readString(), channel.readInt()); + num = connection.database.addPhysicalCluster(name, + channel.readString(), channel.readInt()); else - num = connection.database.addLogicalCluster(name, channel.readInt()); + num = connection.database.addLogicalCluster(name, + channel.readInt()); sendOk(); channel.writeShort((short) num); @@ -262,7 +286,8 @@ protected void execute() throws Exception { final int id = channel.readShort(); - boolean result = connection.database.getStorage().removeCluster(id); + boolean result = connection.database.getStorage() + .removeCluster(id); sendOk(); channel.writeByte((byte) (result ? '1' : '0')); @@ -277,7 +302,8 @@ protected void execute() throws Exception { final String fetchPlanString = channel.readString(); // LOAD THE RAW BUFFER - final ORawBuffer buffer = underlyingDatabase.read(clusterId, clusterPosition, null); + final ORawBuffer buffer = underlyingDatabase.read(clusterId, + clusterPosition, null); sendOk(); if (buffer != null) { @@ -288,33 +314,50 @@ protected void execute() throws Exception { channel.writeByte(buffer.recordType); if (fetchPlanString.length() > 0) { - // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH PLAN - final ORecordInternal record = ORecordFactory.newInstance(buffer.recordType); - record.fill(connection.database, clusterId, clusterPosition, buffer.version); + // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH + // PLAN + final ORecordInternal record = ORecordFactory + .newInstance(buffer.recordType); + record.fill(connection.database, clusterId, + clusterPosition, buffer.version); record.fromStream(buffer.buffer); if (record instanceof ODocument) { - final Map fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString); + final Map fetchPlan = OFetchHelper + .buildFetchPlan(fetchPlanString); final Set recordsToSend = new HashSet(); - OFetchHelper.fetch((ODocument) record, record, fetchPlan, null, 0, -1, new OFetchListener() { - public int size() { - return recordsToSend.size(); - } + OFetchHelper.fetch((ODocument) record, record, + fetchPlan, null, 0, -1, + new OFetchListener() { + public int size() { + return recordsToSend.size(); + } - // ADD TO THE SET OF OBJECTS TO SEND - public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final String iFieldName, - final Object iLinked) { - if (iLinked instanceof ODocument) - return recordsToSend.add((ODocument) iLinked) ? iLinked : null; - else - return recordsToSend.addAll((Collection) iLinked) ? iLinked : null; - } - }); + // ADD TO THE SET OF OBJECTS TO SEND + public Object fetchLinked( + final ODocument iRoot, + final Object iUserObject, + final String iFieldName, + final Object iLinked) { + if (iLinked instanceof ODocument) + return recordsToSend + .add((ODocument) iLinked) ? iLinked + : null; + else + return recordsToSend + .addAll((Collection) iLinked) ? iLinked + : null; + } + }); // SEND RECORDS TO LOAD IN CLIENT CACHE for (ODocument doc : recordsToSend) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT ISN'T PART OF THE RESULT SET + channel.writeByte((byte) 2); // CLIENT CACHE + // RECORD. IT + // ISN'T PART OF + // THE RESULT + // SET writeRecord(doc); } } @@ -331,8 +374,9 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final case OChannelBinaryProtocol.RECORD_CREATE: data.commandInfo = ""Create record""; - final long location = underlyingDatabase.save(channel.readShort(), ORID.CLUSTER_POS_INVALID, channel.readBytes(), -1, - channel.readByte()); + final long location = underlyingDatabase.save( + channel.readShort(), ORID.CLUSTER_POS_INVALID, + channel.readBytes(), -1, channel.readByte()); sendOk(); channel.writeLong(location); break; @@ -343,15 +387,25 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final final int clusterId = channel.readShort(); final long position = channel.readLong(); - long newVersion = underlyingDatabase.save(clusterId, position, channel.readBytes(), channel.readInt(), channel.readByte()); + long newVersion = underlyingDatabase.save(clusterId, position, + channel.readBytes(), channel.readInt(), + channel.readByte()); // TODO: Handle it by using triggers - if (connection.database.getMetadata().getSchema().getDocument().getIdentity().getClusterId() == clusterId - && connection.database.getMetadata().getSchema().getDocument().getIdentity().getClusterPosition() == position) + if (connection.database.getMetadata().getSchema().getDocument() + .getIdentity().getClusterId() == clusterId + && connection.database.getMetadata().getSchema() + .getDocument().getIdentity() + .getClusterPosition() == position) connection.database.getMetadata().loadSchema(); - else if (((ODictionaryLocal) connection.database.getDictionary()).getTree().getRecord().getIdentity().getClusterId() == clusterId - && ((ODictionaryLocal) connection.database.getDictionary()).getTree().getRecord().getIdentity().getClusterPosition() == position) - ((ODictionaryLocal) connection.database.getDictionary()).load(); + else if (((ODictionaryLocal) connection.database + .getDictionary()).getTree().getRecord().getIdentity() + .getClusterId() == clusterId + && ((ODictionaryLocal) connection.database + .getDictionary()).getTree().getRecord() + .getIdentity().getClusterPosition() == position) + ((ODictionaryLocal) connection.database.getDictionary()) + .load(); sendOk(); @@ -361,7 +415,8 @@ else if (((ODictionaryLocal) connection.database.getDictionary()).getTree().g case OChannelBinaryProtocol.RECORD_DELETE: data.commandInfo = ""Delete record""; - underlyingDatabase.delete(channel.readShort(), channel.readLong(), channel.readInt()); + underlyingDatabase.delete(channel.readShort(), + channel.readLong(), channel.readInt()); sendOk(); channel.writeByte((byte) '1'); @@ -371,7 +426,8 @@ else if (((ODictionaryLocal) connection.database.getDictionary()).getTree().g data.commandInfo = ""Count cluster records""; final String clusterName = channel.readString(); - final long size = connection.database.countClusterElements(clusterName); + final long size = connection.database + .countClusterElements(clusterName); sendOk(); @@ -384,10 +440,11 @@ else if (((ODictionaryLocal) connection.database.getDictionary()).getTree().g final boolean asynch = channel.readByte() == 'a'; - final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel - .readBytes()); + final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE + .fromStream(channel.readBytes()); - final OQuery query = (OQuery) (command instanceof OQuery ? command : null); + final OQuery query = (OQuery) (command instanceof OQuery ? command + : null); data.commandDetail = command.getText(); @@ -396,7 +453,8 @@ else if (((ODictionaryLocal) connection.database.getDictionary()).getTree().g final StringBuilder empty = new StringBuilder(); final Set recordsToSend = new HashSet(); - final Map fetchPlan = query != null ? OFetchHelper.buildFetchPlan(query.getFetchPlan()) : null; + final Map fetchPlan = query != null ? OFetchHelper + .buildFetchPlan(query.getFetchPlan()) : null; command.setResultListener(new OCommandResultListener() { public boolean result(final Object iRecord) { @@ -412,21 +470,32 @@ public boolean result(final Object iRecord) { writeRecord((ORecordInternal) iRecord); channel.flush(); - if (fetchPlan != null && iRecord instanceof ODocument) { - OFetchHelper.fetch((ODocument) iRecord, iRecord, fetchPlan, null, 0, -1, new OFetchListener() { - public int size() { - return recordsToSend.size(); - } - - // ADD TO THE SET OF OBJECT TO SEND - public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final String iFieldName, - final Object iLinked) { - if (iLinked instanceof ODocument) - return recordsToSend.add((ODocument) iLinked) ? iLinked : null; - else - return recordsToSend.addAll((Collection) iLinked) ? iLinked : null; - } - }); + if (fetchPlan != null + && iRecord instanceof ODocument) { + OFetchHelper.fetch((ODocument) iRecord, + iRecord, fetchPlan, null, 0, -1, + new OFetchListener() { + public int size() { + return recordsToSend.size(); + } + + // ADD TO THE SET OF OBJECT TO + // SEND + public Object fetchLinked( + final ODocument iRoot, + final Object iUserObject, + final String iFieldName, + final Object iLinked) { + if (iLinked instanceof ODocument) + return recordsToSend + .add((ODocument) iLinked) ? iLinked + : null; + else + return recordsToSend + .addAll((Collection) iLinked) ? iLinked + : null; + } + }); } } catch (IOException e) { @@ -437,7 +506,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final } }); - ((OCommandRequestInternal) connection.database.command(command)).execute(); + ((OCommandRequestInternal) connection.database + .command(command)).execute(); if (empty.length() == 0) try { @@ -447,14 +517,17 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final // SEND RECORDS TO LOAD IN CLIENT CACHE for (ODocument doc : recordsToSend) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT ISN'T PART OF THE RESULT SET + channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT + // ISN'T PART OF THE + // RESULT SET writeRecord(doc); } channel.writeByte((byte) 0); // NO MORE RECORDS } else { // SYNCHRONOUS - final Object result = ((OCommandRequestInternal) connection.database.command(command)).execute(); + final Object result = ((OCommandRequestInternal) connection.database + .command(command)).execute(); sendOk(); @@ -469,7 +542,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final } else { // ANY OTHER (INCLUDING LITERALS) channel.writeByte((byte) 'a'); - channel.writeBytes(OStreamSerializerAnyRuntime.INSTANCE.toStream(result)); + channel.writeBytes(OStreamSerializerAnyRuntime.INSTANCE + .toStream(result)); } } break; @@ -479,10 +553,12 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = ""Dictionary lookup""; final String key = channel.readString(); - final ORecordAbstract value = connection.database.getDictionary().get(key); + final ORecordAbstract value = connection.database + .getDictionary().get(key); if (value != null) - ((ODatabaseRecordTx>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -494,16 +570,19 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = ""Dictionary put""; String key = channel.readString(); - ORecordInternal value = ORecordFactory.newInstance(channel.readByte()); + ORecordInternal value = ORecordFactory.newInstance(channel + .readByte()); final ORecordId rid = new ORecordId(channel.readString()); value.setIdentity(rid.clusterId, rid.clusterPosition); value.setDatabase(connection.database); - value = connection.database.getDictionary().putRecord(key, value); + value = connection.database.getDictionary().putRecord(key, + value); if (value != null) - ((ODatabaseRecordTx>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -515,10 +594,12 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = ""Dictionary remove""; final String key = channel.readString(); - final ORecordInternal value = connection.database.getDictionary().remove(key); + final ORecordInternal value = connection.database + .getDictionary().remove(key); if (value != null) - ((ODatabaseRecordTx>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -538,15 +619,19 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = ""Dictionary keys""; sendOk(); - channel.writeCollectionString(connection.database.getDictionary().keySet()); + channel.writeCollectionString(connection.database + .getDictionary().keySet()); break; } case OChannelBinaryProtocol.TX_COMMIT: data.commandInfo = ""Transaction commit""; - ((OStorageLocal) connection.database.getStorage()).commit(connection.database.getId(), new OTransactionOptimisticProxy( - (ODatabaseRecordTx) connection.database.getUnderlying(), channel)); + ((OStorageLocal) connection.database.getStorage()) + .commit(connection.database.getId(), + new OTransactionOptimisticProxy( + (ODatabaseRecordTx) connection.database + .getUnderlying(), channel)); sendOk(); break; @@ -554,7 +639,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final default: data.commandInfo = ""Command not supported""; - OLogManager.instance().error(this, ""Request not supported. Code: "" + commandType); + OLogManager.instance().error(this, + ""Request not supported. Code: "" + commandType); channel.clearInput(); sendError(null); @@ -572,12 +658,14 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final try { channel.flush(); } catch (Throwable t) { - OLogManager.instance().debug(this, ""Error on send data over the network"", t); + OLogManager.instance().debug(this, + ""Error on send data over the network"", t); } OSerializationThreadLocal.INSTANCE.get().clear(); - data.lastCommandExecutionTime = System.currentTimeMillis() - data.lastCommandReceived; + data.lastCommandExecutionTime = System.currentTimeMillis() + - data.lastCommandReceived; data.totalCommandExecutionTime += data.lastCommandExecutionTime; data.lastCommandInfo = data.commandInfo; @@ -595,7 +683,8 @@ public void shutdown() { sendShutdown(); channel.close(); - OClientConnectionManager.instance().onClientDisconnection(connection.id); + OClientConnectionManager.instance() + .onClientDisconnection(connection.id); } @Override @@ -625,11 +714,14 @@ protected void sendError(final Throwable t) throws IOException { channel.clearInput(); } - private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) { - account = connection.database.getMetadata().getSecurity().getUser(iUserName); + private boolean loadUserFromSchema(final String iUserName, + final String iUserPassword) { + account = connection.database.getMetadata().getSecurity() + .getUser(iUserName); if (account == null) - throw new OSecurityAccessException(connection.database.getName(), ""User '"" + iUserName + ""' was not found in database: "" - + connection.database.getName()); + throw new OSecurityAccessException(connection.database.getName(), + ""User '"" + iUserName + ""' was not found in database: "" + + connection.database.getName()); boolean allow = account.checkPassword(iUserPassword); @@ -651,13 +743,14 @@ private boolean loadUserFromSchema(final String iUserName, final String iUserPas * @param iRecord * @throws IOException */ - private void writeRecord(final ORecordInternal iRecord) throws IOException { + private void writeRecord(final ORecordInternal iRecord) + throws IOException { if (iRecord == null) { channel.writeShort((short) OChannelBinaryProtocol.RECORD_NULL); } else { channel.writeShort((short) (iRecord instanceof ORecordSchemaAware - && ((ORecordSchemaAware) iRecord).getSchemaClass() != null ? ((ORecordSchemaAware) iRecord).getSchemaClass() - .getId() : -1)); + && ((ORecordSchemaAware) iRecord).getSchemaClass() != null ? ((ORecordSchemaAware) iRecord) + .getSchemaClass().getId() : -1)); channel.writeByte(iRecord.getRecordType()); channel.writeShort((short) iRecord.getIdentity().getClusterId()); diff --git a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java index f9f6f2d28d9..b8fea9effa3 100644 --- a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java +++ b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java @@ -139,8 +139,8 @@ private boolean compareRecords() { clusterId = storage1.getClusterIdByName(clusterName); - long db1Max = storage1.getClusterLastEntryPosition(clusterId); - long db2Max = storage2.getClusterLastEntryPosition(clusterId); + long db1Max = storage1.getClusterDataRange(clusterId)[1]; + long db2Max = storage2.getClusterDataRange(clusterId)[1]; long clusterMax = Math.max(db1Max, db2Max); for (int i = 0; i < clusterMax; ++i) { diff --git a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java index 0f30a9b69ef..667ba0da585 100644 --- a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java +++ b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java @@ -462,7 +462,7 @@ record = ORecordSerializerJSON.INSTANCE.fromString(database, value, record); String rid = record.getIdentity().toString(); - long nextAvailablePos = database.getStorage().getClusterLastEntryPosition(record.getIdentity().getClusterId()) + 1; + long nextAvailablePos = database.getStorage().getClusterDataRange(record.getIdentity().getClusterId())[1] + 1; // SAVE THE RECORD if (record.getIdentity().getClusterPosition() < nextAvailablePos) {" 0b37cec28721a379b87dd8a67a0d8cdd629d13c0,spring-framework,"Consistent support for JTA 1.1- TransactionSynchronizationRegistry--JtaTransactionManager's configuration options for a TransactionSynchronizationRegistry are now in sync with the options for UserTransaction/TransactionManager. Specifically, there are setTransactionSynchronizationRegistry/getTransactionSynchronizationRegistry methods for programmatic configuration now. Motivated by Spring's adapting to a Hibernate JtaPlatform, specifically the Hibernate 4.3 changes in that area.--Issue: SPR-10839-",c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java b/spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java index 5e808b70c4e9..9f136ba1e7e8 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java +++ b/spring-tx/src/main/java/org/springframework/transaction/jta/JtaTransactionManager.java @@ -164,9 +164,11 @@ public class JtaTransactionManager extends AbstractPlatformTransactionManager private boolean autodetectTransactionManager = true; + private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry; + private String transactionSynchronizationRegistryName; - private transient TransactionSynchronizationRegistry transactionSynchronizationRegistry; + private boolean autodetectTransactionSynchronizationRegistry = true; private boolean allowCustomIsolationLevels = false; @@ -327,7 +329,7 @@ public void setTransactionManager(TransactionManager transactionManager) { } /** - * Return the JTA TransactionManager that this transaction manager uses. + * Return the JTA TransactionManager that this transaction manager uses, if any. */ public TransactionManager getTransactionManager() { return this.transactionManager; @@ -363,6 +365,28 @@ public void setAutodetectTransactionManager(boolean autodetectTransactionManager this.autodetectTransactionManager = autodetectTransactionManager; } + /** + * Set the JTA 1.1 TransactionSynchronizationRegistry to use as direct reference. + *

    A TransactionSynchronizationRegistry allows for interposed registration + * of transaction synchronizations, as an alternative to the regular registration + * methods on the JTA TransactionManager API. Also, it is an official part of the + * Java EE 5 platform, in contrast to the JTA TransactionManager itself. + *

    Note that the TransactionSynchronizationRegistry will be autodetected in JNDI and + * also from the UserTransaction/TransactionManager object if implemented there as well. + * @see #setTransactionSynchronizationRegistryName + * @see #setAutodetectTransactionSynchronizationRegistry + */ + public void setTransactionSynchronizationRegistry(TransactionSynchronizationRegistry transactionSynchronizationRegistry) { + this.transactionSynchronizationRegistry = transactionSynchronizationRegistry; + } + + /** + * Return the JTA 1.1 TransactionSynchronizationRegistry that this transaction manager uses, if any. + */ + public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() { + return this.transactionSynchronizationRegistry; + } + /** * Set the JNDI name of the JTA 1.1 TransactionSynchronizationRegistry. *

    Note that the TransactionSynchronizationRegistry will be autodetected @@ -374,6 +398,20 @@ public void setTransactionSynchronizationRegistryName(String transactionSynchron this.transactionSynchronizationRegistryName = transactionSynchronizationRegistryName; } + /** + * Set whether to autodetect a JTA 1.1 TransactionSynchronizationRegistry object + * at its default JDNI location (""java:comp/TransactionSynchronizationRegistry"") + * if the UserTransaction has also been obtained from JNDI, and also whether + * to fall back to checking whether the JTA UserTransaction/TransactionManager + * object implements the JTA TransactionSynchronizationRegistry interface too. + *

    Default is ""true"", autodetecting the TransactionSynchronizationRegistry + * unless it has been specified explicitly. Can be turned off to delegate + * synchronization registration to the regular JTA TransactionManager API. + */ + public void setAutodetectTransactionSynchronizationRegistry(boolean autodetectTransactionSynchronizationRegistry) { + this.autodetectTransactionSynchronizationRegistry = autodetectTransactionSynchronizationRegistry; + } + /** * Set whether to allow custom isolation levels to be specified. *

    Default is ""false"", throwing an exception if a non-default isolation level @@ -404,38 +442,36 @@ public void afterPropertiesSet() throws TransactionSystemException { * @throws TransactionSystemException if initialization failed */ protected void initUserTransactionAndTransactionManager() throws TransactionSystemException { - // Fetch JTA UserTransaction from JNDI, if necessary. if (this.userTransaction == null) { + // Fetch JTA UserTransaction from JNDI, if necessary. if (StringUtils.hasLength(this.userTransactionName)) { this.userTransaction = lookupUserTransaction(this.userTransactionName); this.userTransactionObtainedFromJndi = true; } else { this.userTransaction = retrieveUserTransaction(); + if (this.userTransaction == null && this.autodetectUserTransaction) { + // Autodetect UserTransaction at its default JNDI location. + this.userTransaction = findUserTransaction(); + } } } - // Fetch JTA TransactionManager from JNDI, if necessary. if (this.transactionManager == null) { + // Fetch JTA TransactionManager from JNDI, if necessary. if (StringUtils.hasLength(this.transactionManagerName)) { this.transactionManager = lookupTransactionManager(this.transactionManagerName); } else { this.transactionManager = retrieveTransactionManager(); + if (this.transactionManager == null && this.autodetectTransactionManager) { + // Autodetect UserTransaction object that implements TransactionManager, + // and check fallback JNDI locations otherwise. + this.transactionManager = findTransactionManager(this.userTransaction); + } } } - // Autodetect UserTransaction at its default JNDI location. - if (this.userTransaction == null && this.autodetectUserTransaction) { - this.userTransaction = findUserTransaction(); - } - - // Autodetect UserTransaction object that implements TransactionManager, - // and check fallback JNDI locations else. - if (this.transactionManager == null && this.autodetectTransactionManager) { - this.transactionManager = findTransactionManager(this.userTransaction); - } - // If only JTA TransactionManager specified, create UserTransaction handle for it. if (this.userTransaction == null && this.transactionManager != null) { this.userTransaction = buildUserTransaction(this.transactionManager); @@ -477,15 +513,20 @@ protected void checkUserTransactionAndTransactionManager() throws IllegalStateEx * @throws TransactionSystemException if initialization failed */ protected void initTransactionSynchronizationRegistry() { - if (StringUtils.hasLength(this.transactionSynchronizationRegistryName)) { - this.transactionSynchronizationRegistry = - lookupTransactionSynchronizationRegistry(this.transactionSynchronizationRegistryName); - } - else { - this.transactionSynchronizationRegistry = retrieveTransactionSynchronizationRegistry(); - if (this.transactionSynchronizationRegistry == null) { + if (this.transactionSynchronizationRegistry == null) { + // Fetch JTA TransactionSynchronizationRegistry from JNDI, if necessary. + if (StringUtils.hasLength(this.transactionSynchronizationRegistryName)) { this.transactionSynchronizationRegistry = - findTransactionSynchronizationRegistry(this.userTransaction, this.transactionManager); + lookupTransactionSynchronizationRegistry(this.transactionSynchronizationRegistryName); + } + else { + this.transactionSynchronizationRegistry = retrieveTransactionSynchronizationRegistry(); + if (this.transactionSynchronizationRegistry == null && this.autodetectTransactionSynchronizationRegistry) { + // Autodetect in JNDI if applicable, and check UserTransaction/TransactionManager + // object that implements TransactionSynchronizationRegistry otherwise. + this.transactionSynchronizationRegistry = + findTransactionSynchronizationRegistry(this.userTransaction, this.transactionManager); + } } }" a8dbce159679cd031f60e6151399fa2cd5ac9374,hadoop,HADOOP-7223. FileContext createFlag combinations- are not clearly defined. Contributed by Suresh Srinivas.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1092565 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index a6186537bdbb6..7a2ece8c71744 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,4 @@ -Hadoop Change Log +Hn jaadoop Change Log Trunk (unreleased changes) @@ -139,6 +139,10 @@ Trunk (unreleased changes) HADOOP-7207. fs member of FSShell is not really needed (boryas) + HADOOP-7223. FileContext createFlag combinations are not clearly defined. + (suresh) + + Release 0.22.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/ChecksumFs.java b/src/java/org/apache/hadoop/fs/ChecksumFs.java index a55108598becd..87cd5a77dec39 100644 --- a/src/java/org/apache/hadoop/fs/ChecksumFs.java +++ b/src/java/org/apache/hadoop/fs/ChecksumFs.java @@ -337,8 +337,9 @@ public ChecksumFSOutputSummer(final ChecksumFs fs, final Path file, int bytesPerSum = fs.getBytesPerSum(); int sumBufferSize = fs.getSumBufferSize(bytesPerSum, bufferSize); this.sums = fs.getRawFs().createInternal(fs.getChecksumFile(file), - EnumSet.of(CreateFlag.OVERWRITE), absolutePermission, sumBufferSize, - replication, blockSize, progress, bytesPerChecksum, createParent); + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), + absolutePermission, sumBufferSize, replication, blockSize, progress, + bytesPerChecksum, createParent); sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length); sums.writeInt(bytesPerSum); } diff --git a/src/java/org/apache/hadoop/fs/CreateFlag.java b/src/java/org/apache/hadoop/fs/CreateFlag.java index 375876a8bdb40..4373124caabf4 100644 --- a/src/java/org/apache/hadoop/fs/CreateFlag.java +++ b/src/java/org/apache/hadoop/fs/CreateFlag.java @@ -17,49 +17,63 @@ */ package org.apache.hadoop.fs; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.EnumSet; + +import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /**************************************************************** - *CreateFlag specifies the file create semantic. Users can combine flags like:
    - * + * CreateFlag specifies the file create semantic. Users can combine flags like:
    + * * EnumSet.of(CreateFlag.CREATE, CreateFlag.APPEND) * - * and pass it to {@link org.apache.hadoop.fs.FileSystem #create(Path f, FsPermission permission, - * EnumSet flag, int bufferSize, short replication, long blockSize, - * Progressable progress)}. - * *

    - * Combine {@link #OVERWRITE} with either {@link #CREATE} - * or {@link #APPEND} does the same as only use - * {@link #OVERWRITE}.
    - * Combine {@link #CREATE} with {@link #APPEND} has the semantic: + * + * Use the CreateFlag as follows: + *

      + *
    1. CREATE - to create a file if it does not exist, + * else throw FileAlreadyExists.
    2. + *
    3. APPEND - to append to a file if it exists, + * else throw FileNotFoundException.
    4. + *
    5. OVERWRITE - to truncate a file if it exists, + * else throw FileNotFoundException.
    6. + *
    7. CREATE|APPEND - to create a file if it does not exist, + * else append to an existing file.
    8. + *
    9. CREATE|OVERWRITE - to create a file if it does not exist, + * else overwrite an existing file.
    10. + *
    + * + * Following combination is not valid and will result in + * {@link HadoopIllegalArgumentException}: *
      - *
    1. create the file if it does not exist; - *
    2. append the file if it already exists. + *
    3. APPEND|OVERWRITE
    4. + *
    5. CREATE|APPEND|OVERWRITE
    6. *
    *****************************************************************/ @InterfaceAudience.Public -@InterfaceStability.Stable +@InterfaceStability.Evolving public enum CreateFlag { /** - * create the file if it does not exist, and throw an IOException if it + * Create a file. See javadoc for more description * already exists */ CREATE((short) 0x01), /** - * create the file if it does not exist, if it exists, overwrite it. + * Truncate/overwrite a file. Same as POSIX O_TRUNC. See javadoc for description. */ OVERWRITE((short) 0x02), /** - * append to a file, and throw an IOException if it does not exist + * Append to a file. See javadoc for more description. */ APPEND((short) 0x04); - private short mode; + private final short mode; private CreateFlag(short mode) { this.mode = mode; @@ -68,4 +82,49 @@ private CreateFlag(short mode) { short getMode() { return mode; } + + /** + * Validate the CreateFlag and throw exception if it is invalid + * @param flag set of CreateFlag + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(EnumSet flag) { + if (flag == null || flag.isEmpty()) { + throw new HadoopIllegalArgumentException(flag + + "" does not specify any options""); + } + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + + // Both append and overwrite is an error + if (append && overwrite) { + throw new HadoopIllegalArgumentException( + flag + ""Both append and overwrite options cannot be enabled.""); + } + } + + /** + * Validate the CreateFlag for create operation + * @param path Object representing the path; usually String or {@link Path} + * @param pathExists pass true if the path exists in the file system + * @param flag set of CreateFlag + * @throws IOException on error + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(Object path, boolean pathExists, + EnumSet flag) throws IOException { + validate(flag); + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + if (pathExists) { + if (!(append || overwrite)) { + throw new FileAlreadyExistsException(""File already exists: "" + + path.toString() + + "". Append or overwrite option must be specified in "" + flag); + } + } else if (!flag.contains(CREATE)) { + throw new FileNotFoundException(""Non existing file: "" + path.toString() + + "". Create option is not specified in "" + flag); + } + } } \ No newline at end of file diff --git a/src/java/org/apache/hadoop/fs/FileContext.java b/src/java/org/apache/hadoop/fs/FileContext.java index 2596daae5e7b4..e3163ea75e5b7 100644 --- a/src/java/org/apache/hadoop/fs/FileContext.java +++ b/src/java/org/apache/hadoop/fs/FileContext.java @@ -511,7 +511,7 @@ public Path makeQualified(final Path path) { * writing into the file. * * @param f the file name to open - * @param createFlag gives the semantics of create: overwrite, append etc. + * @param createFlag gives the semantics of create; see {@link CreateFlag} * @param opts file creation options; see {@link Options.CreateOpts}. *
      *
    • Progress - to report progress on the operation - default null @@ -2057,7 +2057,10 @@ public boolean copy(final Path src, final Path dst, boolean deleteSource, OutputStream out = null; try { in = open(qSrc); - out = create(qDst, EnumSet.of(CreateFlag.OVERWRITE)); + EnumSet createFlag = overwrite ? EnumSet.of( + CreateFlag.CREATE, CreateFlag.OVERWRITE) : + EnumSet.of(CreateFlag.CREATE); + out = create(qDst, createFlag); IOUtils.copyBytes(in, out, conf, true); } catch (IOException e) { IOUtils.closeStream(out); diff --git a/src/java/org/apache/hadoop/fs/FileSystem.java b/src/java/org/apache/hadoop/fs/FileSystem.java index be1c796a4caa3..8708b7d62de03 100644 --- a/src/java/org/apache/hadoop/fs/FileSystem.java +++ b/src/java/org/apache/hadoop/fs/FileSystem.java @@ -717,24 +717,21 @@ protected FSDataOutputStream primitiveCreate(Path f, FsPermission absolutePermission, EnumSet flag, int bufferSize, short replication, long blockSize, Progressable progress, int bytesPerChecksum) throws IOException { + + boolean pathExists = exists(f); + CreateFlag.validate(f, pathExists, flag); // Default impl assumes that permissions do not matter and // nor does the bytesPerChecksum hence // calling the regular create is good enough. // FSs that implement permissions should override this. - if (exists(f)) { - if (flag.contains(CreateFlag.APPEND)) { - return append(f, bufferSize, progress); - } else if (!flag.contains(CreateFlag.OVERWRITE)) { - throw new IOException(""File already exists: "" + f); - } - } else { - if (flag.contains(CreateFlag.APPEND) && !flag.contains(CreateFlag.CREATE)) - throw new IOException(""File already exists: "" + f.toString()); + if (pathExists && flag.contains(CreateFlag.APPEND)) { + return append(f, bufferSize, progress); } - return this.create(f, absolutePermission, flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, + return this.create(f, absolutePermission, + flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, blockSize, progress); } diff --git a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java index 18ef152baf35c..3a54fae955b7e 100644 --- a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java +++ b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java @@ -264,28 +264,6 @@ public FSDataOutputStream create(Path f, FsPermission permission, return out; } - - @Override - protected FSDataOutputStream primitiveCreate(Path f, - FsPermission absolutePermission, EnumSet flag, - int bufferSize, short replication, long blockSize, Progressable progress, - int bytesPerChecksum) throws IOException { - - if(flag.contains(CreateFlag.APPEND)){ - if (!exists(f)){ - if(flag.contains(CreateFlag.CREATE)) { - return create(f, false, bufferSize, replication, blockSize, null); - } - } - return append(f, bufferSize, null); - } - - FSDataOutputStream out = create(f, flag.contains(CreateFlag.OVERWRITE), - bufferSize, replication, blockSize, progress); - setPermission(f, absolutePermission); - return out; - } - public boolean rename(Path src, Path dst) throws IOException { if (pathToFile(src).renameTo(pathToFile(dst))) { return true; diff --git a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java index 1af5a6391bca2..b88f5b5c5d9ae 100644 --- a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java +++ b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java @@ -21,8 +21,8 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.EnumSet; -import java.util.Iterator; +import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.fs.Options.CreateOpts; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.permission.FsPermission; @@ -32,6 +32,7 @@ import org.junit.Test; import static org.apache.hadoop.fs.FileContextTestHelper.*; +import static org.apache.hadoop.fs.CreateFlag.*; /** *

      @@ -155,7 +156,7 @@ public void testWorkingDirectory() throws Exception { // Now open a file relative to the wd we just set above. Path absolutePath = new Path(absoluteDir, ""foo""); - fc.create(absolutePath, EnumSet.of(CreateFlag.CREATE)).close(); + fc.create(absolutePath, EnumSet.of(CREATE)).close(); fc.open(new Path(""foo"")).close(); @@ -645,7 +646,7 @@ private void writeReadAndDelete(int len) throws IOException { fc.mkdir(path.getParent(), FsPermission.getDefault(), true); - FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), CreateOpts.repFac((short) 1), CreateOpts .blockSize(getDefaultBlockSize())); out.write(data, 0, len); @@ -670,31 +671,93 @@ private void writeReadAndDelete(int len) throws IOException { } + @Test(expected=HadoopIllegalArgumentException.class) + public void testNullCreateFlag() throws IOException { + Path p = getTestRootPath(fc, ""test/file""); + fc.create(p, null); + Assert.fail(""Excepted exception not thrown""); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testEmptyCreateFlag() throws IOException { + Path p = getTestRootPath(fc, ""test/file""); + fc.create(p, EnumSet.noneOf(CreateFlag.class)); + Assert.fail(""Excepted exception not thrown""); + } + + @Test(expected=FileAlreadyExistsException.class) + public void testCreateFlagCreateExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagCreateExistingFile""); + createFile(p); + fc.create(p, EnumSet.of(CREATE)); + Assert.fail(""Excepted exception not thrown""); + } + + @Test(expected=FileNotFoundException.class) + public void testCreateFlagOverwriteNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagOverwriteNonExistingFile""); + fc.create(p, EnumSet.of(OVERWRITE)); + Assert.fail(""Excepted exception not thrown""); + } + @Test - public void testOverwrite() throws IOException { - Path path = getTestRootPath(fc, ""test/hadoop/file""); - - fc.mkdir(path.getParent(), FsPermission.getDefault(), true); - - createFile(path); - - Assert.assertTrue(""Exists"", exists(fc, path)); - Assert.assertEquals(""Length"", data.length, fc.getFileStatus(path).getLen()); - - try { - fc.create(path, EnumSet.of(CreateFlag.CREATE)); - Assert.fail(""Should throw IOException.""); - } catch (IOException e) { - // Expected - } - - FSDataOutputStream out = fc.create(path,EnumSet.of(CreateFlag.OVERWRITE)); + public void testCreateFlagOverwriteExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagOverwriteExistingFile""); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(OVERWRITE)); + writeData(fc, p, out, data, data.length); + } + + @Test(expected=FileNotFoundException.class) + public void testCreateFlagAppendNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagAppendNonExistingFile""); + fc.create(p, EnumSet.of(APPEND)); + Assert.fail(""Excepted exception not thrown""); + } + + @Test + public void testCreateFlagAppendExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagAppendExistingFile""); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(APPEND)); + writeData(fc, p, out, data, 2 * data.length); + } + + @Test + public void testCreateFlagCreateAppendNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagCreateAppendNonExistingFile""); + FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); + writeData(fc, p, out, data, data.length); + } + + @Test + public void testCreateFlagCreateAppendExistingFile() throws IOException { + Path p = getTestRootPath(fc, ""test/testCreateFlagCreateAppendExistingFile""); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); + writeData(fc, p, out, data, 2*data.length); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testCreateFlagAppendOverwrite() throws IOException { + Path p = getTestRootPath(fc, ""test/nonExistent""); + fc.create(p, EnumSet.of(APPEND, OVERWRITE)); + Assert.fail(""Excepted exception not thrown""); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testCreateFlagAppendCreateOverwrite() throws IOException { + Path p = getTestRootPath(fc, ""test/nonExistent""); + fc.create(p, EnumSet.of(CREATE, APPEND, OVERWRITE)); + Assert.fail(""Excepted exception not thrown""); + } + + private static void writeData(FileContext fc, Path p, FSDataOutputStream out, + byte[] data, long expectedLen) throws IOException { out.write(data, 0, data.length); out.close(); - - Assert.assertTrue(""Exists"", exists(fc, path)); - Assert.assertEquals(""Length"", data.length, fc.getFileStatus(path).getLen()); - + Assert.assertTrue(""Exists"", exists(fc, p)); + Assert.assertEquals(""Length"", expectedLen, fc.getFileStatus(p).getLen()); } @Test @@ -1057,7 +1120,7 @@ public void testOutputStreamClosedTwice() throws IOException { //HADOOP-4760 according to Closeable#close() closing already-closed //streams should have no effect. Path src = getTestRootPath(fc, ""test/hadoop/file""); - FSDataOutputStream out = fc.create(src, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(src, EnumSet.of(CREATE), Options.CreateOpts.createParent()); out.writeChar('H'); //write some data @@ -1091,7 +1154,7 @@ public void testUnsupportedSymlink() throws IOException { } protected void createFile(Path path) throws IOException { - FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), Options.CreateOpts.createParent()); out.write(data, 0, data.length); out.close(); diff --git a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java index 97342951579ca..5124211d344db 100644 --- a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java +++ b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java @@ -140,7 +140,8 @@ private void genFiles() throws IOException { * a length of fileSize. The file is filled with character 'a'. */ private void genFile(Path file, long fileSize) throws IOException { - FSDataOutputStream out = fc.create(file, EnumSet.of(CreateFlag.OVERWRITE), + FSDataOutputStream out = fc.create(file, + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), CreateOpts.createParent(), CreateOpts.bufferSize(4096), CreateOpts.repFac((short) 3)); for(long i=0; i HostName */ + private HashMap reverseDNSCacheMap = + new HashMap(); + + /** The NameServer address */ + private String nameServer = null; + /** * Builds a TableRecordReader. If no TableRecordReader was provided, uses * the default. @@ -128,6 +142,10 @@ public List getSplits(JobContext context) throws IOException { if (table == null) { throw new IOException(""No table was provided.""); } + // Get the name server address and the default value is null. + this.nameServer = + context.getConfiguration().get(""hbase.nameserver.address"", null); + Pair keys = table.getStartEndKeys(); if (keys == null || keys.getFirst() == null || keys.getFirst().length == 0) { @@ -138,13 +156,24 @@ public List getSplits(JobContext context) throws IOException { if ( !includeRegionInSplit(keys.getFirst()[i], keys.getSecond()[i])) { continue; } - String regionLocation = table.getRegionLocation(keys.getFirst()[i]). - getHostname(); - byte[] startRow = scan.getStartRow(); - byte[] stopRow = scan.getStopRow(); - // determine if the given start an stop key fall into the region + HServerAddress regionServerAddress = + table.getRegionLocation(keys.getFirst()[i]).getServerAddress(); + InetAddress regionAddress = + regionServerAddress.getInetSocketAddress().getAddress(); + String regionLocation; + try { + regionLocation = reverseDNS(regionAddress); + } catch (NamingException e) { + LOG.error(""Cannot resolve the host name for "" + regionAddress + + "" because of "" + e); + regionLocation = regionServerAddress.getHostname(); + } + + byte[] startRow = scan.getStartRow(); + byte[] stopRow = scan.getStopRow(); + // determine if the given start an stop key fall into the region if ((startRow.length == 0 || keys.getSecond()[i].length == 0 || - Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) && + Bytes.compareTo(startRow, keys.getSecond()[i]) < 0) && (stopRow.length == 0 || Bytes.compareTo(stopRow, keys.getFirst()[i]) > 0)) { byte[] splitStart = startRow.length == 0 || @@ -164,6 +193,15 @@ public List getSplits(JobContext context) throws IOException { } return splits; } + + private String reverseDNS(InetAddress ipAddress) throws NamingException { + String hostName = this.reverseDNSCacheMap.get(ipAddress); + if (hostName == null) { + hostName = DNS.reverseDns(ipAddress, this.nameServer); + this.reverseDNSCacheMap.put(ipAddress, hostName); + } + return hostName; + } /** *" a82c6167163a27223548b1aa6b8cc1b720c33073,drools,"JBRULES-2537 JSon Marshaller -Added JSon marshaller- using xstream, with unit tests.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@33359 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-",a,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java b/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java index d9e560b55a7..bf808e6e071 100644 --- a/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java +++ b/drools-core/src/main/java/org/drools/base/ClassFieldAccessorFactory.java @@ -142,13 +142,12 @@ public BaseClassFieldReader getClassFieldReader(final Class< ? > clazz, final Object[] params = {index, fieldType, valueType}; return (BaseClassFieldReader) newClass.getConstructors()[0].newInstance( params ); } else { - throw new RuntimeDroolsException( ""Field/method '"" + fieldName + ""' not found for class '"" + clazz.getName() + ""'"" ); + throw new RuntimeDroolsException( ""Field/method '"" + fieldName + ""' not found for class '"" + clazz.getName() + ""'\n"" ); } } } catch ( final RuntimeDroolsException e ) { throw e; } catch ( final Exception e ) { -// e.printStackTrace(); throw new RuntimeDroolsException( e ); } } diff --git a/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java b/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java index 76e4acf98f3..8d0197359c3 100644 --- a/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java +++ b/drools-core/src/main/java/org/drools/command/runtime/GetGlobalCommand.java @@ -41,6 +41,12 @@ public void setOutIdentifier(String outIdentifier) { public String getIdentifier() { return identifier; } + + + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } public Object execute(Context context) { StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession(); diff --git a/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java b/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java index 14915f90a89..d34e3dedf6d 100644 --- a/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java +++ b/drools-core/src/main/java/org/drools/command/runtime/SetGlobalCommand.java @@ -54,6 +54,10 @@ public Void execute(Context context) { public String getIdentifier() { return this.identifier; } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } public Object getObject() { return this.object; diff --git a/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java b/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java index 3a62f3b56b9..01ac7ed3f40 100644 --- a/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java +++ b/drools-core/src/main/java/org/drools/command/runtime/rule/InsertObjectCommand.java @@ -1,5 +1,7 @@ package org.drools.command.runtime.rule; +import java.io.ObjectStreamException; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -89,5 +91,10 @@ public void setReturnObject(boolean returnObject) { public String toString() { return ""session.insert("" + object + "");""; } + +// private Object readResolve() throws ObjectStreamException { +// this.returnObject = true; +// return this; +// } } diff --git a/drools-core/src/main/java/org/drools/core/util/StringUtils.java b/drools-core/src/main/java/org/drools/core/util/StringUtils.java index acc61e42095..906217f6c99 100644 --- a/drools-core/src/main/java/org/drools/core/util/StringUtils.java +++ b/drools-core/src/main/java/org/drools/core/util/StringUtils.java @@ -17,7 +17,10 @@ * limitations under the License. */ +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; @@ -1184,4 +1187,29 @@ public static String deleteAny(String inString, String charsToDelete) { } return out.toString(); } + + public static String toString(Reader reader) throws IOException { + if ( reader instanceof BufferedReader ) { + return toString( (BufferedReader) reader ); + } else { + return toString( new BufferedReader( reader ) ); + } + } + + public static String toString(InputStream is) throws IOException { + return toString( new BufferedReader(new InputStreamReader(is, ""UTF-8"") ) ); + } + + public static String toString(BufferedReader reader) throws IOException { + StringBuilder sb = new StringBuilder(); + try { + String line; + while ((line = reader.readLine()) != null) { + sb.append(line).append(""\n""); + } + } finally { + reader.close(); + } + return sb.toString(); + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java b/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java index bac8bda0437..96b13b255b1 100644 --- a/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/BatchExecutionHelperProviderImpl.java @@ -1,1052 +1,23 @@ package org.drools.runtime.help.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.drools.base.ClassObjectType; -import org.drools.base.DroolsQuery; -import org.drools.command.Command; -import org.drools.command.CommandFactory; -import org.drools.command.Setter; -import org.drools.command.runtime.BatchExecutionCommand; -import org.drools.command.runtime.GetGlobalCommand; -import org.drools.command.runtime.SetGlobalCommand; -import org.drools.command.runtime.process.AbortWorkItemCommand; -import org.drools.command.runtime.process.CompleteWorkItemCommand; -import org.drools.command.runtime.process.SignalEventCommand; -import org.drools.command.runtime.process.StartProcessCommand; -import org.drools.command.runtime.rule.FireAllRulesCommand; -import org.drools.command.runtime.rule.GetObjectCommand; -import org.drools.command.runtime.rule.GetObjectsCommand; -import org.drools.command.runtime.rule.InsertElementsCommand; -import org.drools.command.runtime.rule.InsertObjectCommand; -import org.drools.command.runtime.rule.ModifyCommand; -import org.drools.command.runtime.rule.QueryCommand; -import org.drools.command.runtime.rule.RetractCommand; -import org.drools.common.DefaultFactHandle; -import org.drools.common.DisconnectedFactHandle; -import org.drools.rule.Declaration; -import org.drools.runtime.ExecutionResults; import org.drools.runtime.help.BatchExecutionHelperProvider; -import org.drools.runtime.impl.ExecutionResultImpl; -import org.drools.runtime.rule.FactHandle; -import org.drools.runtime.rule.QueryResults; -import org.drools.runtime.rule.QueryResultsRow; -import org.drools.runtime.rule.impl.FlatQueryResults; -import org.drools.runtime.rule.impl.NativeQueryResults; -import org.drools.spi.ObjectType; import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.MarshallingContext; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import com.thoughtworks.xstream.mapper.Mapper; public class BatchExecutionHelperProviderImpl implements BatchExecutionHelperProvider { - - public XStream newXStreamMarshaller() { - return newXStreamMarshaller( new XStream()); - } - - public XStream newXStreamMarshaller(XStream xstream) { - ElementNames names = new XmlElementNames(); - - // xstream.setMode( XStream.NO_REFERENCES ); - xstream.processAnnotations( BatchExecutionCommand.class ); - xstream.addImplicitCollection( BatchExecutionCommand.class, - ""commands"" ); - - xstream.alias( ""batch-execution"", - BatchExecutionCommand.class ); - xstream.alias( ""insert"", - InsertObjectCommand.class ); - xstream.alias( ""modify"", - ModifyCommand.class ); - xstream.alias( ""retract"", - RetractCommand.class ); - xstream.alias( ""insert-elements"", - InsertElementsCommand.class ); - xstream.alias( ""start-process"", - StartProcessCommand.class ); - xstream.alias( ""signal-event"", - SignalEventCommand.class ); - xstream.alias( ""complete-work-item"", - CompleteWorkItemCommand.class ); - xstream.alias( ""abort-work-item"", - AbortWorkItemCommand.class ); - xstream.alias( ""set-global"", - SetGlobalCommand.class ); - xstream.alias( ""get-global"", - GetGlobalCommand.class ); - xstream.alias( ""get-object"", - GetObjectCommand.class ); - xstream.alias( ""get-objects"", - GetObjectsCommand.class ); - xstream.alias( ""execution-results"", - ExecutionResultImpl.class ); - xstream.alias( ""fire-all-rules"", - FireAllRulesCommand.class ); - xstream.alias( ""query"", - QueryCommand.class ); - xstream.alias( ""query-results"", - FlatQueryResults.class ); - xstream.alias( ""query-results"", - NativeQueryResults.class ); - xstream.alias(""fact-handle"", DefaultFactHandle.class); - - xstream.registerConverter( new InsertConverter( xstream.getMapper() ) ); - xstream.registerConverter( new RetractConverter( xstream.getMapper() ) ); - xstream.registerConverter( new ModifyConverter( xstream.getMapper() ) ); - xstream.registerConverter( new GetObjectConverter( xstream.getMapper() ) ); - xstream.registerConverter( new InsertElementsConverter( xstream.getMapper() ) ); - xstream.registerConverter( new FireAllRulesConverter( xstream.getMapper() ) ); - xstream.registerConverter( new StartProcessConvert( xstream.getMapper() ) ); - xstream.registerConverter( new SignalEventConverter( xstream.getMapper() ) ); - xstream.registerConverter( new CompleteWorkItemConverter( xstream.getMapper() ) ); - xstream.registerConverter( new AbortWorkItemConverter( xstream.getMapper() ) ); - xstream.registerConverter( new QueryConverter( xstream.getMapper() ) ); - xstream.registerConverter( new SetGlobalConverter( xstream.getMapper() ) ); - xstream.registerConverter( new GetGlobalConverter( xstream.getMapper() ) ); - xstream.registerConverter( new GetObjectsConverter( xstream.getMapper() ) ); - xstream.registerConverter( new BatchExecutionResultConverter( xstream.getMapper() ) ); - xstream.registerConverter( new QueryResultsConverter( xstream.getMapper() ) ); - xstream.registerConverter( new FactHandleConverter(xstream.getMapper())); - - return xstream; - } - - public static interface ElementNames { - public String getIn(); - - public String getInOut(); - - public String getOut(); - } - - public static class JsonElementNames - implements - ElementNames { - private String in = ""in""; - private String inOut = ""inOut""; - private String out = ""out""; - - public String getIn() { - return in; - } - - public String getInOut() { - return inOut; - } - - public String getOut() { - return out; - } - } - - public static class XmlElementNames - implements - ElementNames { - private String in = ""in""; - private String inOut = ""in-out""; - private String out = ""out""; - - public String getIn() { - return in; - } - - public String getInOut() { - return inOut; - } - - public String getOut() { - return out; - } - } - - public static class InsertConverter extends AbstractCollectionConverter - implements - Converter { - - public InsertConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - InsertObjectCommand cmd = (InsertObjectCommand) object; - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - - writer.addAttribute( ""return-object"", - Boolean.toString( cmd.isReturnObject() ) ); - - } - writeItem( cmd.getObject(), - context, - writer ); - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String identifierOut = reader.getAttribute( ""out-identifier"" ); - String returnObject = reader.getAttribute( ""return-object"" ); - - reader.moveDown(); - Object object = readItem( reader, - context, - null ); - reader.moveUp(); - InsertObjectCommand cmd = new InsertObjectCommand( object ); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - if ( returnObject != null ) { - cmd.setReturnObject( Boolean.parseBoolean( returnObject ) ); - } - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( InsertObjectCommand.class ); - } - - } - - public static class FactHandleConverter extends AbstractCollectionConverter - implements - Converter { - public FactHandleConverter(Mapper mapper) { - super(mapper); - } - - public boolean canConvert(Class aClass) { - return FactHandle.class.isAssignableFrom(aClass); - } - - public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) { - FactHandle fh = (FactHandle) object; - //writer.startNode(""fact-handle""); - writer.addAttribute(""externalForm"", fh.toExternalForm()); - //writer.endNode(); - } - - public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) { - throw new UnsupportedOperationException(""Unable to unmarshal fact handles.""); - } - } - - public static class ModifyConverter extends AbstractCollectionConverter - implements - Converter { - - public ModifyConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - ModifyCommand cmd = (ModifyCommand) object; - - writer.addAttribute( ""factHandle"", - cmd.getFactHandle().toExternalForm() ); - - for ( Setter setter : cmd.getSetters() ) { - writer.startNode( ""set"" ); - writer.addAttribute( ""accessor"", - setter.getAccessor() ); - writer.addAttribute( ""value"", - setter.getValue() ); - writer.endNode(); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""factHandle"" ) ); - - List setters = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - Setter setter = CommandFactory.newSetter( reader.getAttribute( ""accessor"" ), - reader.getAttribute( ""value"" ) ); - setters.add( setter ); - reader.moveUp(); - } - - Command cmd = CommandFactory.newModify( factHandle, - setters ); - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( ModifyCommand.class ); - } - - } - - public static class RetractConverter extends AbstractCollectionConverter - implements - Converter { - - public RetractConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - RetractCommand cmd = (RetractCommand) object; - - writer.addAttribute( ""factHandle"", - cmd.getFactHandle().toExternalForm() ); - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""factHandle"" ) ); - - Command cmd = CommandFactory.newRetract( factHandle ); - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( RetractCommand.class ); - } - } - - public static class InsertElementsConverter extends AbstractCollectionConverter - implements - Converter { - - public InsertElementsConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - InsertElementsCommand cmd = (InsertElementsCommand) object; - - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - - writer.addAttribute( ""return-objects"", - Boolean.toString( cmd.isReturnObject() ) ); - - } - - for ( Object element : cmd.getObjects() ) { - writeItem( element, - context, - writer ); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String identifierOut = reader.getAttribute( ""out-identifier"" ); - String returnObject = reader.getAttribute( ""return-objects"" ); - - List objects = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - Object object = readItem( reader, - context, - null ); - reader.moveUp(); - objects.add( object ); - } - - InsertElementsCommand cmd = new InsertElementsCommand( objects ); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - if ( returnObject != null ) { - cmd.setReturnObject( Boolean.parseBoolean( returnObject ) ); - } - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( InsertElementsCommand.class ); - } - - } - - public static class SetGlobalConverter extends AbstractCollectionConverter - implements - Converter { - - public SetGlobalConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - SetGlobalCommand cmd = (SetGlobalCommand) object; - - writer.addAttribute( ""identifier"", - cmd.getIdentifier() ); - - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - } else if ( cmd.isOut() ) { - writer.addAttribute( ""out"", - Boolean.toString( cmd.isOut() ) ); - } - - writeItem( cmd.getObject(), - context, - writer ); - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String identifier = reader.getAttribute( ""identifier"" ); - String out = reader.getAttribute( ""out"" ); - String identifierOut = reader.getAttribute( ""out-identifier"" ); - - reader.moveDown(); - Object object = readItem( reader, - context, - null ); - reader.moveUp(); - SetGlobalCommand cmd = new SetGlobalCommand( identifier, - object ); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - } else if ( out != null ) { - cmd.setOut( Boolean.parseBoolean( out ) ); - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( SetGlobalCommand.class ); - } - } - - public static class GetObjectConverter extends AbstractCollectionConverter - implements - Converter { - - public GetObjectConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - GetObjectCommand cmd = (GetObjectCommand) object; - - writer.addAttribute( ""factHandle"", - cmd.getFactHandle().toExternalForm() ); - - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""factHandle"" ) ); - String identifierOut = reader.getAttribute( ""out-identifier"" ); - - GetObjectCommand cmd = new GetObjectCommand( factHandle ); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( GetObjectCommand.class ); - } - } - - public static class GetGlobalConverter extends AbstractCollectionConverter - implements - Converter { - - public GetGlobalConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - GetGlobalCommand cmd = (GetGlobalCommand) object; - writer.addAttribute( ""identifier"", - cmd.getIdentifier() ); - - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String identifier = reader.getAttribute( ""identifier"" ); - String identifierOut = reader.getAttribute( ""out-identifier"" ); - - GetGlobalCommand cmd = new GetGlobalCommand( identifier ); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( GetGlobalCommand.class ); - } - } - - public static class GetObjectsConverter extends AbstractCollectionConverter - implements - Converter { - - public GetObjectsConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - GetObjectsCommand cmd = (GetObjectsCommand) object; - - if ( cmd.getOutIdentifier() != null ) { - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String identifierOut = reader.getAttribute( ""out-identifier"" ); - - GetObjectsCommand cmd = new GetObjectsCommand(); - if ( identifierOut != null ) { - cmd.setOutIdentifier( identifierOut ); - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( GetObjectsCommand.class ); - } - } - - public static class FireAllRulesConverter extends AbstractCollectionConverter - implements - Converter { - - public FireAllRulesConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - FireAllRulesCommand cmd = (FireAllRulesCommand) object; - - if ( cmd.getMax() != -1 ) { - writer.addAttribute( ""max"", - Integer.toString( cmd.getMax() ) ); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String max = reader.getAttribute( ""max"" ); - - FireAllRulesCommand cmd = null; - - if ( max != null ) { - cmd = new FireAllRulesCommand( Integer.parseInt( max ) ); - } else { - cmd = new FireAllRulesCommand(); - } - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( FireAllRulesCommand.class ); - } - } - - public static class QueryConverter extends AbstractCollectionConverter - implements - Converter { - - public QueryConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - QueryCommand cmd = (QueryCommand) object; - writer.addAttribute( ""out-identifier"", - cmd.getOutIdentifier() ); - writer.addAttribute( ""name"", - cmd.getName() ); - if ( cmd.getArguments() != null ) { - for ( Object arg : cmd.getArguments() ) { - writeItem( arg, - context, - writer ); - } - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - List outs = new ArrayList(); - - // Query cmd = null; - String outIdentifier = reader.getAttribute( ""out-identifier"" ); - String name = reader.getAttribute( ""name"" ); - List args = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - Object arg = readItem( reader, - context, - null ); - args.add( arg ); - reader.moveUp(); - } - QueryCommand cmd = new QueryCommand( outIdentifier, - name, - args.toArray( new Object[args.size()] ) ); - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( QueryCommand.class ); - } - } - - public static class StartProcessConvert extends AbstractCollectionConverter - implements - Converter { - - public StartProcessConvert(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - StartProcessCommand cmd = (StartProcessCommand) object; - writer.addAttribute( ""processId"", - cmd.getProcessId() ); - - for ( Entry entry : cmd.getParameters().entrySet() ) { - writer.startNode( ""parameter"" ); - writer.addAttribute( ""identifier"", - entry.getKey() ); - writeItem( entry.getValue(), - context, - writer ); - writer.endNode(); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String processId = reader.getAttribute( ""processId"" ); - - HashMap params = new HashMap(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - String identifier = reader.getAttribute( ""identifier"" ); - reader.moveDown(); - Object value = readItem( reader, - context, - null ); - reader.moveUp(); - params.put( identifier, - value ); - reader.moveUp(); - } - StartProcessCommand cmd = new StartProcessCommand(); - cmd.setProcessId( processId ); - cmd.setParameters( params ); - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( StartProcessCommand.class ); - } - } - - public static class SignalEventConverter extends AbstractCollectionConverter - implements - Converter { - - public SignalEventConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - SignalEventCommand cmd = (SignalEventCommand) object; - long processInstanceId = cmd.getProcessInstanceId(); - String eventType = cmd.getEventType(); - Object event = cmd.getEvent(); - - if ( processInstanceId != -1 ) { - writer.addAttribute( ""process-instance-id"", - Long.toString( processInstanceId ) ); - } - - writer.addAttribute( ""event-type"", - eventType ); - - writeItem( event, - context, - writer ); - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String processInstanceId = reader.getAttribute( ""process-instance-id"" ); - String eventType = reader.getAttribute( ""event-type"" ); - - reader.moveDown(); - Object event = readItem( reader, - context, - null ); - reader.moveUp(); - - Command cmd; - if ( processInstanceId != null ) { - cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ), - eventType, - event ); - } else { - cmd = CommandFactory.newSignalEvent( eventType, - event ); - } - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( SignalEventCommand.class ); - } - - } - - public static class CompleteWorkItemConverter extends AbstractCollectionConverter - implements - Converter { - - public CompleteWorkItemConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object; - writer.addAttribute( ""id"", - Long.toString( cmd.getWorkItemId() ) ); - - for ( Entry entry : cmd.getResults().entrySet() ) { - writer.startNode( ""result"" ); - writer.addAttribute( ""identifier"", - entry.getKey() ); - writeItem( entry.getValue(), - context, - writer ); - writer.endNode(); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String id = reader.getAttribute( ""id"" ); - - Map results = new HashMap(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - String identifier = reader.getAttribute( ""identifier"" ); - reader.moveDown(); - Object value = readItem( reader, - context, - null ); - reader.moveUp(); - results.put( identifier, - value ); - reader.moveUp(); - } - - Command cmd = CommandFactory.newCompleteWorkItem( Long.parseLong( id ), - results ); - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( CompleteWorkItemCommand.class ); - } - } - - public static class AbortWorkItemConverter extends AbstractCollectionConverter - implements - Converter { - - public AbortWorkItemConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - AbortWorkItemCommand cmd = (AbortWorkItemCommand) object; - writer.addAttribute( ""id"", - Long.toString( cmd.getWorkItemId() ) ); - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - String id = reader.getAttribute( ""id"" ); - Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) ); - - return cmd; - } - - public boolean canConvert(Class clazz) { - return clazz.equals( AbortWorkItemCommand.class ); - } + public XStream newXStreamMarshaller() { + return newXStreamMarshaller( new XStream() ); } - public static class BatchExecutionResultConverter extends AbstractCollectionConverter - implements - Converter { - - public BatchExecutionResultConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - ExecutionResults result = (ExecutionResults) object; - for ( String identifier : result.getIdentifiers() ) { - writer.startNode( ""result"" ); - writer.addAttribute( ""identifier"", - identifier ); - Object value = result.getValue( identifier ); - writeItem( value, - context, - writer ); - writer.endNode(); - } - - for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) { - - Object handle = result.getFactHandle( identifier ); - if ( handle instanceof FactHandle ) { - writer.startNode( ""fact-handle"" ); - writer.addAttribute( ""identifier"", - identifier ); - writer.addAttribute( ""externalForm"", - ((FactHandle) handle).toExternalForm() ); - - writer.endNode(); - } else if ( handle instanceof Collection ) { - writer.startNode( ""fact-handles"" ); - writer.addAttribute( ""identifier"", - identifier ); - for ( FactHandle factHandle : (Collection) handle ) { - writer.startNode( ""fact-handle"" ); - writer.addAttribute( ""externalForm"", - ((FactHandle) factHandle).toExternalForm() ); - writer.endNode(); - } - - writer.endNode(); - } - - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - ExecutionResultImpl result = new ExecutionResultImpl(); - Map results = result.getResults(); - Map facts = result.getFactHandles(); - - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - if ( reader.getNodeName().equals( ""result"" ) ) { - String identifier = reader.getAttribute( ""identifier"" ); - reader.moveDown(); - Object value = readItem( reader, - context, - null ); - results.put( identifier, - value ); - reader.moveUp(); - reader.moveUp(); - } else if ( reader.getNodeName().equals( ""fact-handle"" ) ) { - String identifier = reader.getAttribute( ""identifier"" ); - facts.put( identifier, - new DisconnectedFactHandle( reader.getAttribute( ""externalForm"" ) ) ); - } else if ( reader.getNodeName().equals( ""fact-handles"" ) ) { - String identifier = reader.getAttribute( ""identifier"" ); - List list = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - list.add( new DisconnectedFactHandle( reader.getAttribute( ""externalForm"" ) ) ); - reader.moveUp(); - } - facts.put( identifier, - list ); - } else { - throw new IllegalArgumentException( ""Element '"" + reader.getNodeName() + ""' is not supported here"" ); - } - } - - return result; - } - - public boolean canConvert(Class clazz) { - return ExecutionResults.class.isAssignableFrom( clazz ); - } + public XStream newJSonMarshaller() { + return XStreamJSon.newJSonMarshaller(); } - public static class QueryResultsConverter extends AbstractCollectionConverter - implements - Converter { - - public QueryResultsConverter(Mapper mapper) { - super( mapper ); - } - - public void marshal(Object object, - HierarchicalStreamWriter writer, - MarshallingContext context) { - QueryResults results = (QueryResults) object; - - // write out identifiers - List originalIds = Arrays.asList( results.getIdentifiers() ); - List actualIds = new ArrayList(); - if ( results instanceof NativeQueryResults ) { - for ( String identifier : originalIds ) { - // we don't want to marshall the query parameters - Declaration declr = ((NativeQueryResults) results).getDeclarations().get( identifier ); - ObjectType objectType = declr.getPattern().getObjectType(); - if ( objectType instanceof ClassObjectType ) { - if ( ((ClassObjectType) objectType).getClassType() == DroolsQuery.class ) { - continue; - } - } - actualIds.add( identifier ); - } - } - - String[] identifiers = actualIds.toArray( new String[actualIds.size()] ); - - writer.startNode( ""identifiers"" ); - for ( int i = 0; i < identifiers.length; i++ ) { - writer.startNode( ""identifier"" ); - writer.setValue( identifiers[i] ); - writer.endNode(); - } - writer.endNode(); - - for ( QueryResultsRow result : results ) { - writer.startNode( ""row"" ); - for ( int i = 0; i < identifiers.length; i++ ) { - Object value = result.get( identifiers[i] ); - FactHandle factHandle = result.getFactHandle( identifiers[i] ); - writeItem( value, - context, - writer ); - writer.startNode( ""fact-handle"" ); - writer.addAttribute( ""externalForm"", - ((FactHandle) factHandle).toExternalForm() ); - writer.endNode(); - } - writer.endNode(); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, - UnmarshallingContext context) { - reader.moveDown(); - List list = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - list.add( reader.getValue() ); - reader.moveUp(); - } - reader.moveUp(); - - HashMap identifiers = new HashMap(); - for ( int i = 0; i < list.size(); i++ ) { - identifiers.put( list.get( i ), - i ); - } - - ArrayList> results = new ArrayList(); - ArrayList> resultHandles = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - ArrayList objects = new ArrayList(); - ArrayList handles = new ArrayList(); - while ( reader.hasMoreChildren() ) { - reader.moveDown(); - Object object = readItem( reader, - context, - null ); - reader.moveUp(); - - reader.moveDown(); - FactHandle handle = new DisconnectedFactHandle( reader.getAttribute( ""externalForm"" ) ); - reader.moveUp(); - - objects.add( object ); - handles.add( handle ); - } - results.add( objects ); - resultHandles.add( handles ); - reader.moveUp(); - } - - return new FlatQueryResults( identifiers, - results, - resultHandles ); - } - - public boolean canConvert(Class clazz) { - return QueryResults.class.isAssignableFrom( clazz ); - } + public XStream newXStreamMarshaller(XStream xstream) { + return XStreamXML.newXStreamMarshaller(xstream); } + } diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java new file mode 100644 index 00000000000..d741f2181b2 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsList.java @@ -0,0 +1,17 @@ +package org.drools.runtime.help.impl; + +import java.util.List; + +public class CommandsList { + private List commands; + + public List getCommands() { + return commands; + } + + public void setCommands(List commands) { + this.commands = commands; + } + + +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java new file mode 100644 index 00000000000..c1d064e4ef3 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/CommandsObjectContainer.java @@ -0,0 +1,14 @@ +package org.drools.runtime.help.impl; + +public class CommandsObjectContainer { + + private Object containedObject; + + public CommandsObjectContainer(Object object) { + this.containedObject = object; + } + + public Object getContainedObject() { + return containedObject; + } +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java new file mode 100644 index 00000000000..25a4591fbbb --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/IdentifiersContainer.java @@ -0,0 +1,28 @@ +package org.drools.runtime.help.impl; + +import org.drools.runtime.rule.FactHandle; + +public class IdentifiersContainer { + + private String identifier; + private int index; + + public IdentifiersContainer() { + + } + + public IdentifiersContainer(String identifier, + int index) { + this.identifier = identifier; + this.index = index; + } + + public String getIdentifier() { + return identifier; + } + + public int getIndex() { + return index; + } + +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java new file mode 100644 index 00000000000..efc6d7e396a --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/ObjectsObjectContainer.java @@ -0,0 +1,14 @@ +package org.drools.runtime.help.impl; + +public class ObjectsObjectContainer { + + private Object containedObject; + + public ObjectsObjectContainer(Object object) { + this.containedObject = object; + } + + public Object getContainedObject() { + return containedObject; + } +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java new file mode 100644 index 00000000000..e67c9d91812 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/ParameterContainer.java @@ -0,0 +1,34 @@ +package org.drools.runtime.help.impl; + +public class ParameterContainer { + + private String identifier; + private Object object; + + public ParameterContainer() { + + } + + public ParameterContainer(String identifier, + Object object) { + this.identifier = identifier; + this.object = object; + } + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public Object getObject() { + return object; + } + + public void setObject(Object object) { + this.object = object; + } + +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java new file mode 100644 index 00000000000..2102607d2c0 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/RowItemContainer.java @@ -0,0 +1,37 @@ +package org.drools.runtime.help.impl; + +import org.drools.runtime.rule.FactHandle; + + +public class RowItemContainer { + + private FactHandle factHandle; + private Object object; + + public RowItemContainer() { + + } + + public RowItemContainer(FactHandle factHandle, + Object object) { + super(); + this.factHandle = factHandle; + this.object = object; + } + + public FactHandle getFactHandle() { + return factHandle; + } + + public void setFactHandle(FactHandle factHandle) { + this.factHandle = factHandle; + } + + public Object getObject() { + return object; + } + + public void setObject(Object object) { + this.object = object; + } +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java b/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java new file mode 100644 index 00000000000..f7579c9f380 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/WorkItemResultsContainer.java @@ -0,0 +1,34 @@ +package org.drools.runtime.help.impl; + +public class WorkItemResultsContainer { + + private String identifier; + private Object object; + + public WorkItemResultsContainer() { + + } + + public WorkItemResultsContainer(String identifier, + Object object) { + this.identifier = identifier; + this.object = object; + } + + public String getIdentifier() { + return identifier; + } + + public void setIdentifier(String identifier) { + this.identifier = identifier; + } + + public Object getObject() { + return object; + } + + public void setObject(Object object) { + this.object = object; + } + +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java new file mode 100644 index 00000000000..ab56dbd88b2 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamHelper.java @@ -0,0 +1,72 @@ +package org.drools.runtime.help.impl; + +import org.drools.command.runtime.BatchExecutionCommand; +import org.drools.command.runtime.GetGlobalCommand; +import org.drools.command.runtime.SetGlobalCommand; +import org.drools.command.runtime.process.AbortWorkItemCommand; +import org.drools.command.runtime.process.CompleteWorkItemCommand; +import org.drools.command.runtime.process.SignalEventCommand; +import org.drools.command.runtime.process.StartProcessCommand; +import org.drools.command.runtime.rule.FireAllRulesCommand; +import org.drools.command.runtime.rule.GetObjectCommand; +import org.drools.command.runtime.rule.GetObjectsCommand; +import org.drools.command.runtime.rule.InsertElementsCommand; +import org.drools.command.runtime.rule.InsertObjectCommand; +import org.drools.command.runtime.rule.ModifyCommand; +import org.drools.command.runtime.rule.QueryCommand; +import org.drools.command.runtime.rule.RetractCommand; +import org.drools.command.runtime.rule.ModifyCommand.SetterImpl; +import org.drools.common.DefaultFactHandle; +import org.drools.common.DisconnectedFactHandle; +import org.drools.runtime.impl.ExecutionResultImpl; +import org.drools.runtime.rule.impl.FlatQueryResults; +import org.drools.runtime.rule.impl.NativeQueryResults; + +import com.thoughtworks.xstream.XStream; + +public class XStreamHelper { + public static void setAliases(XStream xstream) { + xstream.alias( ""batch-execution"", + BatchExecutionCommand.class ); + xstream.alias( ""insert"", + InsertObjectCommand.class ); + xstream.alias( ""modify"", + ModifyCommand.class ); + xstream.alias( ""setters"", + SetterImpl.class ); + xstream.alias( ""retract"", + RetractCommand.class ); + xstream.alias( ""insert-elements"", + InsertElementsCommand.class ); + xstream.alias( ""start-process"", + StartProcessCommand.class ); + xstream.alias( ""signal-event"", + SignalEventCommand.class ); + xstream.alias( ""complete-work-item"", + CompleteWorkItemCommand.class ); + xstream.alias( ""abort-work-item"", + AbortWorkItemCommand.class ); + xstream.alias( ""set-global"", + SetGlobalCommand.class ); + xstream.alias( ""get-global"", + GetGlobalCommand.class ); + xstream.alias( ""get-object"", + GetObjectCommand.class ); + xstream.alias( ""get-objects"", + GetObjectsCommand.class ); + xstream.alias( ""execution-results"", + ExecutionResultImpl.class ); + xstream.alias( ""fire-all-rules"", + FireAllRulesCommand.class ); + xstream.alias( ""query"", + QueryCommand.class ); + xstream.alias( ""query-results"", + FlatQueryResults.class ); + xstream.alias( ""query-results"", + NativeQueryResults.class ); + xstream.alias( ""fact-handle"", + DefaultFactHandle.class ); + xstream.alias( ""fact-handle"", + DisconnectedFactHandle.class ); + } +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java new file mode 100644 index 00000000000..1842feaa509 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamJSon.java @@ -0,0 +1,1355 @@ +package org.drools.runtime.help.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.drools.command.Command; +import org.drools.command.CommandFactory; +import org.drools.command.Setter; +import org.drools.command.impl.GenericCommand; +import org.drools.command.runtime.BatchExecutionCommand; +import org.drools.command.runtime.GetGlobalCommand; +import org.drools.command.runtime.SetGlobalCommand; +import org.drools.command.runtime.process.AbortWorkItemCommand; +import org.drools.command.runtime.process.CompleteWorkItemCommand; +import org.drools.command.runtime.process.SignalEventCommand; +import org.drools.command.runtime.process.StartProcessCommand; +import org.drools.command.runtime.rule.FireAllRulesCommand; +import org.drools.command.runtime.rule.GetObjectCommand; +import org.drools.command.runtime.rule.GetObjectsCommand; +import org.drools.command.runtime.rule.InsertElementsCommand; +import org.drools.command.runtime.rule.InsertObjectCommand; +import org.drools.command.runtime.rule.ModifyCommand; +import org.drools.command.runtime.rule.QueryCommand; +import org.drools.command.runtime.rule.RetractCommand; +import org.drools.common.DisconnectedFactHandle; +import org.drools.runtime.ExecutionResults; +import org.drools.runtime.impl.ExecutionResultImpl; +import org.drools.runtime.rule.FactHandle; +import org.drools.runtime.rule.QueryResults; +import org.drools.runtime.rule.QueryResultsRow; +import org.drools.runtime.rule.impl.FlatQueryResults; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter; +import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; +import com.thoughtworks.xstream.core.util.HierarchicalStreams; +import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriterHelper; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; +import com.thoughtworks.xstream.mapper.Mapper; + +public class XStreamJSon { + public static XStream newJSonMarshaller() { + JettisonMappedXmlDriver jet = new JettisonMappedXmlDriver(); + XStream xstream = new XStream( jet ); + + XStreamHelper.setAliases( xstream ); + + xstream.alias( ""commands"", + CommandsObjectContainer.class ); + xstream.alias( ""objects"", + ObjectsObjectContainer.class ); + xstream.alias( ""item"", + RowItemContainer.class ); + xstream.alias( ""parameters"", + ParameterContainer.class ); + xstream.alias( ""results"", + WorkItemResultsContainer.class ); + + xstream.setMode( XStream.NO_REFERENCES ); + + xstream.registerConverter( new JSonFactHandleConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonBatchExecutionResultConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonInsertConverter( xstream.getMapper(), + xstream.getReflectionProvider() ) ); + xstream.registerConverter( new JSonFireAllRulesConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonBatchExecutionCommandConverter( xstream.getMapper() ) ); + xstream.registerConverter( new CommandsContainerConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonGetObjectConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonRetractConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonModifyConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonSetGlobalConverter( xstream.getMapper(), + xstream.getReflectionProvider() ) ); + xstream.registerConverter( new JSonInsertElementsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonGetGlobalConverter( xstream.getMapper(), + xstream.getReflectionProvider() ) ); + xstream.registerConverter( new JSonGetObjectsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonQueryConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonQueryResultsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new RowItemConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonStartProcessConvert( xstream.getMapper() ) ); + xstream.registerConverter( new JSonSignalEventConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonCompleteWorkItemConverter( xstream.getMapper() ) ); + xstream.registerConverter( new JSonAbortWorkItemConverter( xstream.getMapper() ) ); + + return xstream; + } + + public static class CommandsContainerConverter extends AbstractCollectionConverter { + public CommandsContainerConverter(Mapper mapper) { + super( mapper ); + } + + public boolean canConvert(Class type) { + return CommandsObjectContainer.class.isAssignableFrom( type ); + + } + + @Override + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + CommandsObjectContainer container = (CommandsObjectContainer) object; + + writeItem( container.getContainedObject(), + context, + writer ); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + throw new UnsupportedOperationException(); + } + + } + + public static class RowItemConverter extends AbstractCollectionConverter { + public RowItemConverter(Mapper mapper) { + super( mapper ); + } + + public boolean canConvert(Class type) { + return RowItemContainer.class.isAssignableFrom( type ); + + } + + @Override + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + RowItemContainer container = (RowItemContainer) object; + + writer.startNode( ""external-form"" ); + writer.setValue( container.getFactHandle().toExternalForm() ); + writer.endNode(); + + writer.startNode( ""object"" ); + writeItem( container.getObject(), + context, + writer ); + writer.endNode(); + } + + @Override + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String externalForm = null; + Object object = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""external-form"".equals( nodeName ) ) { + externalForm = reader.getValue(); + } else if ( ""object"".equals( nodeName ) ) { + reader.moveDown(); + object = readItem( reader, + context, + null ); + reader.moveUp(); + } + reader.moveUp(); + } + return new RowItemContainer( new DisconnectedFactHandle( externalForm ), + object ); + } + + } + + // public static class ModifyEntriesContainerConverter extends AbstractCollectionConverter { + // public ModifyEntriesContainerConverter(Mapper mapper) { + // super( mapper ); + // } + // + // public boolean canConvert(Class type) { + // return ModifyEntriesContainer.class.isAssignableFrom( type ); + // + // } + // + // @Override + // public void marshal(Object object, + // HierarchicalStreamWriter writer, + // MarshallingContext context) { + // ModifyEntriesContainer container = (ModifyEntriesContainer) object; + // + // writer.startNode( ""accessor"" ); + // writer.setValue( container.getAccessor() ); + // writer.endNode(); + // + // writer.startNode( ""value"" ); + // writer.setValue( container.getValue() ); + // writer.endNode(); + // } + // + // @Override + // public Object unmarshal(HierarchicalStreamReader reader, + // UnmarshallingContext context) { + // throw new UnsupportedOperationException(); + // } + // + // } + + public static class JSonBatchExecutionCommandConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonBatchExecutionCommandConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + BatchExecutionCommand cmds = (BatchExecutionCommand) object; + if ( cmds.getLookup() != null ) { + writer.startNode( ""lookup"" ); + writer.setValue( cmds.getLookup() ); + writer.endNode(); + } + List> list = cmds.getCommands(); + + for ( GenericCommand cmd : list ) { + writeItem( new CommandsObjectContainer( cmd ), + context, + writer ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + List> list = new ArrayList>(); + String lookup = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + if ( ""commands"".equals( reader.getNodeName() ) ) { + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + GenericCommand cmd = (GenericCommand) readItem( reader, + context, + null ); + list.add( cmd ); + reader.moveUp(); + } + } else if ( ""lookup"".equals( reader.getNodeName() ) ) { + lookup = reader.getValue(); + } else { + throw new IllegalArgumentException( ""batch-execution does not support the child element name=''"" + reader.getNodeName() + ""' value="" + reader.getValue() + ""'"" ); + } + reader.moveUp(); + } + return new BatchExecutionCommand( list, + lookup ); + } + + public boolean canConvert(Class clazz) { + return clazz.equals( BatchExecutionCommand.class ); + } + } + + public static class JSonInsertConverter extends BaseConverter + implements + Converter { + + public JSonInsertConverter(Mapper mapper, + ReflectionProvider reflectionProvider) { + super( mapper, + reflectionProvider ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + InsertObjectCommand cmd = (InsertObjectCommand) object; + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + + writer.startNode( ""return-object"" ); + writer.setValue( Boolean.toString( cmd.isReturnObject() ) ); + writer.endNode(); + } + writeValue( writer, + context, + ""object"", + cmd.getObject() ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + InsertObjectCommand cmd = new InsertObjectCommand(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""out-identifier"".equals( nodeName ) ) { + cmd.setOutIdentifier( reader.getValue() ); + } else if ( ""return-object"".equals( nodeName ) ) { + cmd.setReturnObject( Boolean.parseBoolean( reader.getValue() ) ); + } else if ( ""object"".equals( nodeName ) ) { + cmd.setObject( readValue( reader, + context, + cmd.getObject(), + ""object"" ) ); + } + reader.moveUp(); + + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( InsertObjectCommand.class ); + } + + } + + public static class JSonFactHandleConverter extends AbstractCollectionConverter + implements + Converter { + public JSonFactHandleConverter(Mapper mapper) { + super( mapper ); + } + + public boolean canConvert(Class aClass) { + return FactHandle.class.isAssignableFrom( aClass ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext marshallingContext) { + FactHandle fh = (FactHandle) object; + writer.startNode( ""external-form"" ); + writer.setValue( fh.toExternalForm() ); + writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext unmarshallingContext) { + reader.moveDown(); + DisconnectedFactHandle factHandle = new DisconnectedFactHandle( reader.getValue() ); + reader.moveUp(); + return factHandle; + } + } + + public static class JSonFireAllRulesConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonFireAllRulesConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + FireAllRulesCommand cmd = (FireAllRulesCommand) object; + + if ( cmd.getMax() != -1 ) { + writer.startNode( ""max"" ); + writer.setValue( Integer.toString( cmd.getMax() ) ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String max = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + if ( ""max"".equals( reader.getNodeName() ) ) { + max = reader.getValue(); + } else { + throw new IllegalArgumentException( ""fire-all-rules does not support the child element name=''"" + reader.getNodeName() + ""' value="" + reader.getValue() + ""'"" ); + } + reader.moveUp(); + } + + FireAllRulesCommand cmd = null; + + if ( max != null ) { + cmd = new FireAllRulesCommand( Integer.parseInt( max ) ); + } else { + cmd = new FireAllRulesCommand(); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( FireAllRulesCommand.class ); + } + } + + public static class JSonGetObjectConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonGetObjectConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetObjectCommand cmd = (GetObjectCommand) object; + writer.startNode( ""fact-handle"" ); + writer.setValue( cmd.getFactHandle().toExternalForm() ); + writer.endNode(); + + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + FactHandle factHandle = null; + String outIdentifier = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String name = reader.getNodeName(); + if ( ""fact-handle"".equals( name ) ) { + factHandle = new DisconnectedFactHandle( reader.getValue() ); + } else if ( ""out-identifier"".equals( ""out-identifier"" ) ) { + outIdentifier = reader.getValue(); + } + reader.moveUp(); + } + + GetObjectCommand cmd = new GetObjectCommand( factHandle ); + if ( outIdentifier != null ) { + cmd.setOutIdentifier( outIdentifier ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetObjectCommand.class ); + } + } + + public static class JSonRetractConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonRetractConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + RetractCommand cmd = (RetractCommand) object; + writer.startNode( ""fact-handle"" ); + writer.setValue( cmd.getFactHandle().toExternalForm() ); + writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + FactHandle factHandle = new DisconnectedFactHandle( reader.getValue() ); + reader.moveUp(); + + Command cmd = CommandFactory.newRetract( factHandle ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( RetractCommand.class ); + } + } + + public static class JSonModifyConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonModifyConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + ModifyCommand cmd = (ModifyCommand) object; + + writer.startNode( ""fact-handle"" ); + writer.setValue( cmd.getFactHandle().toExternalForm() ); + writer.endNode(); + + List setters = cmd.getSetters(); + for ( Setter setter : setters ) { + writeItem( setter, + context, + writer ); + + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + FactHandle factHandle = new DisconnectedFactHandle( reader.getValue() ); + reader.moveUp(); + + List setters = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + + reader.moveDown(); + String accessor = reader.getValue(); + reader.moveUp(); + + reader.moveDown(); + String value = reader.getValue(); + reader.moveUp(); + + Setter setter = CommandFactory.newSetter( accessor, + value ); + setters.add( setter ); + + reader.moveUp(); + } + + Command cmd = CommandFactory.newModify( factHandle, + setters ); + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( ModifyCommand.class ); + } + + } + + public static class JSonInsertElementsConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonInsertElementsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + InsertElementsCommand cmd = (InsertElementsCommand) object; + + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + + writer.startNode( ""return-objects"" ); + writer.setValue( Boolean.toString( cmd.isReturnObject() ) ); + writer.endNode(); + + } + + for ( Object element : cmd.getObjects() ) { + writeItem( new ObjectsObjectContainer( element ), + context, + writer ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + List objects = new ArrayList(); + String outIdentifier = null; + String returnObjects = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""objects"".equals( nodeName ) ) { + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Object o = readItem( reader, + context, + null ); + objects.add( o ); + reader.moveUp(); + } + } else if ( ""out-identifier"".equals( nodeName ) ) { + outIdentifier = reader.getValue(); + } else if ( ""return-objects"".equals( nodeName ) ) { + returnObjects = reader.getValue(); + } else { + throw new IllegalArgumentException( ""insert-elements does not support the child element name=''"" + reader.getNodeName() + ""' value="" + reader.getValue() + ""'"" ); + } + reader.moveUp(); + } + InsertElementsCommand cmd = new InsertElementsCommand( objects ); + if ( outIdentifier != null ) { + cmd.setOutIdentifier( outIdentifier ); + if ( outIdentifier != null ) { + cmd.setReturnObject( Boolean.parseBoolean( returnObjects ) ); + } + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( InsertElementsCommand.class ); + } + } + + public static class JSonBatchExecutionResultConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonBatchExecutionResultConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + ExecutionResults result = (ExecutionResults) object; + writer.startNode( ""results"" ); + if ( !result.getIdentifiers().isEmpty() ) { + for ( String identifier : result.getIdentifiers() ) { + writer.startNode( ""result"" ); + + writer.startNode( ""identifier"" ); + writer.setValue( identifier ); + writer.endNode(); + + writer.startNode( ""value"" ); + Object value = result.getValue( identifier ); + writeItem( value, + context, + writer ); + writer.endNode(); + + writer.endNode(); + } + } + + for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) { + Object handle = result.getFactHandle( identifier ); + if ( handle instanceof FactHandle ) { + writer.startNode( ""fact-handle"" ); + + writer.startNode( ""identifier"" ); + writer.setValue( identifier ); + writer.endNode(); + + writer.startNode( ""external-form"" ); + writer.setValue( ((FactHandle) handle).toExternalForm() ); + writer.endNode(); + + writer.endNode(); + } else if ( handle instanceof Collection ) { + writer.startNode( ""fact-handles"" ); + + writer.startNode( ""identifier"" ); + writer.setValue( identifier ); + writer.endNode(); + + //writer.startNode( ""xxx"" ); + for ( FactHandle factHandle : (Collection) handle ) { + writeItem( factHandle.toExternalForm(), + context, + writer ); + } + //writer.endNode(); + + writer.endNode(); + } + } + + writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + ExecutionResultImpl result = new ExecutionResultImpl(); + Map results = result.getResults(); + Map facts = result.getFactHandles(); + + reader.moveDown(); + if ( ""results"".equals( reader.getNodeName() ) ) { + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + + if ( reader.getNodeName().equals( ""result"" ) ) { + reader.moveDown(); + String identifier = reader.getValue(); + reader.moveUp(); + + reader.moveDown(); + reader.moveDown(); + Object value = readItem( reader, + context, + null ); + results.put( identifier, + value ); + reader.moveUp(); + reader.moveUp(); + } else if ( reader.getNodeName().equals( ""fact-handle"" ) ) { + reader.moveDown(); + String identifier = reader.getValue(); + reader.moveUp(); + + reader.moveDown(); + String externalForm = reader.getValue(); + reader.moveUp(); + + facts.put( identifier, + new DisconnectedFactHandle( externalForm ) ); + } else if ( reader.getNodeName().equals( ""fact-handles"" ) ) { + List list = new ArrayList(); + String identifier = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + identifier = reader.getValue(); + reader.moveUp(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + FactHandle factHandle = new DisconnectedFactHandle( (String) readItem( reader, + context, + null ) ); + list.add( factHandle ); + reader.moveUp(); + } + } + facts.put( identifier, + list ); + } else { + throw new IllegalArgumentException( ""Element '"" + reader.getNodeName() + ""' is not supported here"" ); + } + reader.moveUp(); + } + } else { + throw new IllegalArgumentException( ""Element '"" + reader.getNodeName() + ""' is not supported here"" ); + } + reader.moveUp(); + + return result; + } + + public boolean canConvert(Class clazz) { + return ExecutionResults.class.isAssignableFrom( clazz ); + } + } + + public static abstract class BaseConverter { + protected Mapper mapper; + protected ReflectionProvider reflectionProvider; + + public BaseConverter(Mapper mapper, + ReflectionProvider reflectionProvider) { + super(); + this.mapper = mapper; + this.reflectionProvider = reflectionProvider; + } + + protected void writeValue(HierarchicalStreamWriter writer, + MarshallingContext context, + String fieldName, + Object object) { + writer.startNode( fieldName ); + String name = this.mapper.serializedClass( object.getClass() ); + ExtendedHierarchicalStreamWriterHelper.startNode( writer, + name, + Mapper.Null.class ); + context.convertAnother( object ); + writer.endNode(); + writer.endNode(); + } + + protected Object readValue(HierarchicalStreamReader reader, + UnmarshallingContext context, + Object object, + Object fieldName) { + reader.moveDown(); + Class type = HierarchicalStreams.readClassType( reader, + this.mapper ); + Object o = context.convertAnother( null, + type ); + + reader.moveUp(); + return o; + } + } + + public static class JSonSetGlobalConverter extends BaseConverter + implements + Converter { + + public JSonSetGlobalConverter(Mapper mapper, + ReflectionProvider reflectionProvider) { + super( mapper, + reflectionProvider ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + SetGlobalCommand cmd = (SetGlobalCommand) object; + + writer.startNode( ""identifier"" ); + writer.setValue( cmd.getIdentifier() ); + writer.endNode(); + + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + } else if ( cmd.isOut() ) { + writer.startNode( ""out"" ); + writer.setValue( Boolean.toString( cmd.isOut() ) ); + writer.endNode(); + } + writeValue( writer, + context, + ""object"", + cmd.getObject() ); + + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifier = null; + String out = null; + String outIdentifier = null; + Object object = null; + SetGlobalCommand cmd = new SetGlobalCommand(); + + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""identifier"".equals( nodeName ) ) { + identifier = reader.getValue(); + } else if ( ""out"".equals( nodeName ) ) { + out = reader.getValue(); + } else if ( ""out-identifier"".equals( nodeName ) ) { + outIdentifier = reader.getValue(); + } else if ( ""object"".equals( nodeName ) ) { + cmd.setObject( readValue( reader, + context, + cmd.getObject(), + ""object"" ) ); + } + reader.moveUp(); + } + + cmd.setIdentifier( identifier ); + + if ( outIdentifier != null ) { + cmd.setOutIdentifier( outIdentifier ); + } else if ( out != null ) { + cmd.setOut( Boolean.parseBoolean( out ) ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( SetGlobalCommand.class ); + } + + } + + public static class JSonGetGlobalConverter extends BaseConverter + implements + Converter { + + public JSonGetGlobalConverter(Mapper mapper, + ReflectionProvider reflectionProvider) { + super( mapper, + reflectionProvider ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetGlobalCommand cmd = (GetGlobalCommand) object; + + writer.startNode( ""identifier"" ); + writer.setValue( cmd.getIdentifier() ); + writer.endNode(); + + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + } + + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifier = null; + String outIdentifier = null; + GetGlobalCommand cmd = new GetGlobalCommand(); + + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""identifier"".equals( nodeName ) ) { + identifier = reader.getValue(); + } else if ( ""out-identifier"".equals( nodeName ) ) { + outIdentifier = reader.getValue(); + } + reader.moveUp(); + } + + cmd.setIdentifier( identifier ); + + if ( outIdentifier != null ) { + cmd.setOutIdentifier( outIdentifier ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetGlobalCommand.class ); + } + } + + public static class JSonGetObjectsConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonGetObjectsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetObjectsCommand cmd = (GetObjectsCommand) object; + + if ( cmd.getOutIdentifier() != null ) { + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String outIdentifier = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + if ( ""out-identifier"".equals( reader.getNodeName() ) ) { + outIdentifier = reader.getValue(); + } + reader.moveUp(); + } + + GetObjectsCommand cmd = new GetObjectsCommand(); + if ( outIdentifier != null ) { + cmd.setOutIdentifier( outIdentifier ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetObjectsCommand.class ); + } + } + + public static class JSonQueryConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonQueryConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + QueryCommand cmd = (QueryCommand) object; + + writer.startNode( ""out-identifier"" ); + writer.setValue( cmd.getOutIdentifier() ); + writer.endNode(); + + writer.startNode( ""name"" ); + writer.setValue( cmd.getName() ); + writer.endNode(); + + if ( cmd.getArguments() != null && cmd.getArguments().size() > 0 ) { + writer.startNode( ""args"" ); + for ( Object arg : cmd.getArguments() ) { + writeItem( arg, + context, + writer ); + } + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + List outs = new ArrayList(); + + String outIdentifier = null; + String name = null; + List args = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""out-identifier"".equals( nodeName ) ) { + outIdentifier = reader.getValue(); + } else if ( ""name"".equals( nodeName ) ) { + name = reader.getValue(); + } else if ( ""args"".equals( nodeName ) ) { + reader.moveDown(); + args = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Object arg = readItem( reader, + context, + null ); + args.add( arg ); + reader.moveUp(); + } + reader.moveUp(); + } + reader.moveUp(); + } + + QueryCommand cmd = new QueryCommand( outIdentifier, + name, + (args != null) ? args.toArray( new Object[args.size()] ) : null ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( QueryCommand.class ); + } + } + + public static class JSonQueryResultsConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonQueryResultsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + QueryResults results = (QueryResults) object; + + // write out identifiers + String[] identifiers = results.getIdentifiers(); + + writer.startNode( ""identifiers"" ); + for ( int i = 0; i < identifiers.length; i++ ) { + writeItem( identifiers[i], + context, + writer ); + } + writer.endNode(); + + for ( QueryResultsRow result : results ) { + writer.startNode( ""row"" ); + for ( int i = 0; i < identifiers.length; i++ ) { + Object value = result.get( identifiers[i] ); + FactHandle factHandle = result.getFactHandle( identifiers[i] ); + writeItem( new RowItemContainer( factHandle, + value ), + context, + writer ); + } + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + List list = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + list.add( (String) readItem( reader, + context, + null ) ); + reader.moveUp(); + } + reader.moveUp(); + + HashMap identifiers = new HashMap(); + for ( int i = 0; i < list.size(); i++ ) { + identifiers.put( list.get( i ), + i ); + } + + ArrayList> results = new ArrayList(); + ArrayList> resultHandles = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + ArrayList objects = new ArrayList(); + ArrayList handles = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + RowItemContainer container = (RowItemContainer) readItem( reader, + context, + null ); + + objects.add( container.getObject() ); + handles.add( container.getFactHandle() ); + reader.moveUp(); + } + results.add( objects ); + resultHandles.add( handles ); + reader.moveUp(); + } + + return new FlatQueryResults( identifiers, + results, + resultHandles ); + } + + public boolean canConvert(Class clazz) { + return QueryResults.class.isAssignableFrom( clazz ); + } + } + + public static class JSonStartProcessConvert extends AbstractCollectionConverter + implements + Converter { + + public JSonStartProcessConvert(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + StartProcessCommand cmd = (StartProcessCommand) object; + writer.startNode( ""process-id"" ); + writer.setValue( cmd.getProcessId() ); + writer.endNode(); + + for ( Entry entry : cmd.getParameters().entrySet() ) { + writeItem( new ParameterContainer( entry.getKey(), + entry.getValue() ), + context, + writer ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + String processId = reader.getValue(); + reader.moveUp(); + + HashMap params = new HashMap(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + ParameterContainer parameterContainer = (ParameterContainer) readItem( reader, + context, + null ); + params.put( parameterContainer.getIdentifier(), + parameterContainer.getObject() ); + reader.moveUp(); + } + + StartProcessCommand cmd = new StartProcessCommand(); + cmd.setProcessId( processId ); + cmd.setParameters( params ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( StartProcessCommand.class ); + } + } + + public static class JSonSignalEventConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonSignalEventConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + SignalEventCommand cmd = (SignalEventCommand) object; + long processInstanceId = cmd.getProcessInstanceId(); + String eventType = cmd.getEventType(); + Object event = cmd.getEvent(); + + if ( processInstanceId != -1 ) { + writer.startNode( ""process-instance-id"" ); + writer.setValue( Long.toString( processInstanceId ) ); + writer.endNode(); + } + + writer.addAttribute( ""event-type"", + eventType ); + + writer.startNode( ""event-type"" ); + writer.setValue( eventType ); + writer.endNode(); + + writer.startNode( ""object"" ); + writeItem( event, + context, + writer ); + writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String processInstanceId = null; + String eventType = null; + Object event = null; + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""process-instance-id"".equals( nodeName ) ) { + processInstanceId = reader.getValue(); + } else if ( ""event-type"".equals( nodeName ) ) { + eventType = reader.getValue(); + } else if ( ""object"".equals( nodeName ) ) { + reader.moveDown(); + event = readItem( reader, + context, + null ); + reader.moveUp(); + } + reader.moveUp(); + } + + Command cmd; + if ( processInstanceId != null ) { + cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ), + eventType, + event ); + } else { + cmd = CommandFactory.newSignalEvent( eventType, + event ); + } + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( SignalEventCommand.class ); + } + + } + + public static class JSonCompleteWorkItemConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonCompleteWorkItemConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object; + + writer.startNode( ""id"" ); + writer.setValue( Long.toString( cmd.getWorkItemId() ) ); + writer.endNode(); + + for ( Entry entry : cmd.getResults().entrySet() ) { + writeItem( new WorkItemResultsContainer( entry.getKey(), + entry.getValue() ), + context, + writer ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String id = null; + Map results = new HashMap(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String nodeName = reader.getNodeName(); + if ( ""id"".equals( nodeName ) ) { + id = reader.getValue(); + } else if ( ""results"".equals( nodeName ) ) { + while ( reader.hasMoreChildren() ) { + WorkItemResultsContainer res = (WorkItemResultsContainer) readItem( reader, + context, + null ); + results.put( res.getIdentifier(), + res.getObject() ); + } + } + reader.moveUp(); + } + + return new CompleteWorkItemCommand( Long.parseLong( id ), + results ); + } + + public boolean canConvert(Class clazz) { + return clazz.equals( CompleteWorkItemCommand.class ); + } + } + + public static class JSonAbortWorkItemConverter extends AbstractCollectionConverter + implements + Converter { + + public JSonAbortWorkItemConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + AbortWorkItemCommand cmd = (AbortWorkItemCommand) object; + writer.startNode( ""id"" ); + writer.setValue( Long.toString( cmd.getWorkItemId() ) ); + writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + String id = reader.getValue(); + reader.moveUp(); + + Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( AbortWorkItemCommand.class ); + } + } +} diff --git a/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java new file mode 100644 index 00000000000..497d05aa480 --- /dev/null +++ b/drools-core/src/main/java/org/drools/runtime/help/impl/XStreamXML.java @@ -0,0 +1,964 @@ +package org.drools.runtime.help.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.drools.base.ClassObjectType; +import org.drools.base.DroolsQuery; +import org.drools.command.Command; +import org.drools.command.CommandFactory; +import org.drools.command.Setter; +import org.drools.command.runtime.BatchExecutionCommand; +import org.drools.command.runtime.GetGlobalCommand; +import org.drools.command.runtime.SetGlobalCommand; +import org.drools.command.runtime.process.AbortWorkItemCommand; +import org.drools.command.runtime.process.CompleteWorkItemCommand; +import org.drools.command.runtime.process.SignalEventCommand; +import org.drools.command.runtime.process.StartProcessCommand; +import org.drools.command.runtime.rule.FireAllRulesCommand; +import org.drools.command.runtime.rule.GetObjectCommand; +import org.drools.command.runtime.rule.GetObjectsCommand; +import org.drools.command.runtime.rule.InsertElementsCommand; +import org.drools.command.runtime.rule.InsertObjectCommand; +import org.drools.command.runtime.rule.ModifyCommand; +import org.drools.command.runtime.rule.QueryCommand; +import org.drools.command.runtime.rule.RetractCommand; +import org.drools.common.DisconnectedFactHandle; +import org.drools.rule.Declaration; +import org.drools.runtime.ExecutionResults; +import org.drools.runtime.impl.ExecutionResultImpl; +import org.drools.runtime.rule.FactHandle; +import org.drools.runtime.rule.QueryResults; +import org.drools.runtime.rule.QueryResultsRow; +import org.drools.runtime.rule.impl.FlatQueryResults; +import org.drools.runtime.rule.impl.NativeQueryResults; +import org.drools.spi.ObjectType; + +import com.thoughtworks.xstream.XStream; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.MarshallingContext; +import com.thoughtworks.xstream.converters.UnmarshallingContext; +import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter; +import com.thoughtworks.xstream.io.HierarchicalStreamReader; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; +import com.thoughtworks.xstream.mapper.Mapper; + +public class XStreamXML { + + public static XStream newXStreamMarshaller(XStream xstream) { + XStreamHelper.setAliases( xstream ); + + xstream.processAnnotations( BatchExecutionCommand.class ); + xstream.addImplicitCollection( BatchExecutionCommand.class, + ""commands"" ); + + xstream.registerConverter( new InsertConverter( xstream.getMapper() ) ); + xstream.registerConverter( new RetractConverter( xstream.getMapper() ) ); + xstream.registerConverter( new ModifyConverter( xstream.getMapper() ) ); + xstream.registerConverter( new GetObjectConverter( xstream.getMapper() ) ); + xstream.registerConverter( new InsertElementsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new FireAllRulesConverter( xstream.getMapper() ) ); + xstream.registerConverter( new StartProcessConvert( xstream.getMapper() ) ); + xstream.registerConverter( new SignalEventConverter( xstream.getMapper() ) ); + xstream.registerConverter( new CompleteWorkItemConverter( xstream.getMapper() ) ); + xstream.registerConverter( new AbortWorkItemConverter( xstream.getMapper() ) ); + xstream.registerConverter( new QueryConverter( xstream.getMapper() ) ); + xstream.registerConverter( new SetGlobalConverter( xstream.getMapper() ) ); + xstream.registerConverter( new GetGlobalConverter( xstream.getMapper() ) ); + xstream.registerConverter( new GetObjectsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new BatchExecutionResultConverter( xstream.getMapper() ) ); + xstream.registerConverter( new QueryResultsConverter( xstream.getMapper() ) ); + xstream.registerConverter( new FactHandleConverter( xstream.getMapper() ) ); + + return xstream; + } + + + public static class InsertConverter extends AbstractCollectionConverter + implements + Converter { + + public InsertConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + InsertObjectCommand cmd = (InsertObjectCommand) object; + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + + writer.addAttribute( ""return-object"", + Boolean.toString( cmd.isReturnObject() ) ); + + } + writeItem( cmd.getObject(), + context, + writer ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifierOut = reader.getAttribute( ""out-identifier"" ); + String returnObject = reader.getAttribute( ""return-object"" ); + + reader.moveDown(); + Object object = readItem( reader, + context, + null ); + reader.moveUp(); + InsertObjectCommand cmd = new InsertObjectCommand( object ); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + if ( returnObject != null ) { + cmd.setReturnObject( Boolean.parseBoolean( returnObject ) ); + } + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( InsertObjectCommand.class ); + } + + } + + public static class FactHandleConverter + implements + Converter { + private Mapper mapper; + + public FactHandleConverter(Mapper mapper) { + this.mapper = mapper; + } + + public boolean canConvert(Class aClass) { + return FactHandle.class.isAssignableFrom( aClass ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext marshallingContext) { + FactHandle fh = (FactHandle) object; + //writer.startNode(""fact-handle""); + writer.addAttribute( ""external-form"", + fh.toExternalForm() ); + //writer.endNode(); + } + + public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, + UnmarshallingContext unmarshallingContext) { + throw new UnsupportedOperationException( ""Unable to unmarshal fact handles."" ); + } + } + + public static class ModifyConverter + implements + Converter { + + public ModifyConverter(Mapper mapper) { + + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + ModifyCommand cmd = (ModifyCommand) object; + + writer.addAttribute( ""fact-handle"", + cmd.getFactHandle().toExternalForm() ); + + for ( Setter setter : cmd.getSetters() ) { + writer.startNode( ""set"" ); + writer.addAttribute( ""accessor"", + setter.getAccessor() ); + writer.addAttribute( ""value"", + setter.getValue() ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""fact-handle"" ) ); + + List setters = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Setter setter = CommandFactory.newSetter( reader.getAttribute( ""accessor"" ), + reader.getAttribute( ""value"" ) ); + setters.add( setter ); + reader.moveUp(); + } + + Command cmd = CommandFactory.newModify( factHandle, + setters ); + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( ModifyCommand.class ); + } + + } + + public static class RetractConverter extends AbstractCollectionConverter + implements + Converter { + + public RetractConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + RetractCommand cmd = (RetractCommand) object; + + writer.addAttribute( ""fact-handle"", + cmd.getFactHandle().toExternalForm() ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""fact-handle"" ) ); + + Command cmd = CommandFactory.newRetract( factHandle ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( RetractCommand.class ); + } + } + + public static class InsertElementsConverter extends AbstractCollectionConverter + implements + Converter { + + public InsertElementsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + InsertElementsCommand cmd = (InsertElementsCommand) object; + + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + + writer.addAttribute( ""return-objects"", + Boolean.toString( cmd.isReturnObject() ) ); + + } + + for ( Object element : cmd.getObjects() ) { + writeItem( element, + context, + writer ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifierOut = reader.getAttribute( ""out-identifier"" ); + String returnObject = reader.getAttribute( ""return-objects"" ); + + List objects = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Object object = readItem( reader, + context, + null ); + reader.moveUp(); + objects.add( object ); + } + + InsertElementsCommand cmd = new InsertElementsCommand( objects ); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + if ( returnObject != null ) { + cmd.setReturnObject( Boolean.parseBoolean( returnObject ) ); + } + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( InsertElementsCommand.class ); + } + + } + + public static class SetGlobalConverter extends AbstractCollectionConverter + implements + Converter { + + public SetGlobalConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + SetGlobalCommand cmd = (SetGlobalCommand) object; + + writer.addAttribute( ""identifier"", + cmd.getIdentifier() ); + + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + } else if ( cmd.isOut() ) { + writer.addAttribute( ""out"", + Boolean.toString( cmd.isOut() ) ); + } + + writeItem( cmd.getObject(), + context, + writer ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifier = reader.getAttribute( ""identifier"" ); + String out = reader.getAttribute( ""out"" ); + String identifierOut = reader.getAttribute( ""out-identifier"" ); + + reader.moveDown(); + Object object = readItem( reader, + context, + null ); + reader.moveUp(); + SetGlobalCommand cmd = new SetGlobalCommand( identifier, + object ); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + } else if ( out != null ) { + cmd.setOut( Boolean.parseBoolean( out ) ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( SetGlobalCommand.class ); + } + } + + public static class GetObjectConverter extends AbstractCollectionConverter + implements + Converter { + + public GetObjectConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetObjectCommand cmd = (GetObjectCommand) object; + + writer.addAttribute( ""fact-handle"", + cmd.getFactHandle().toExternalForm() ); + + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + FactHandle factHandle = new DisconnectedFactHandle( reader.getAttribute( ""fact-handle"" ) ); + String identifierOut = reader.getAttribute( ""out-identifier"" ); + + GetObjectCommand cmd = new GetObjectCommand( factHandle ); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetObjectCommand.class ); + } + } + + public static class GetGlobalConverter extends AbstractCollectionConverter + implements + Converter { + + public GetGlobalConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetGlobalCommand cmd = (GetGlobalCommand) object; + + writer.addAttribute( ""identifier"", + cmd.getIdentifier() ); + + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifier = reader.getAttribute( ""identifier"" ); + String identifierOut = reader.getAttribute( ""out-identifier"" ); + + GetGlobalCommand cmd = new GetGlobalCommand( identifier ); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetGlobalCommand.class ); + } + } + + public static class GetObjectsConverter extends AbstractCollectionConverter + implements + Converter { + + public GetObjectsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + GetObjectsCommand cmd = (GetObjectsCommand) object; + + if ( cmd.getOutIdentifier() != null ) { + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String identifierOut = reader.getAttribute( ""out-identifier"" ); + + GetObjectsCommand cmd = new GetObjectsCommand(); + if ( identifierOut != null ) { + cmd.setOutIdentifier( identifierOut ); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( GetObjectsCommand.class ); + } + } + + public static class FireAllRulesConverter extends AbstractCollectionConverter + implements + Converter { + + public FireAllRulesConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + FireAllRulesCommand cmd = (FireAllRulesCommand) object; + + if ( cmd.getMax() != -1 ) { + writer.addAttribute( ""max"", + Integer.toString( cmd.getMax() ) ); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String max = reader.getAttribute( ""max"" ); + + FireAllRulesCommand cmd = null; + + if ( max != null ) { + cmd = new FireAllRulesCommand( Integer.parseInt( max ) ); + } else { + cmd = new FireAllRulesCommand(); + } + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( FireAllRulesCommand.class ); + } + } + + public static class QueryConverter extends AbstractCollectionConverter + implements + Converter { + + public QueryConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + QueryCommand cmd = (QueryCommand) object; + writer.addAttribute( ""out-identifier"", + cmd.getOutIdentifier() ); + writer.addAttribute( ""name"", + cmd.getName() ); + if ( cmd.getArguments() != null ) { + for ( Object arg : cmd.getArguments() ) { + writeItem( arg, + context, + writer ); + } + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + List outs = new ArrayList(); + + // Query cmd = null; + String outIdentifier = reader.getAttribute( ""out-identifier"" ); + String name = reader.getAttribute( ""name"" ); + List args = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Object arg = readItem( reader, + context, + null ); + args.add( arg ); + reader.moveUp(); + } + QueryCommand cmd = new QueryCommand( outIdentifier, + name, + args.toArray( new Object[args.size()] ) ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( QueryCommand.class ); + } + } + + public static class StartProcessConvert extends AbstractCollectionConverter + implements + Converter { + + public StartProcessConvert(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + StartProcessCommand cmd = (StartProcessCommand) object; + writer.addAttribute( ""processId"", + cmd.getProcessId() ); + + for ( Entry entry : cmd.getParameters().entrySet() ) { + writer.startNode( ""parameter"" ); + writer.addAttribute( ""identifier"", + entry.getKey() ); + writeItem( entry.getValue(), + context, + writer ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String processId = reader.getAttribute( ""processId"" ); + + HashMap params = new HashMap(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String identifier = reader.getAttribute( ""identifier"" ); + reader.moveDown(); + Object value = readItem( reader, + context, + null ); + reader.moveUp(); + params.put( identifier, + value ); + reader.moveUp(); + } + StartProcessCommand cmd = new StartProcessCommand(); + cmd.setProcessId( processId ); + cmd.setParameters( params ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( StartProcessCommand.class ); + } + } + + public static class SignalEventConverter extends AbstractCollectionConverter + implements + Converter { + + public SignalEventConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + SignalEventCommand cmd = (SignalEventCommand) object; + long processInstanceId = cmd.getProcessInstanceId(); + String eventType = cmd.getEventType(); + Object event = cmd.getEvent(); + + if ( processInstanceId != -1 ) { + writer.addAttribute( ""process-instance-id"", + Long.toString( processInstanceId ) ); + } + + writer.addAttribute( ""event-type"", + eventType ); + + writeItem( event, + context, + writer ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String processInstanceId = reader.getAttribute( ""process-instance-id"" ); + String eventType = reader.getAttribute( ""event-type"" ); + + reader.moveDown(); + Object event = readItem( reader, + context, + null ); + reader.moveUp(); + + Command cmd; + if ( processInstanceId != null ) { + cmd = CommandFactory.newSignalEvent( Long.parseLong( processInstanceId ), + eventType, + event ); + } else { + cmd = CommandFactory.newSignalEvent( eventType, + event ); + } + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( SignalEventCommand.class ); + } + + } + + public static class CompleteWorkItemConverter extends AbstractCollectionConverter + implements + Converter { + + public CompleteWorkItemConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + CompleteWorkItemCommand cmd = (CompleteWorkItemCommand) object; + writer.addAttribute( ""id"", + Long.toString( cmd.getWorkItemId() ) ); + + for ( Entry entry : cmd.getResults().entrySet() ) { + writer.startNode( ""result"" ); + writer.addAttribute( ""identifier"", + entry.getKey() ); + writeItem( entry.getValue(), + context, + writer ); + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String id = reader.getAttribute( ""id"" ); + + Map results = new HashMap(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + String identifier = reader.getAttribute( ""identifier"" ); + reader.moveDown(); + Object value = readItem( reader, + context, + null ); + reader.moveUp(); + results.put( identifier, + value ); + reader.moveUp(); + } + + Command cmd = CommandFactory.newCompleteWorkItem( Long.parseLong( id ), + results ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( CompleteWorkItemCommand.class ); + } + } + + public static class AbortWorkItemConverter extends AbstractCollectionConverter + implements + Converter { + + public AbortWorkItemConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + AbortWorkItemCommand cmd = (AbortWorkItemCommand) object; + writer.addAttribute( ""id"", + Long.toString( cmd.getWorkItemId() ) ); + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + String id = reader.getAttribute( ""id"" ); + Command cmd = CommandFactory.newAbortWorkItem( Long.parseLong( id ) ); + + return cmd; + } + + public boolean canConvert(Class clazz) { + return clazz.equals( AbortWorkItemCommand.class ); + } + } + + public static class BatchExecutionResultConverter extends AbstractCollectionConverter + implements + Converter { + + public BatchExecutionResultConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + ExecutionResults result = (ExecutionResults) object; + for ( String identifier : result.getIdentifiers() ) { + writer.startNode( ""result"" ); + writer.addAttribute( ""identifier"", + identifier ); + Object value = result.getValue( identifier ); + writeItem( value, + context, + writer ); + writer.endNode(); + } + + for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) { + Object handle = result.getFactHandle( identifier ); + if ( handle instanceof FactHandle ) { + writer.startNode( ""fact-handle"" ); + writer.addAttribute( ""identifier"", + identifier ); + writer.addAttribute( ""external-form"", + ((FactHandle) handle).toExternalForm() ); + + writer.endNode(); + } else if ( handle instanceof Collection ) { + writer.startNode( ""fact-handles"" ); + writer.addAttribute( ""identifier"", + identifier ); + for ( FactHandle factHandle : (Collection) handle ) { + writer.startNode( ""fact-handle"" ); + writer.addAttribute( ""external-form"", + ((FactHandle) factHandle).toExternalForm() ); + writer.endNode(); + } + + writer.endNode(); + } + + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + ExecutionResultImpl result = new ExecutionResultImpl(); + Map results = result.getResults(); + Map facts = result.getFactHandles(); + + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + if ( reader.getNodeName().equals( ""result"" ) ) { + String identifier = reader.getAttribute( ""identifier"" ); + reader.moveDown(); + Object value = readItem( reader, + context, + null ); + results.put( identifier, + value ); + reader.moveUp(); + reader.moveUp(); + } else if ( reader.getNodeName().equals( ""fact-handle"" ) ) { + String identifier = reader.getAttribute( ""identifier"" ); + facts.put( identifier, + new DisconnectedFactHandle( reader.getAttribute( ""external-form"" ) ) ); + } else if ( reader.getNodeName().equals( ""fact-handles"" ) ) { + String identifier = reader.getAttribute( ""identifier"" ); + List list = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + list.add( new DisconnectedFactHandle( reader.getAttribute( ""external-form"" ) ) ); + reader.moveUp(); + } + facts.put( identifier, + list ); + } else { + throw new IllegalArgumentException( ""Element '"" + reader.getNodeName() + ""' is not supported here"" ); + } + } + + return result; + } + + public boolean canConvert(Class clazz) { + return ExecutionResults.class.isAssignableFrom( clazz ); + } + } + + public static class QueryResultsConverter extends AbstractCollectionConverter + implements + Converter { + + public QueryResultsConverter(Mapper mapper) { + super( mapper ); + } + + public void marshal(Object object, + HierarchicalStreamWriter writer, + MarshallingContext context) { + QueryResults results = (QueryResults) object; + + // write out identifiers + List originalIds = Arrays.asList( results.getIdentifiers() ); + List actualIds = new ArrayList(); + if ( results instanceof NativeQueryResults ) { + for ( String identifier : originalIds ) { + // we don't want to marshall the query parameters + Declaration declr = ((NativeQueryResults) results).getDeclarations().get( identifier ); + ObjectType objectType = declr.getPattern().getObjectType(); + if ( objectType instanceof ClassObjectType ) { + if ( ((ClassObjectType) objectType).getClassType() == DroolsQuery.class ) { + continue; + } + } + actualIds.add( identifier ); + } + } + + String[] identifiers = actualIds.toArray( new String[actualIds.size()] ); + + writer.startNode( ""identifiers"" ); + for ( int i = 0; i < identifiers.length; i++ ) { + writer.startNode( ""identifier"" ); + writer.setValue( identifiers[i] ); + writer.endNode(); + } + writer.endNode(); + + for ( QueryResultsRow result : results ) { + writer.startNode( ""row"" ); + for ( int i = 0; i < identifiers.length; i++ ) { + Object value = result.get( identifiers[i] ); + FactHandle factHandle = result.getFactHandle( identifiers[i] ); + writeItem( value, + context, + writer ); + writer.startNode( ""fact-handle"" ); + writer.addAttribute( ""external-form"", + ((FactHandle) factHandle).toExternalForm() ); + writer.endNode(); + } + writer.endNode(); + } + } + + public Object unmarshal(HierarchicalStreamReader reader, + UnmarshallingContext context) { + reader.moveDown(); + List list = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + list.add( reader.getValue() ); + reader.moveUp(); + } + reader.moveUp(); + + HashMap identifiers = new HashMap(); + for ( int i = 0; i < list.size(); i++ ) { + identifiers.put( list.get( i ), + i ); + } + + ArrayList> results = new ArrayList(); + ArrayList> resultHandles = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + ArrayList objects = new ArrayList(); + ArrayList handles = new ArrayList(); + while ( reader.hasMoreChildren() ) { + reader.moveDown(); + Object object = readItem( reader, + context, + null ); + reader.moveUp(); + + reader.moveDown(); + FactHandle handle = new DisconnectedFactHandle( reader.getAttribute( ""external-form"" ) ); + reader.moveUp(); + + objects.add( object ); + handles.add( handle ); + } + results.add( objects ); + resultHandles.add( handles ); + reader.moveUp(); + } + + return new FlatQueryResults( identifiers, + results, + resultHandles ); + } + + public boolean canConvert(Class clazz) { + return QueryResults.class.isAssignableFrom( clazz ); + } + } +}" 02b0fc2fa3a41f340a75235d407d8516fe4c7a63,restlet-framework-java, - Disabled failing test cases (temp)--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java index 22c32949cc..f07b1d3823 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java @@ -60,7 +60,7 @@ public static Test suite() { mySuite.addTestSuite(InheritAnnotationTest.class); mySuite.addTestSuite(InjectionTest.class); mySuite.addTestSuite(Issue593Test.class); - mySuite.addTestSuite(JsonTest.class); + // mySuite.addTestSuite(JsonTest.class); mySuite.addTestSuite(ListParamTest.class); mySuite.addTestSuite(MatchedTest.class); mySuite.addTestSuite(MatrixParamTest.class); @@ -74,7 +74,7 @@ public static Test suite() { mySuite.addTestSuite(PathParamTest3.class); mySuite.addTestSuite(PersonsTest.class); mySuite.addTestSuite(PrimitiveWrapperEntityTest.class); - mySuite.addTestSuite(ProviderTest.class); + // mySuite.addTestSuite(ProviderTest.class); mySuite.addTestSuite(QueryParamTest.class); mySuite.addTestSuite(RecursiveTest.class); mySuite.addTestSuite(RepresentationTest.class);" 586b7e3deedb5a917cffc194a3783b453becf5ca,kotlin,Base class for multi-file tests extracted--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/tests/org/jetbrains/jet/checkers/BaseDiagnosticsTest.java b/compiler/tests/org/jetbrains/jet/checkers/BaseDiagnosticsTest.java index e58eecf7950bd..b9509bff0549e 100644 --- a/compiler/tests/org/jetbrains/jet/checkers/BaseDiagnosticsTest.java +++ b/compiler/tests/org/jetbrains/jet/checkers/BaseDiagnosticsTest.java @@ -18,12 +18,10 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; -import com.google.common.io.Files; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.TextRange; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.search.GlobalSearchScope; @@ -34,29 +32,22 @@ import kotlin.KotlinPackage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.ConfigurationKind; -import org.jetbrains.jet.JetLiteFixture; -import org.jetbrains.jet.JetTestUtils; -import org.jetbrains.jet.TestJdkKind; import org.jetbrains.jet.asJava.AsJavaPackage; -import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; import org.jetbrains.jet.lang.diagnostics.*; import org.jetbrains.jet.lang.psi.JetDeclaration; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.Diagnostics; import org.jetbrains.jet.lang.types.Flexibility; -import org.jetbrains.jet.utils.UtilsPackage; import org.junit.Assert; import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -public abstract class BaseDiagnosticsTest extends JetLiteFixture { +public abstract class BaseDiagnosticsTest extends + KotlinMultiFileTestWithWithJava { public static final String DIAGNOSTICS_DIRECTIVE = ""DIAGNOSTICS""; public static final Pattern DIAGNOSTICS_PATTERN = Pattern.compile(""([\\+\\-!])(\\w+)\\s*""); @@ -86,81 +77,17 @@ public abstract class BaseDiagnosticsTest extends JetLiteFixture { private static final String EXPLICIT_FLEXIBLE_TYPES_IMPORT = ""import "" + EXPLICIT_FLEXIBLE_PACKAGE + ""."" + EXPLICIT_FLEXIBLE_CLASS_NAME; @Override - protected JetCoreEnvironment createEnvironment() { - File javaFilesDir = createJavaFilesDir(); - return JetCoreEnvironment.createForTests(getTestRootDisposable(), JetTestUtils.compilerConfigurationForTests( - ConfigurationKind.JDK_AND_ANNOTATIONS, - TestJdkKind.MOCK_JDK, - Arrays.asList(JetTestUtils.getAnnotationsJar()), - Arrays.asList(javaFilesDir) - )); + protected TestModule createTestModule(String name) { + return new TestModule(name); } - protected File createJavaFilesDir() { - File javaFilesDir = new File(FileUtil.getTempDirectory(), ""java-files""); - try { - JetTestUtils.mkdirs(javaFilesDir); - } - catch (IOException e) { - throw UtilsPackage.rethrow(e); - } - return javaFilesDir; - } - - private static boolean writeJavaFile(@NotNull String fileName, @NotNull String content, @NotNull File javaFilesDir) { - try { - File javaFile = new File(javaFilesDir, fileName); - JetTestUtils.mkdirs(javaFile.getParentFile()); - Files.write(content, javaFile, Charset.forName(""utf-8"")); - return true; - } catch (Exception e) { - throw UtilsPackage.rethrow(e); - } + @Override + protected TestFile createTestFile(TestModule module, String fileName, String text, Map directives) { + return new TestFile(module, fileName, text, directives); } - protected void doTest(String filePath) throws IOException { - File file = new File(filePath); - final File javaFilesDir = createJavaFilesDir(); - - String expectedText = JetTestUtils.doLoadFile(file); - - class ModuleAndDependencies { - final TestModule module; - final List dependencies; - - ModuleAndDependencies(TestModule module, List dependencies) { - this.module = module; - this.dependencies = dependencies; - } - } - final Map modules = new HashMap(); - - List testFiles = - JetTestUtils.createTestFiles(file.getName(), expectedText, new JetTestUtils.TestFileFactory() { - @Override - public TestFile createFile( - @Nullable TestModule module, - @NotNull String fileName, - @NotNull String text, - @NotNull Map directives - ) { - if (fileName.endsWith("".java"")) { - writeJavaFile(fileName, text, javaFilesDir); - } - - return new TestFile(module, fileName, text, directives); - } - - @Override - public TestModule createModule(@NotNull String name, @NotNull List dependencies) { - TestModule module = new TestModule(name); - ModuleAndDependencies oldValue = modules.put(name, new ModuleAndDependencies(module, dependencies)); - assert oldValue == null : ""Module "" + name + "" declared more than once""; - - return module; - } - }); - + @Override + protected void doMultiFileTest(File file, final Map modules, List testFiles) { for (final ModuleAndDependencies moduleAndDependencies : modules.values()) { List dependencies = KotlinPackage.map( moduleAndDependencies.dependencies, @@ -168,7 +95,10 @@ public TestModule createModule(@NotNull String name, @NotNull List depen @Override public TestModule invoke(String name) { ModuleAndDependencies dependency = modules.get(name); - assert dependency != null : ""Dependency not found: "" + name + "" for module "" + moduleAndDependencies.module.getName(); + assert dependency != null : ""Dependency not found: "" + + name + + "" for module "" + + moduleAndDependencies.module.getName(); return dependency.module; } } diff --git a/compiler/tests/org/jetbrains/jet/checkers/KotlinMultiFileTestWithWithJava.java b/compiler/tests/org/jetbrains/jet/checkers/KotlinMultiFileTestWithWithJava.java new file mode 100644 index 0000000000000..e8fc04fab4aa7 --- /dev/null +++ b/compiler/tests/org/jetbrains/jet/checkers/KotlinMultiFileTestWithWithJava.java @@ -0,0 +1,127 @@ +/* + * Copyright 2010-2014 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.jet.checkers; + +import com.google.common.io.Files; +import com.intellij.openapi.util.io.FileUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.ConfigurationKind; +import org.jetbrains.jet.JetLiteFixture; +import org.jetbrains.jet.JetTestUtils; +import org.jetbrains.jet.TestJdkKind; +import org.jetbrains.jet.cli.jvm.compiler.JetCoreEnvironment; +import org.jetbrains.jet.config.CompilerConfiguration; +import org.jetbrains.jet.utils.UtilsPackage; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class KotlinMultiFileTestWithWithJava extends JetLiteFixture { + protected class ModuleAndDependencies { + final M module; + final List dependencies; + + ModuleAndDependencies(M module, List dependencies) { + this.module = module; + this.dependencies = dependencies; + } + } + + protected static boolean writeSourceFile(@NotNull String fileName, @NotNull String content, @NotNull File targetDir) { + try { + File sourceFile = new File(targetDir, fileName); + JetTestUtils.mkdirs(sourceFile.getParentFile()); + Files.write(content, sourceFile, Charset.forName(""utf-8"")); + return true; + } + catch (Exception e) { + throw UtilsPackage.rethrow(e); + } + } + + @Override + protected JetCoreEnvironment createEnvironment() { + File javaFilesDir = createJavaFilesDir(); + CompilerConfiguration configuration = JetTestUtils.compilerConfigurationForTests( + ConfigurationKind.JDK_AND_ANNOTATIONS, + TestJdkKind.MOCK_JDK, + Arrays.asList(JetTestUtils.getAnnotationsJar()), + Arrays.asList(javaFilesDir) + ); + return JetCoreEnvironment.createForTests(getTestRootDisposable(), configuration); + } + + protected File createJavaFilesDir() { + File dir = new File(FileUtil.getTempDirectory(), ""java-files""); + try { + JetTestUtils.mkdirs(dir); + } + catch (IOException e) { + throw UtilsPackage.rethrow(e); + } + return dir; + } + + protected void doTest(String filePath) throws Exception { + File file = new File(filePath); + final File javaFilesDir = createJavaFilesDir(); + + String expectedText = JetTestUtils.doLoadFile(file); + + final Map modules = new HashMap(); + + List testFiles = + JetTestUtils.createTestFiles(file.getName(), expectedText, new JetTestUtils.TestFileFactory() { + @Override + public F createFile( + @Nullable M module, + @NotNull String fileName, + @NotNull String text, + @NotNull Map directives + ) { + if (fileName.endsWith("".java"")) { + writeSourceFile(fileName, text, javaFilesDir); + } + + return createTestFile(module, fileName, text, directives); + } + + @Override + public M createModule(@NotNull String name, @NotNull List dependencies) { + M module = createTestModule(name); + ModuleAndDependencies oldValue = modules.put(name, new ModuleAndDependencies(module, dependencies)); + assert oldValue == null : ""Module "" + name + "" declared more than once""; + + return module; + } + }); + + doMultiFileTest(file, modules, testFiles); + } + + protected abstract M createTestModule(String name); + + protected abstract F createTestFile(M module, String fileName, String text, Map directives); + + protected abstract void doMultiFileTest(File file, Map modules, List files) throws Exception; +}" 9613f4fd719faac3cc4428ba560e4cc7c6d158a9,intellij-community,preferred focused component (IDEA-60570)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterPasswordDialog.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterPasswordDialog.java index 1598f6eef3877..ce19098caa15d 100644 --- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterPasswordDialog.java +++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/MasterPasswordDialog.java @@ -91,6 +91,11 @@ protected Action[] createActions() { new DialogWrapperExitAction(""&Reset Password"", RESET_USER_CODE), getCancelAction()}; } + @Override + public JComponent getPreferredFocusedComponent() { + return myMasterPasswordPasswordField; + } + /** * Ask password from user and set it to password safe instance *" a170f9ee4e77bc94ed51ff2d143422e27dc1bc01,hbase,HBASE-4131 Make the Replication Service pluggable- via a standard interface definition--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1174963 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt index ce41ed233ad4..1aa56c41fa80 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -3,6 +3,8 @@ Release 0.93.0 - Unreleased IMPROVEMENT HBASE-4132 Extend the WALActionsListener API to accomodate log archival (dhruba borthakur) + HBASE-4131 Make the Replication Service pluggable via a standard + interface definition (dhruba borthakur) Release 0.92.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/main/java/org/apache/hadoop/hbase/HConstants.java b/src/main/java/org/apache/hadoop/hbase/HConstants.java index 7ea64b7e7785..3af1bf030387 100644 --- a/src/main/java/org/apache/hadoop/hbase/HConstants.java +++ b/src/main/java/org/apache/hadoop/hbase/HConstants.java @@ -473,8 +473,17 @@ public static enum Modify { */ public static int DEFAULT_HBASE_RPC_TIMEOUT = 60000; + /* + * cluster replication constants. + */ public static final String REPLICATION_ENABLE_KEY = ""hbase.replication""; + public static final String + REPLICATION_SOURCE_SERVICE_CLASSNAME = ""hbase.replication.source.service""; + public static final String + REPLICATION_SINK_SERVICE_CLASSNAME = ""hbase.replication.sink.service""; + public static final String REPLICATION_SERVICE_CLASSNAME_DEFAULT = + ""org.apache.hadoop.hbase.replication.regionserver.Replication""; /** HBCK special code name used as server name when manipulating ZK nodes */ public static final String HBCK_CODE_NAME = ""HBCKServerName""; diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 5869c18412d9..9f1fd8fe2a6b 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -54,6 +54,7 @@ import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Chore; +import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.hbase.ClockOutOfSyncException; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HBaseConfiguration; @@ -284,7 +285,8 @@ public class HRegionServer implements HRegionInterface, HBaseRPCErrorHandler, private ExecutorService service; // Replication services. If no replication, this handler will be null. - private Replication replicationHandler; + private ReplicationSourceService replicationSourceHandler; + private ReplicationSinkService replicationSinkHandler; private final RegionServerAccounting regionServerAccounting; @@ -1169,12 +1171,7 @@ private HLog setupWALAndReplication() throws IOException { // Instantiate replication manager if replication enabled. Pass it the // log directories. - try { - this.replicationHandler = Replication.isReplication(this.conf)? - new Replication(this, this.fs, logdir, oldLogDir): null; - } catch (KeeperException e) { - throw new IOException(""Failed replication handler create"", e); - } + createNewReplicationInstance(conf, this, this.fs, logdir, oldLogDir); return instantiateHLog(logdir, oldLogDir); } @@ -1201,9 +1198,10 @@ protected List getWALActionListeners() { // Log roller. this.hlogRoller = new LogRoller(this, this); listeners.add(this.hlogRoller); - if (this.replicationHandler != null) { + if (this.replicationSourceHandler != null && + this.replicationSourceHandler.getWALActionsListener() != null) { // Replication handler is an implementation of WALActionsListener. - listeners.add(this.replicationHandler); + listeners.add(this.replicationSourceHandler.getWALActionsListener()); } return listeners; } @@ -1351,8 +1349,13 @@ public void uncaughtException(Thread t, Throwable e) { // that port is occupied. Adjust serverInfo if this is the case. this.webuiport = putUpWebUI(); - if (this.replicationHandler != null) { - this.replicationHandler.startReplicationServices(); + if (this.replicationSourceHandler == this.replicationSinkHandler && + this.replicationSourceHandler != null) { + this.replicationSourceHandler.startReplicationService(); + } else if (this.replicationSourceHandler != null) { + this.replicationSourceHandler.startReplicationService(); + } else if (this.replicationSinkHandler != null) { + this.replicationSinkHandler.startReplicationService(); } // Start Server. This service is like leases in that it internally runs @@ -1557,11 +1560,32 @@ protected void join() { this.compactSplitThread.join(); } if (this.service != null) this.service.shutdown(); - if (this.replicationHandler != null) { - this.replicationHandler.join(); + if (this.replicationSourceHandler != null && + this.replicationSourceHandler == this.replicationSinkHandler) { + this.replicationSourceHandler.stopReplicationService(); + } else if (this.replicationSourceHandler != null) { + this.replicationSourceHandler.stopReplicationService(); + } else if (this.replicationSinkHandler != null) { + this.replicationSinkHandler.stopReplicationService(); } } + /** + * @return Return the object that implements the replication + * source service. + */ + ReplicationSourceService getReplicationSourceService() { + return replicationSourceHandler; + } + + /** + * @return Return the object that implements the replication + * sink service. + */ + ReplicationSinkService getReplicationSinkService() { + return replicationSinkHandler; + } + /** * Get the current master from ZooKeeper and open the RPC connection to it. * @@ -3063,6 +3087,63 @@ public ExecutorService getExecutorService() { // Main program and support routines // + /** + * Load the replication service objects, if any + */ + static private void createNewReplicationInstance(Configuration conf, + HRegionServer server, FileSystem fs, Path logDir, Path oldLogDir) throws IOException{ + + // If replication is not enabled, then return immediately. + if (!conf.getBoolean(HConstants.REPLICATION_ENABLE_KEY, false)) { + return; + } + + // read in the name of the source replication class from the config file. + String sourceClassname = conf.get(HConstants.REPLICATION_SOURCE_SERVICE_CLASSNAME, + HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT); + + // read in the name of the sink replication class from the config file. + String sinkClassname = conf.get(HConstants.REPLICATION_SINK_SERVICE_CLASSNAME, + HConstants.REPLICATION_SERVICE_CLASSNAME_DEFAULT); + + // If both the sink and the source class names are the same, then instantiate + // only one object. + if (sourceClassname.equals(sinkClassname)) { + server.replicationSourceHandler = (ReplicationSourceService) + newReplicationInstance(sourceClassname, + conf, server, fs, logDir, oldLogDir); + server.replicationSinkHandler = (ReplicationSinkService) + server.replicationSinkHandler; + } + else { + server.replicationSourceHandler = (ReplicationSourceService) + newReplicationInstance(sourceClassname, + conf, server, fs, logDir, oldLogDir); + server.replicationSinkHandler = (ReplicationSinkService) + newReplicationInstance(sinkClassname, + conf, server, fs, logDir, oldLogDir); + } + } + + static private ReplicationService newReplicationInstance(String classname, + Configuration conf, HRegionServer server, FileSystem fs, Path logDir, + Path oldLogDir) throws IOException{ + + Class clazz = null; + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + clazz = Class.forName(classname, true, classLoader); + } catch (java.lang.ClassNotFoundException nfe) { + throw new IOException(""Cound not find class for "" + classname); + } + + // create an instance of the replication object. + ReplicationService service = (ReplicationService) + ReflectionUtils.newInstance(clazz, conf); + service.initialize(server, fs, logDir, oldLogDir); + return service; + } + /** * @param hrs * @return Thread the RegionServer is running in correctly named. @@ -3115,8 +3196,8 @@ public static HRegionServer constructRegionServer( public void replicateLogEntries(final HLog.Entry[] entries) throws IOException { checkOpen(); - if (this.replicationHandler == null) return; - this.replicationHandler.replicateLogEntries(entries); + if (this.replicationSinkHandler == null) return; + this.replicationSinkHandler.replicateLogEntries(entries); } /** diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationService.java b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationService.java new file mode 100644 index 000000000000..489e1410dfb3 --- /dev/null +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationService.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.regionserver; + +import java.io.IOException; + +import org.apache.hadoop.hbase.Server; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; + +/** + * Gateway to Cluster Replication. + * Used by {@link org.apache.hadoop.hbase.regionserver.HRegionServer}. + * One such application is a cross-datacenter + * replication service that can keep two hbase clusters in sync. + */ +public interface ReplicationService { + + /** + * Initializes the replication service object. + * @throws IOException + */ + public void initialize(Server rs, FileSystem fs, Path logdir, + Path oldLogDir) throws IOException; + + /** + * Start replication services. + * @throws IOException + */ + public void startReplicationService() throws IOException; + + /** + * Stops replication service. + */ + public void stopReplicationService(); +} diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSinkService.java b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSinkService.java new file mode 100644 index 000000000000..a5706731e803 --- /dev/null +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSinkService.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.regionserver; + +import java.io.IOException; + +import org.apache.hadoop.hbase.regionserver.wal.HLog; + +/** + * A sink for a replication stream has to expose this service. + * This service allows an application to hook into the + * regionserver and behave as a replication sink. + */ +public interface ReplicationSinkService extends ReplicationService { + + /** + * Carry on the list of log entries down to the sink + * @param entries list of entries to replicate + * @throws IOException + */ + public void replicateLogEntries(HLog.Entry[] entries) throws IOException; +} diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSourceService.java b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSourceService.java new file mode 100644 index 000000000000..af0a7d887e20 --- /dev/null +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/ReplicationSourceService.java @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.regionserver; + +import java.io.IOException; + +import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener; + +/** + * A source for a replication stream has to expose this service. + * This service allows an application to hook into the + * regionserver and watch for new transactions. + */ +public interface ReplicationSourceService extends ReplicationService { + + /** + * Returns a WALObserver for the service. This is needed to + * observe log rolls and log archival events. + */ + public WALActionsListener getWALActionsListener(); +} diff --git a/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java b/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java index 0ce776400663..9d6b9ccefb70 100644 --- a/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java +++ b/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java @@ -31,6 +31,8 @@ import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.Server; +import org.apache.hadoop.hbase.regionserver.ReplicationSourceService; +import org.apache.hadoop.hbase.regionserver.ReplicationSinkService; import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.apache.hadoop.hbase.regionserver.wal.HLogKey; import org.apache.hadoop.hbase.regionserver.wal.WALEdit; @@ -47,15 +49,16 @@ /** * Gateway to Replication. Used by {@link org.apache.hadoop.hbase.regionserver.HRegionServer}. */ -public class Replication implements WALActionsListener { - private final boolean replication; - private final ReplicationSourceManager replicationManager; +public class Replication implements WALActionsListener, + ReplicationSourceService, ReplicationSinkService { + private boolean replication; + private ReplicationSourceManager replicationManager; private final AtomicBoolean replicating = new AtomicBoolean(true); - private final ReplicationZookeeper zkHelper; - private final Configuration conf; + private ReplicationZookeeper zkHelper; + private Configuration conf; private ReplicationSink replicationSink; // Hosting server - private final Server server; + private Server server; /** * Instantiate the replication management (if rep is enabled). @@ -64,16 +67,29 @@ public class Replication implements WALActionsListener { * @param logDir * @param oldLogDir directory where logs are archived * @throws IOException - * @throws KeeperException */ public Replication(final Server server, final FileSystem fs, - final Path logDir, final Path oldLogDir) - throws IOException, KeeperException { + final Path logDir, final Path oldLogDir) throws IOException{ + initialize(server, fs, logDir, oldLogDir); + } + + /** + * Empty constructor + */ + public Replication() { + } + + public void initialize(final Server server, final FileSystem fs, + final Path logDir, final Path oldLogDir) throws IOException { this.server = server; this.conf = this.server.getConfiguration(); this.replication = isReplication(this.conf); if (replication) { - this.zkHelper = new ReplicationZookeeper(server, this.replicating); + try { + this.zkHelper = new ReplicationZookeeper(server, this.replicating); + } catch (KeeperException ke) { + throw new IOException(""Failed replication handler create"", ke); + } this.replicationManager = new ReplicationSourceManager(zkHelper, conf, this.server, fs, this.replicating, logDir, oldLogDir) ; } else { @@ -82,14 +98,27 @@ public Replication(final Server server, final FileSystem fs, } } - /** - * @param c Configuration to look at - * @return True if replication is enabled. - */ + /** + * @param c Configuration to look at + * @return True if replication is enabled. + */ public static boolean isReplication(final Configuration c) { return c.getBoolean(REPLICATION_ENABLE_KEY, false); } + /* + * Returns an object to listen to new hlog changes + **/ + public WALActionsListener getWALActionsListener() { + return this; + } + /** + * Stops replication service. + */ + public void stopReplicationService() { + join(); + } + /** * Join with the replication threads */ @@ -115,7 +144,7 @@ public void replicateLogEntries(HLog.Entry[] entries) throws IOException { * it starts * @throws IOException */ - public void startReplicationServices() throws IOException { + public void startReplicationService() throws IOException { if (this.replication) { this.replicationManager.init(); this.replicationSink = new ReplicationSink(this.conf, this.server);" 311520d14682a1f3096dc9307da3e5fcb82936ab,elasticsearch,add peer recovery status to the indices status- API exposing both on going and summary when recovering from a peer shard--,a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/ShardStatus.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/ShardStatus.java index 882b74d25b477..be39f8bd43023 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/ShardStatus.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/ShardStatus.java @@ -112,7 +112,7 @@ public static Stage fromValue(byte value) { final long startTime; - final long took; + final long time; final long retryTime; @@ -124,11 +124,11 @@ public static Stage fromValue(byte value) { final long recoveredTranslogOperations; - public PeerRecoveryStatus(Stage stage, long startTime, long took, long retryTime, long indexSize, long reusedIndexSize, + public PeerRecoveryStatus(Stage stage, long startTime, long time, long retryTime, long indexSize, long reusedIndexSize, long recoveredIndexSize, long recoveredTranslogOperations) { this.stage = stage; this.startTime = startTime; - this.took = took; + this.time = time; this.retryTime = retryTime; this.indexSize = indexSize; this.reusedIndexSize = reusedIndexSize; @@ -148,12 +148,12 @@ public long getStartTime() { return this.startTime; } - public TimeValue took() { - return TimeValue.timeValueMillis(took); + public TimeValue time() { + return TimeValue.timeValueMillis(time); } - public TimeValue getTook() { - return took(); + public TimeValue getTime() { + return time(); } public TimeValue retryTime() { @@ -321,7 +321,7 @@ public static ShardStatus readIndexShardStatus(StreamInput in) throws IOExceptio out.writeBoolean(true); out.writeByte(peerRecoveryStatus.stage.value); out.writeVLong(peerRecoveryStatus.startTime); - out.writeVLong(peerRecoveryStatus.took); + out.writeVLong(peerRecoveryStatus.time); out.writeVLong(peerRecoveryStatus.retryTime); out.writeVLong(peerRecoveryStatus.indexSize); out.writeVLong(peerRecoveryStatus.reusedIndexSize); diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java index 466e4c9b35651..e5db74b8c135e 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/status/TransportIndicesStatusAction.java @@ -172,7 +172,7 @@ public class TransportIndicesStatusAction extends TransportBroadcastOperationAct default: stage = ShardStatus.PeerRecoveryStatus.Stage.INIT; } - shardStatus.peerRecoveryStatus = new ShardStatus.PeerRecoveryStatus(stage, peerRecoveryStatus.startTime(), peerRecoveryStatus.took(), + shardStatus.peerRecoveryStatus = new ShardStatus.PeerRecoveryStatus(stage, peerRecoveryStatus.startTime(), peerRecoveryStatus.time(), peerRecoveryStatus.retryTime(), peerRecoveryStatus.phase1TotalSize(), peerRecoveryStatus.phase1ExistingTotalSize(), peerRecoveryStatus.currentFilesSize(), peerRecoveryStatus.currentTranslogOperations()); } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/PeerRecoveryStatus.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/PeerRecoveryStatus.java index e64b99c4c562e..1a5251badf3c4 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/PeerRecoveryStatus.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/PeerRecoveryStatus.java @@ -43,7 +43,7 @@ public static enum Stage { ConcurrentMap openIndexOutputs = ConcurrentCollections.newConcurrentMap(); final long startTime = System.currentTimeMillis(); - long took; + long time; volatile long retryTime = 0; List phase1FileNames; List phase1FileSizes; @@ -60,8 +60,8 @@ public long startTime() { return startTime; } - public long took() { - return this.took; + public long time() { + return this.time; } public long retryTime() { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java index b62574be15e9e..291e9d6ef7161 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoveryTarget.java @@ -103,7 +103,15 @@ public static class Actions { } public PeerRecoveryStatus peerRecoveryStatus(ShardId shardId) { - return onGoingRecoveries.get(shardId); + PeerRecoveryStatus peerRecoveryStatus = onGoingRecoveries.get(shardId); + if (peerRecoveryStatus == null) { + return null; + } + // update how long it takes if we are still recovering... + if (peerRecoveryStatus.startTime > 0 && peerRecoveryStatus.stage != PeerRecoveryStatus.Stage.DONE) { + peerRecoveryStatus.time = System.currentTimeMillis() - peerRecoveryStatus.startTime; + } + return peerRecoveryStatus; } public void startRecovery(final StartRecoveryRequest request, final boolean fromRetry, final RecoveryListener listener) { @@ -313,7 +321,7 @@ class FinalizeRecoveryRequestHandler extends BaseTransportRequestHandler 0) { - builder.field(""took"", peerRecoveryStatus.took()); - builder.field(""took_in_millis"", peerRecoveryStatus.took().millis()); - } + builder.field(""time"", peerRecoveryStatus.time()); + builder.field(""took_in_millis"", peerRecoveryStatus.time().millis()); builder.field(""retry_time"", peerRecoveryStatus.retryTime()); builder.field(""retry_time_in_millis"", peerRecoveryStatus.retryTime().millis());" c2f8ee105b99622ad6f3f0c9cee3448cc5b869c7,elasticsearch,"add a marker CachedFilter this allows to easily- and globally check if we cache a filter or not, all filter caching uses this- marker interface--",p,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/common/lucene/search/CachedFilter.java b/src/main/java/org/elasticsearch/common/lucene/search/CachedFilter.java new file mode 100644 index 0000000000000..6699fe6d36d4d --- /dev/null +++ b/src/main/java/org/elasticsearch/common/lucene/search/CachedFilter.java @@ -0,0 +1,32 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.elasticsearch.common.lucene.search; + +import org.apache.lucene.search.Filter; + +/** + * A marker indicating that this is a cached filter. + */ +public abstract class CachedFilter extends Filter { + + public static boolean isCached(Filter filter) { + return filter instanceof CachedFilter; + } +} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/index/cache/filter/FilterCache.java b/src/main/java/org/elasticsearch/index/cache/filter/FilterCache.java index c5df2d84cea51..dfd05eb7d5f5d 100644 --- a/src/main/java/org/elasticsearch/index/cache/filter/FilterCache.java +++ b/src/main/java/org/elasticsearch/index/cache/filter/FilterCache.java @@ -43,8 +43,6 @@ public EntriesStats(long sizeInBytes, long count) { Filter cache(Filter filterToCache); - boolean isCached(Filter filter); - void clear(IndexReader reader); void clear(String reason); diff --git a/src/main/java/org/elasticsearch/index/cache/filter/none/NoneFilterCache.java b/src/main/java/org/elasticsearch/index/cache/filter/none/NoneFilterCache.java index 5e365fb3d248e..81275ef948b47 100644 --- a/src/main/java/org/elasticsearch/index/cache/filter/none/NoneFilterCache.java +++ b/src/main/java/org/elasticsearch/index/cache/filter/none/NoneFilterCache.java @@ -54,11 +54,6 @@ public Filter cache(Filter filterToCache) { return filterToCache; } - @Override - public boolean isCached(Filter filter) { - return false; - } - @Override public void clear(String reason) { // nothing to do here diff --git a/src/main/java/org/elasticsearch/index/cache/filter/weighted/WeightedFilterCache.java b/src/main/java/org/elasticsearch/index/cache/filter/weighted/WeightedFilterCache.java index 4e872e1bab576..30ed8a0fe9edf 100644 --- a/src/main/java/org/elasticsearch/index/cache/filter/weighted/WeightedFilterCache.java +++ b/src/main/java/org/elasticsearch/index/cache/filter/weighted/WeightedFilterCache.java @@ -33,6 +33,7 @@ import org.elasticsearch.ElasticSearchException; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.docset.DocIdSets; +import org.elasticsearch.common.lucene.search.CachedFilter; import org.elasticsearch.common.lucene.search.NoCacheFilter; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.metrics.MeanMetric; @@ -122,18 +123,13 @@ public Filter cache(Filter filterToCache) { if (filterToCache instanceof NoCacheFilter) { return filterToCache; } - if (isCached(filterToCache)) { + if (CachedFilter.isCached(filterToCache)) { return filterToCache; } return new FilterCacheFilterWrapper(filterToCache, this); } - @Override - public boolean isCached(Filter filter) { - return filter instanceof FilterCacheFilterWrapper; - } - - static class FilterCacheFilterWrapper extends Filter { + static class FilterCacheFilterWrapper extends CachedFilter { private final Filter filter;" 3b68aaa84cfa714a4d1b5ef0c615d924e75d2be0,kotlin,JS: fix rhino 64k issue--,c,https://github.com/JetBrains/kotlin,"diff --git a/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java b/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java index fe73f3f5c0419..ebe8d8b21ffbf 100644 --- a/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java +++ b/js/js.tests/test/org/jetbrains/kotlin/js/test/rhino/RhinoUtils.java @@ -109,6 +109,7 @@ private static void runFileWithRhino(@NotNull String inputFile, catch (IOException e) { throw new RuntimeException(e); } + context.setOptimizationLevel(-1); context.evaluateString(scope, result, inputFile, 1, null); }" caf2af077a3a6454cef39678564391c4abaf8eeb,spring-framework,Polish MockHttpServletRequestBuilder--,p,https://github.com/spring-projects/spring-framework,"diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java index 606b3ee74d0d..5e4b18db7feb 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java @@ -73,6 +73,8 @@ protected void service(HttpServletRequest request, HttpServletResponse response) super.service(request, response); + // TODO: add CountDownLatch to DeferredResultInterceptor and wait in request().asyncResult(..) + Object handler = getMvcResult(request).getHandler(); if (asyncManager.isConcurrentHandlingStarted() && !deferredResultInterceptor.wasInvoked) { if (!callableInterceptor.await()) { diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java index 8d31b4df85fe..c1f8521e1e5d 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java @@ -202,6 +202,21 @@ public MockHttpServletRequestBuilder content(byte[] content) { return this; } + /** + * Set the request body as a UTF-8 String. + * + * @param content the body content + */ + public MockHttpServletRequestBuilder content(String content) { + try { + this.content = content.getBytes(""UTF-8""); + } + catch (UnsupportedEncodingException e) { + // should never happen + } + return this; + } + /** * Add the given cookies to the request. Cookies are always added. * diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java index e9a68a350bf9..5bc401583fb1 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java @@ -84,9 +84,6 @@ public void match(MvcResult result) { /** * Assert the result from asynchronous processing with the given matcher. - * This method can be used when a controller method returns {@link Callable} - * or {@link AsyncTask}. The value matched is the value returned from the - * {@code Callable} or the exception raised. */ public ResultMatcher asyncResult(final Matcher matcher) { return new ResultMatcher() { @@ -95,7 +92,7 @@ public void match(MvcResult result) { HttpServletRequest request = result.getRequest(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); MatcherAssert.assertThat(""Async started"", request.isAsyncStarted(), equalTo(true)); - MatcherAssert.assertThat(""Callable result"", (T) asyncManager.getConcurrentResult(), matcher); + MatcherAssert.assertThat(""Async result"", (T) asyncManager.getConcurrentResult(), matcher); } }; }" 00feeb78cbd1f63af1736c775f6e228df6656671,intellij-community,IDEA-127075 IDE hang on file structure--,c,https://github.com/JetBrains/intellij-community,"diff --git a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java index c1afbee6ada4c..669080107623b 100644 --- a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java +++ b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/PsiMethodTreeElement.java @@ -51,12 +51,12 @@ public Collection getChildrenBase() { final PsiMethod element = getElement(); if (element == null || element instanceof SyntheticElement) return result; - final TextRange range = element.getTextRange(); - if (range == null) return result; - final PsiFile psiFile = element.getContainingFile(); if (psiFile == null || psiFile instanceof PsiCompiledElement) return result; + final TextRange range = element.getTextRange(); + if (range == null) return result; + final String fileText = psiFile.getText(); if (fileText == null) return result;" 311bd5f25d55471c807acea3d94e655ebcbc3eb9,kotlin,One more test added--,p,https://github.com/JetBrains/kotlin,"diff --git a/idea/testData/intentions/operatorToFunction/assignment.kt b/idea/testData/intentions/operatorToFunction/assignment.kt new file mode 100644 index 0000000000000..ad6ec3cb8bba0 --- /dev/null +++ b/idea/testData/intentions/operatorToFunction/assignment.kt @@ -0,0 +1,9 @@ +interface C { + operator fun set(p: String, value: Int) +} + +class D(val c: C) { + fun foo() { + this.c[""""] = 10 + } +} diff --git a/idea/testData/intentions/operatorToFunction/assignment.kt.after b/idea/testData/intentions/operatorToFunction/assignment.kt.after new file mode 100644 index 0000000000000..9183b744f775a --- /dev/null +++ b/idea/testData/intentions/operatorToFunction/assignment.kt.after @@ -0,0 +1,9 @@ +interface C { + operator fun set(p: String, value: Int) +} + +class D(val c: C) { + fun foo() { + this.c.set("""", 10) + } +} diff --git a/idea/tests/org/jetbrains/kotlin/idea/intentions/IntentionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/intentions/IntentionTestGenerated.java index 0b34a66d13ae6..bb5b9bd88d00d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/intentions/IntentionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/intentions/IntentionTestGenerated.java @@ -5859,6 +5859,12 @@ public void testArrayAssignmentMultipleIndex() throws Exception { doTest(fileName); } + @TestMetadata(""assignment.kt"") + public void testAssignment() throws Exception { + String fileName = JetTestUtils.navigationMetadata(""idea/testData/intentions/operatorToFunction/assignment.kt""); + doTest(fileName); + } + @TestMetadata(""binaryEqualsEqualsNullableOperands.kt"") public void testBinaryEqualsEqualsNullableOperands() throws Exception { String fileName = JetTestUtils.navigationMetadata(""idea/testData/intentions/operatorToFunction/binaryEqualsEqualsNullableOperands.kt"");" 7eb1ca53b3f1acad4d12cf866075ceace5aabf1f,hadoop,YARN-1608. LinuxContainerExecutor has a few DEBUG- messages at INFO level (kasha)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1558875 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 0b37d93a07cb9..0cadb4bbac2b8 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -325,6 +325,9 @@ Release 2.4.0 - UNRELEASED YARN-1351. Invalid string format in Fair Scheduler log warn message (Konstantin Weitz via Sandy Ryza) + YARN-1608. LinuxContainerExecutor has a few DEBUG messages at INFO level + (kasha) + Release 2.3.0 - UNRELEASED INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java index 3e097815d10cc..0b1af0dd472e0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/LinuxContainerExecutor.java @@ -218,8 +218,6 @@ public void startLocalizer(Path nmPrivateContainerTokensPath, } String[] commandArray = command.toArray(new String[command.size()]); ShellCommandExecutor shExec = new ShellCommandExecutor(commandArray); - // TODO: DEBUG - LOG.info(""initApplication: "" + Arrays.toString(commandArray)); if (LOG.isDebugEnabled()) { LOG.debug(""initApplication: "" + Arrays.toString(commandArray)); } @@ -275,8 +273,9 @@ public int launchContainer(Container container, String[] commandArray = command.toArray(new String[command.size()]); shExec = new ShellCommandExecutor(commandArray, null, // NM's cwd container.getLaunchContext().getEnvironment()); // sanitized env - // DEBUG - LOG.info(""launchContainer: "" + Arrays.toString(commandArray)); + if (LOG.isDebugEnabled()) { + LOG.debug(""launchContainer: "" + Arrays.toString(commandArray)); + } shExec.execute(); if (LOG.isDebugEnabled()) { logOutput(shExec.getOutput()); @@ -375,7 +374,6 @@ public void deleteAsUser(String user, Path dir, Path... baseDirs) { } String[] commandArray = command.toArray(new String[command.size()]); ShellCommandExecutor shExec = new ShellCommandExecutor(commandArray); - LOG.info("" -- DEBUG -- deleteAsUser: "" + Arrays.toString(commandArray)); if (LOG.isDebugEnabled()) { LOG.debug(""deleteAsUser: "" + Arrays.toString(commandArray)); }" 98a24828255cde13eaee893eafc9a049bb2183a7,elasticsearch,"Testing: Add test rule to repeat tests on binding- exceptions--Due to the possibility of ports being already used when choosing a-random port, it makes sense to simply repeat a unit test upon a bind-exception.--This commit adds a junit rule, which does exactly this and does not-require you to change the test code and add loops.--Closes -9010-",c,https://github.com/elastic/elasticsearch,"diff --git a/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java b/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java index 5a1c882017946..95797c51396a4 100644 --- a/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java +++ b/src/test/java/org/elasticsearch/transport/netty/NettyTransportMultiPortTests.java @@ -33,6 +33,7 @@ import org.elasticsearch.test.cache.recycler.MockBigArrays; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; +import org.junit.Rule; import org.junit.Test; import java.io.IOException; @@ -46,6 +47,11 @@ public class NettyTransportMultiPortTests extends ElasticsearchTestCase { + public static int MAX_RETRIES = 10; + + @Rule + public RepeatOnBindExceptionRule repeatOnBindExceptionRule = new RepeatOnBindExceptionRule(logger, MAX_RETRIES); + private NettyTransport nettyTransport; private ThreadPool threadPool; diff --git a/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java b/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java new file mode 100644 index 0000000000000..4db593499fb18 --- /dev/null +++ b/src/test/java/org/elasticsearch/transport/netty/RepeatOnBindExceptionRule.java @@ -0,0 +1,69 @@ +/* + * Licensed to Elasticsearch under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch licenses this file to you under + * the Apache License, Version 2.0 (the ""License""); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.elasticsearch.transport.netty; + +import org.elasticsearch.common.logging.ESLogger; +import org.elasticsearch.transport.BindTransportException; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; + +/** + * A helper rule to catch all BindTransportExceptions + * and rerun the test for a configured number of times + */ +public class RepeatOnBindExceptionRule implements TestRule { + + private ESLogger logger; + private int retryCount; + + /** + * + * @param logger the es logger from the test class + * @param retryCount number of amounts to try a single test before failing + */ + public RepeatOnBindExceptionRule(ESLogger logger, int retryCount) { + this.logger = logger; + this.retryCount = retryCount; + } + + @Override + public Statement apply(final Statement base, Description description) { + + return new Statement() { + @Override + public void evaluate() throws Throwable { + Throwable caughtThrowable = null; + + for (int i = 0; i < retryCount; i++) { + try { + base.evaluate(); + return; + } catch (BindTransportException t) { + caughtThrowable = t; + logger.info(""Bind exception occurred, rerunning the test after [{}] failures"", t, i+1); + } + } + logger.error(""Giving up after [{}] failures... marking test as failed"", retryCount); + throw caughtThrowable; + } + }; + + } +}" 57cf199d7477ddba4c623960c265f356304f4045,drools,fix WELD problem caused by having a beans.xml in- drools-compiler--,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/resources/META-INF/beans.xml b/drools-compiler/src/main/resources/META-INF/beans.xml deleted file mode 100644 index b87599caa0a..00000000000 --- a/drools-compiler/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - \ No newline at end of file diff --git a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java index 2a3de24eb45..b43c20a870e 100644 --- a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java +++ b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java @@ -250,6 +250,12 @@ public void testCompileAndCDI() throws IOException, File fle1 = fld1.getFile( ""KProjectTestClassImpl.java"" ); fle1.create( new ByteArrayInputStream( generateKProjectTestClassImpl( kproj ).getBytes() ) ); + Folder fld2 = trgMfs.getFolder( ""META-INF"" ); + fld2.create(); + File fle2 = fld2.getFile( ""beans.xml"" ); + fle2.create( new ByteArrayInputStream( generateBeansXML( kproj ).getBytes() ) ); + + List inputClasses = new ArrayList(); inputClasses.add( ""org/drools/cdi/test/KProjectTestClassImpl.java"" ); @@ -445,6 +451,14 @@ public String generateKProjectTestClassImpl(KProject kproject) { return s; } + public String generateBeansXML(KProject kproject) { + String s = ""\n"" + + ""\n"" + + """"; + + return s; + } + public static String filenameToClassname(String filename) { return filename.substring( 0, filename.lastIndexOf( "".java"" ) ).replace( '/', '.' ).replace( '\\', '.' ); }" 541aae12ef82767479bcd53afb3681b46dd890a5,spring-framework,SPR-5802 - NullPointerException when using- @CookieValue annotation--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java index f6b7c4204360..e8fa23d6ac5f 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java @@ -600,9 +600,12 @@ protected Object resolveCookieValue(String cookieName, Class paramType, NativeWe if (Cookie.class.isAssignableFrom(paramType)) { return cookieValue; } - else { + else if (cookieValue != null) { return cookieValue.getValue(); } + else { + return null; + } } @Override" 473f7cf6ab558225908e9edaa56a1a6d9845b9c1,orientdb,fix for use of different serializer by the db- compare--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java b/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java index a608f4f09a2..0babd7a27a0 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/tool/ODatabaseCompare.java @@ -18,6 +18,7 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.OCommandOutputListener; +import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.OClusterPosition; @@ -497,7 +498,9 @@ private boolean compareRecords(ODocumentHelper.RIDMapper ridMapper) { final OClusterPosition db1Max = db1Range[1]; final OClusterPosition db2Max = db2Range[1]; + ODatabaseRecordThreadLocal.INSTANCE.set(databaseDocumentTxOne); final ODocument doc1 = new ODocument(); + ODatabaseRecordThreadLocal.INSTANCE.set(databaseDocumentTxTwo); final ODocument doc2 = new ODocument(); final ORecordId rid = new ORecordId(clusterId);" 829bc369078a940aa757f96b1cbf310fa4ac705f,intellij-community,fix--,c,https://github.com/JetBrains/intellij-community,"diff --git a/lang-api/src/com/intellij/psi/ResolveState.java b/lang-api/src/com/intellij/psi/ResolveState.java index 34533739244d7..4915c2f1604fa 100644 --- a/lang-api/src/com/intellij/psi/ResolveState.java +++ b/lang-api/src/com/intellij/psi/ResolveState.java @@ -10,18 +10,19 @@ public class ResolveState { private Map myValues = null; - private static final ResolveState ourInitialState = new ResolveState(); + private static final ResolveState ourInitialState; static { - ResolveState.defaultsTo(PsiSubstitutor.KEY, PsiSubstitutor.EMPTY); - } + ourInitialState = new ResolveState(); + ourInitialState.myValues = new THashMap(); + } public static ResolveState initial() { return ourInitialState; } public static void defaultsTo(Key key, T value) { - initial().put(key, value); + ourInitialState.myValues.put(key, value); } public ResolveState put(Key key, T value) { diff --git a/openapi/src/com/intellij/psi/JavaPsiFacade.java b/openapi/src/com/intellij/psi/JavaPsiFacade.java index 26e0879268edc..f5fc856185cfe 100644 --- a/openapi/src/com/intellij/psi/JavaPsiFacade.java +++ b/openapi/src/com/intellij/psi/JavaPsiFacade.java @@ -18,6 +18,9 @@ public static JavaPsiFacade getInstance(Project project) { return ServiceManager.getService(project, JavaPsiFacade.class); } + static { + ResolveState.defaultsTo(PsiSubstitutor.KEY, PsiSubstitutor.EMPTY); + } /** * Searches the project and all its libraries for a class with the specified full-qualified" 1eee950ac167c1bc02918819c84e6cccb9eebb5f,orientdb,OPLA: supported invocation of Java static methods--,a,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java index 7b9f1d127d6..817898076d4 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java +++ b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java @@ -15,6 +15,7 @@ */ package com.orientechnologies.orient.core.processor.block; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -51,12 +52,44 @@ public Object processBlock(OComposableProcessor iManager, final OCommandContext args = null; final OFunction f = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getFunctionLibrary().getFunction(function); - if (f == null) - throw new OProcessException(""Function '"" + function + ""' was not found""); + if (f != null) { + debug(iContext, ""Calling: "" + function + ""("" + Arrays.toString(args) + "")...""); + return f.executeInContext(iContext, args); + } - debug(iContext, ""Calling: "" + function + ""("" + Arrays.toString(args) + "")...""); + int lastDot = function.lastIndexOf('.'); + if (lastDot > -1) { + final String clsName = function.substring(0, lastDot); + final String methodName = function.substring(lastDot + 1); + Class cls = null; + try { + cls = Class.forName(clsName); - return f.executeInContext(iContext, args); + Class[] argTypes = new Class[args.length]; + for (int i = 0; i < args.length; ++i) + argTypes[i] = args[i].getClass(); + + Method m = cls.getMethod(methodName, argTypes); + return m.invoke(null, args); + } catch (NoSuchMethodException e) { + + for (Method m : cls.getMethods()) { + if (m.getName().equals(methodName) && m.getParameterTypes().length == args.length) { + try { + return m.invoke(null, args); + } catch (Exception e1) { + e1.printStackTrace(); + throw new OProcessException(""Error on call function '"" + function + ""'"", e); + } + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + throw new OProcessException(""Function '"" + function + ""' was not found""); } @Override" ed7166227500891e13c982a2f681962a6b56e5f4,elasticsearch,add debug log if using compressed stored fields--,p,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/index/store/Store.java b/src/main/java/org/elasticsearch/index/store/Store.java index 18d98058eebc2..44360f90f1bc9 100644 --- a/src/main/java/org/elasticsearch/index/store/Store.java +++ b/src/main/java/org/elasticsearch/index/store/Store.java @@ -110,6 +110,9 @@ public Store(ShardId shardId, @IndexSettings Settings indexSettings, IndexStore this.directory = new StoreDirectory(directoryService.build()); this.compressedStoredFields = componentSettings.getAsBoolean(""compress.stored_fields"", false); + + logger.debug(""using compress.stored_fields [{}]"", compressedStoredFields); + indexSettingsService.addListener(applySettings); }" 6a85160cfa4f99167f29a1323d0175703fb57816,camel,Fixed test--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1407748 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java index e4c9658e37864..4625e7cd39ba4 100644 --- a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java +++ b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java @@ -65,10 +65,16 @@ public void testSplitAttachments() throws Exception { Message second = mock.getReceivedExchanges().get(1).getIn(); assertEquals(1, first.getAttachments().size()); - assertEquals(""logo.jpeg"", first.getAttachments().keySet().iterator().next()); - assertEquals(1, second.getAttachments().size()); - assertEquals(""license.txt"", second.getAttachments().keySet().iterator().next()); + + String file1 = first.getAttachments().keySet().iterator().next(); + String file2 = second.getAttachments().keySet().iterator().next(); + + boolean logo = file1.equals(""logo.jpeg"") || file2.equals(""logo.jpeg""); + boolean license = file1.equals(""license.txt"") || file2.equals(""license.txt""); + + assertTrue(""Should have logo.jpeg file attachment"", logo); + assertTrue(""Should have license.txt file attachment"", license); } @Override" d92252312c9c42b598d3e79fb805912e9e061e43,hbase,"HBASE-3082 For ICV gets, first look in MemStore- before reading StoreFiles (Prakash via jgray)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1026910 13f79535-47bb-0310-9956-ffa450edef68-",p,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt index 5badd1367fc9..78003b21b147 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1037,6 +1037,8 @@ Release 0.21.0 - Unreleased HBASE-3132 Print TimestampRange and BloomFilters in HFile pretty print HBASE-2514 RegionServer should refuse to be assigned a region that use LZO when LZO isn't available + HBASE-3082 For ICV gets, first look in MemStore before reading StoreFiles + (prakash via stack) NEW FEATURES HBASE-1961 HBase EC2 scripts diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java index 4c5395e5281b..4954529c4e1d 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -2859,6 +2859,86 @@ public Result get(final Get get, final Integer lockid) throws IOException { return new Result(result); } + /** + * An optimized version of {@link #get(Get)} that checks MemStore first for + * the specified query. + *

      + * This is intended for use by increment operations where we have the + * guarantee that versions are never inserted out-of-order so if a value + * exists in MemStore it is the latest value. + *

      + * It only makes sense to use this method without a TimeRange and maxVersions + * equal to 1. + * @param get + * @return result + * @throws IOException + */ + private List getLastIncrement(final Get get) throws IOException { + InternalScan iscan = new InternalScan(get); + + List results = new ArrayList(); + + // memstore scan + iscan.checkOnlyMemStore(); + InternalScanner scanner = null; + try { + scanner = getScanner(iscan); + scanner.next(results); + } finally { + if (scanner != null) + scanner.close(); + } + + // count how many columns we're looking for + int expected = 0; + Map> familyMap = get.getFamilyMap(); + for (NavigableSet qfs : familyMap.values()) { + expected += qfs.size(); + } + + // found everything we were looking for, done + if (results.size() == expected) { + return results; + } + + // still have more columns to find + if (results != null && !results.isEmpty()) { + // subtract what was found in memstore + for (KeyValue kv : results) { + byte [] family = kv.getFamily(); + NavigableSet qfs = familyMap.get(family); + qfs.remove(kv.getQualifier()); + if (qfs.isEmpty()) familyMap.remove(family); + expected--; + } + // make a new get for just what is left + Get newGet = new Get(get.getRow()); + for (Map.Entry> f : familyMap.entrySet()) { + byte [] family = f.getKey(); + for (byte [] qualifier : f.getValue()) { + newGet.addColumn(family, qualifier); + } + } + iscan = new InternalScan(newGet); + } + + // check store files for what is left + List fileResults = new ArrayList(); + iscan.checkOnlyStoreFiles(); + scanner = null; + try { + scanner = getScanner(iscan); + scanner.next(fileResults); + } finally { + if (scanner != null) + scanner.close(); + } + + // combine and return + results.addAll(fileResults); + return results; + } + /* * Do a get based on the get parameter. */ @@ -2905,7 +2985,7 @@ public long incrementColumnValue(byte [] row, byte [] family, Get get = new Get(row); get.addColumn(family, qualifier); - List results = get(get); + List results = getLastIncrement(get); if (!results.isEmpty()) { KeyValue kv = results.get(0); @@ -2914,7 +2994,7 @@ public long incrementColumnValue(byte [] row, byte [] family, result += Bytes.toLong(buffer, valueOffset, Bytes.SIZEOF_LONG); } - // bulid the KeyValue now: + // build the KeyValue now: KeyValue newKv = new KeyValue(row, family, qualifier, EnvironmentEdgeManager.currentTimeMillis(), Bytes.toBytes(result)); @@ -2930,7 +3010,7 @@ public long incrementColumnValue(byte [] row, byte [] family, // Now request the ICV to the store, this will set the timestamp // appropriately depending on if there is a value in memcache or not. - // returns the + // returns the change in the size of the memstore from operation long size = store.updateColumnValue(row, family, qualifier, result); size = this.memstoreSize.addAndGet(size); diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/InternalScan.java b/src/main/java/org/apache/hadoop/hbase/regionserver/InternalScan.java new file mode 100644 index 000000000000..db2e02d80a81 --- /dev/null +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/InternalScan.java @@ -0,0 +1,78 @@ +/** + * Copyright 2010 The Apache Software Foundation + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.hbase.regionserver; + +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Scan; + +/** + * Special internal-only scanner, currently used for increment operations to + * allow additional server-side arguments for Scan operations. + *

      + * Rather than adding new options/parameters to the public Scan API, this new + * class has been created. + *

      + * Supports adding an option to only read from the MemStore with + * {@link #checkOnlyMemStore()} or to only read from StoreFiles with + * {@link #checkOnlyStoreFiles()}. + */ +class InternalScan extends Scan { + private boolean memOnly = false; + private boolean filesOnly = false; + + /** + * @param get get to model scan after + */ + public InternalScan(Get get) { + super(get); + } + + /** + * StoreFiles will not be scanned. Only MemStore will be scanned. + */ + public void checkOnlyMemStore() { + memOnly = true; + filesOnly = false; + } + + /** + * MemStore will not be scanned. Only StoreFiles will be scanned. + */ + public void checkOnlyStoreFiles() { + memOnly = false; + filesOnly = true; + } + + /** + * Returns true if only the MemStore should be checked. False if not. + * @return true to only check MemStore + */ + public boolean isCheckOnlyMemStore() { + return (memOnly); + } + + /** + * Returns true if only StoreFiles should be checked. False if not. + * @return true if only check StoreFiles + */ + public boolean isCheckOnlyStoreFiles() { + return (filesOnly); + } +} \ No newline at end of file diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java b/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java index 4775fc86454c..202d58a200b3 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java @@ -27,6 +27,7 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.NavigableSet; @@ -149,22 +150,33 @@ private List getScanners() throws IOException { */ private List getScanners(Scan scan, final NavigableSet columns) throws IOException { + boolean memOnly; + boolean filesOnly; + if (scan instanceof InternalScan) { + InternalScan iscan = (InternalScan)scan; + memOnly = iscan.isCheckOnlyMemStore(); + filesOnly = iscan.isCheckOnlyStoreFiles(); + } else { + memOnly = false; + filesOnly = false; + } + List scanners = new LinkedList(); // First the store file scanners - List sfScanners = StoreFileScanner + if (memOnly == false) { + List sfScanners = StoreFileScanner .getScannersForStoreFiles(store.getStorefiles(), cacheBlocks, isGet); - List scanners = - new ArrayList(sfScanners.size()+1); - // include only those scan files which pass all filters - for (StoreFileScanner sfs : sfScanners) { - if (sfs.shouldSeek(scan, columns)) { - scanners.add(sfs); + // include only those scan files which pass all filters + for (StoreFileScanner sfs : sfScanners) { + if (sfs.shouldSeek(scan, columns)) { + scanners.add(sfs); + } } } // Then the memstore scanners - if (this.store.memstore.shouldSeek(scan)) { - scanners.addAll(this.store.memstore.getScanners()); + if ((filesOnly == false) && (this.store.memstore.shouldSeek(scan))) { + scanners.addAll(this.store.memstore.getScanners()); } return scanners; }" ca5239afbb0f9540b0bf71edf3317f0b290af453,restlet-framework-java, - Initial code for new default HTTP connector and- SIP connector.--,a,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java index f57860ee13..0cadd7f228 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ClientConnection.java @@ -253,10 +253,6 @@ protected void writeMessage(Response response) { Series additionalHeaders = (Series) request .getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); addAdditionalHeaders(headers, additionalHeaders); - - // Set the server name again - headers.add(HeaderConstants.HEADER_USER_AGENT, request - .getClientInfo().getAgent()); } catch (Exception e) { getLogger() .log( diff --git a/modules/org.restlet/src/org/restlet/util/Series.java b/modules/org.restlet/src/org/restlet/util/Series.java index cac715fe48..8a387f282f 100644 --- a/modules/org.restlet/src/org/restlet/util/Series.java +++ b/modules/org.restlet/src/org/restlet/util/Series.java @@ -505,6 +505,21 @@ public boolean removeFirst(String name, boolean ignoreCase) { return changed; } + /** + * Replaces the value of the first parameter with the given name and removes + * all other parameters with the same name. The name matching is case + * sensitive. + * + * @param name + * The parameter name. + * @param value + * The value to set. + * @return The parameter set or added. + */ + public E set(String name, String value) { + return set(name, value, false); + } + /** * Replaces the value of the first parameter with the given name and removes * all other parameters with the same name." ebc869b3e3bd720b7f117f57b3a20045b936a5a8,drools,"JBRULES-498 Optimised HashMap implementations- -Changed ReteooWorkingMemory modifyObject to do a retract+assert. Its also- now doing the same as Leaps, so we can move the modifyObject method to- AbstractWorkingMemory.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@6642 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-",p,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java index 8ba6c0f4abc..57d5e0af8ea 100644 --- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java @@ -802,12 +802,79 @@ public void modifyObject(final FactHandle handle, } /** + * modify is implemented as half way retract / assert due to the truth + * maintenance issues. + * * @see WorkingMemory */ - public abstract void modifyObject(FactHandle factHandle, - Object object, - Rule rule, - Activation activation) throws FactException; + public void modifyObject( final FactHandle factHandle, + final Object object, + final Rule rule, + final Activation activation ) throws FactException { + try { + this.lock.lock(); + final int status = ((InternalFactHandle) factHandle).getEqualityKey().getStatus(); + final InternalFactHandle handle = (InternalFactHandle) factHandle; + final Object originalObject = handle.getObject(); + + if ( handle.getId() == -1 || object == null ) { + // the handle is invalid, most likely already retracted, so return + // and we cannot assert a null object + return; + } + + // set anyway, so that it updates the hashCodes + handle.setObject( object ); + + // We only need to put objects, if its a new object + if ( originalObject != object ) { + this.assertMap.put( handle, + handle ); + } + + // the hashCode and equality has changed, so we must update the EqualityKey + EqualityKey key = handle.getEqualityKey(); + key.removeFactHandle( handle ); + + // If the equality key is now empty, then remove it + if ( key.isEmpty() ) { + this.tms.remove( key ); + } + + // now use an existing EqualityKey, if it exists, else create a new one + key = this.tms.get( object ); + if ( key == null ) { + key = new EqualityKey( handle, + status ); + this.tms.put( key ); + } else { + key.addFactHandle( handle ); + } + + handle.setEqualityKey( key ); + + final PropagationContext propagationContext = new PropagationContextImpl( this.propagationIdCounter++, + PropagationContext.MODIFICATION, + rule, + activation ); + doRetract( handle, propagationContext ); + + this.handleFactory.increaseFactHandleRecency( handle ); + + doAssertObject( handle, object, propagationContext ); + + this.workingMemoryEventSupport.fireObjectModified( propagationContext, + factHandle, + originalObject, + object ); + + if ( !this.factQueue.isEmpty() ) { + propagateQueuedActions(); + } + } finally { + this.lock.unlock(); + } + } public void propagateQueuedActions() { for ( final Iterator it = this.factQueue.iterator(); it.hasNext(); ) { diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java b/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java index 0afb414f703..5d10a9d1b1e 100644 --- a/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java @@ -274,81 +274,6 @@ private final void invalidateActivation( final LeapsTuple tuple ) { } } - /** - * modify is implemented as half way retract / assert due to the truth - * maintenance issues. - * - * @see WorkingMemory - */ - public void modifyObject( final FactHandle factHandle, - final Object object, - final Rule rule, - final Activation activation ) throws FactException { - try { - this.lock.lock(); - final int status = ((InternalFactHandle) factHandle).getEqualityKey().getStatus(); - final InternalFactHandle handle = (InternalFactHandle) factHandle; - final Object originalObject = handle.getObject(); - - if ( handle.getId() == -1 || object == null ) { - // the handle is invalid, most likely already retracted, so return - // and we cannot assert a null object - return; - } - - // set anyway, so that it updates the hashCodes - handle.setObject( object ); - - // We only need to put objects, if its a new object - if ( originalObject != object ) { - this.assertMap.put( handle, - handle ); - } - - // the hashCode and equality has changed, so we must update the EqualityKey - EqualityKey key = handle.getEqualityKey(); - key.removeFactHandle( handle ); - - // If the equality key is now empty, then remove it - if ( key.isEmpty() ) { - this.tms.remove( key ); - } - - // now use an existing EqualityKey, if it exists, else create a new one - key = this.tms.get( object ); - if ( key == null ) { - key = new EqualityKey( handle, - status ); - this.tms.put( key ); - } else { - key.addFactHandle( handle ); - } - - handle.setEqualityKey( key ); - - final PropagationContext propagationContext = new PropagationContextImpl( this.propagationIdCounter++, - PropagationContext.MODIFICATION, - rule, - activation ); - doRetract( handle, propagationContext ); - - this.handleFactory.increaseFactHandleRecency( handle ); - - doAssertObject( handle, object, propagationContext ); - - this.workingMemoryEventSupport.fireObjectModified( propagationContext, - factHandle, - originalObject, - object ); - - if ( !this.factQueue.isEmpty() ) { - propagateQueuedActions(); - } - } finally { - this.lock.unlock(); - } - } - /** * ************* leaps section ********************* */ diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java b/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java index 24973e03405..c1d12feb691 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java @@ -80,79 +80,6 @@ public void doRetract(final InternalFactHandle handle, this ); } - /** - * @see WorkingMemory - */ - public void modifyObject(final FactHandle factHandle, - final Object object, - final Rule rule, - final Activation activation) throws FactException { - try { - this.lock.lock(); - final int status = ((InternalFactHandle) factHandle).getEqualityKey().getStatus(); - final InternalFactHandle handle = (InternalFactHandle) factHandle; - final Object originalObject = handle.getObject(); - - if ( handle.getId() == -1 || object == null ) { - // the handle is invalid, most likely already retracted, so return - // and we cannot assert a null object - return; - } - - // set anyway, so that it updates the hashCodes - handle.setObject( object ); - - // We only need to put objects, if its a new object - if ( originalObject != object ) { - this.assertMap.put( handle, - handle ); - } - - // the hashCode and equality has changed, so we must update the EqualityKey - EqualityKey key = handle.getEqualityKey(); - key.removeFactHandle( handle ); - - // If the equality key is now empty, then remove it - if ( key.isEmpty() ) { - this.tms.remove( key ); - } - - // now use an existing EqualityKey, if it exists, else create a new one - key = this.tms.get( object ); - if ( key == null ) { - key = new EqualityKey( handle, - status ); - this.tms.put( key ); - } else { - key.addFactHandle( handle ); - } - - handle.setEqualityKey( key ); - - this.handleFactory.increaseFactHandleRecency( handle ); - - final PropagationContext propagationContext = new PropagationContextImpl( this.propagationIdCounter++, - PropagationContext.MODIFICATION, - rule, - activation ); - - this.ruleBase.modifyObject( factHandle, - propagationContext, - this ); - - this.workingMemoryEventSupport.fireObjectModified( propagationContext, - factHandle, - originalObject, - object ); - - if ( !this.factQueue.isEmpty() ) { - propagateQueuedActions(); - } - } finally { - this.lock.unlock(); - } - } - public QueryResults getQueryResults(final String query) { final FactHandle handle = assertObject( new DroolsQuery( query ) ); final QueryTerminalNode node = (QueryTerminalNode) this.queryResults.remove( query );" 7206c04bb05a5ad7db4030aaf92b355b4c6538ff,drools,"JBPM-3814, BZ 1002724 Bugfixes with regards to- concurrency (cherry picked from commit- 2bf24d6908c1976fca356b2e96279355e863db5a)--- Changed EnvironmentImpl to use a concurrent HashMap-- The most significant persistence changes are in the JpaPersistenceContextManager class-- Reverted locking changes to the SingleSessionCommandService since a fix for JBPM-3814 is not- possible at the level of the SSCS in the form of locking (because of the app-scoped entity- manager).-- Also deleted unsused interfaces (ApplicationScopedPersistenceContext, TransactionablePersistentContext)-",c,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/core/impl/EnvironmentImpl.java b/drools-core/src/main/java/org/drools/core/impl/EnvironmentImpl.java index 00eb562b7d4..27244af94ce 100644 --- a/drools-core/src/main/java/org/drools/core/impl/EnvironmentImpl.java +++ b/drools-core/src/main/java/org/drools/core/impl/EnvironmentImpl.java @@ -16,14 +16,22 @@ package org.drools.core.impl; +import java.util.Collection; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import org.kie.api.runtime.Environment; +import org.kie.api.runtime.KieSession; public class EnvironmentImpl implements Environment { - private Map environment = new HashMap(); + // The default concurrencyLevel is 16: if users have enough threads + // that (16^(1.5))=64 *concurrent* updates are possible/likely + // then the concurrencyLevel will need to be upgraded, + // but that situation is fairly unlikely + private Map environment = new NullValueConcurrentHashMap(); private Environment delegate; @@ -43,4 +51,59 @@ public void set(String name, Object object) { environment.put(name, object); } + /** + * This class adds the possibility of storing null values in the {@link ConcurrentHashMap}, + * since storing null values in an {@link Environment} is something that happens in the kie code. + * + * This class is needed for the {@link Environment} implementation since happens-before is + * not guaranteed with a normal {@link HashMap}. Not having guaranteed happens-before can lead to + * race-conditions, especially when using a {@link KieSession} as a Singleton in a multi-threaded + * environment. + * + * @param The key type + * @param The value type + */ + private static class NullValueConcurrentHashMap extends ConcurrentHashMap { + + private static Object NULL = new Object(); + + public V put(K key, V value) { + if (value != null) { + value = super.put(key, value); + } else { + value = super.put(key, (V) NULL); + if (value == NULL) { + return null; + } + } + return value; + } + + public V get(Object key) { + Object value = super.get(key); + if (value == NULL) { + return null; + } + return (V) value; + } + + public boolean containsValue(Object value) { + if( value == null ) { + return super.containsValue(NULL); + } + return super.containsValue(value); + } + + public void putAll(Map m) { + throw new UnsupportedOperationException(""The putAll(Map m) method is not supported on this implementation.""); + } + + public Collection values() { + throw new UnsupportedOperationException(""The values() method is not supported on this implementation.""); + } + + public Set> entrySet() { + throw new UnsupportedOperationException(""The entrySet() method is not supported on this implementation.""); + } + } } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/ApplicationScopedPersistenceContext.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/ApplicationScopedPersistenceContext.java deleted file mode 100644 index f3a3ee46a5f..00000000000 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/ApplicationScopedPersistenceContext.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.drools.persistence; - -import org.kie.internal.runtime.StatefulKnowledgeSession; -import org.kie.api.runtime.Environment; -import org.kie.api.runtime.KieSessionConfiguration; - -public interface ApplicationScopedPersistenceContext { - - StatefulKnowledgeSession loadStatefulKnowledgeSession(long sessionId, - KieSessionConfiguration kconf, - Environment env); - - void save(StatefulKnowledgeSession internalKnowledgeSession); - - void update(StatefulKnowledgeSession internalKnowledgeSession); - - void setLastModificationDate(long sessionId); -} diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/PersistenceContextManager.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/PersistenceContextManager.java index b086a51e7cb..f55c66c032c 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/PersistenceContextManager.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/PersistenceContextManager.java @@ -1,15 +1,52 @@ package org.drools.persistence; +import javax.persistence.EntityManager; +import javax.transaction.Synchronization; + +import org.drools.core.command.CommandService; +import org.kie.api.command.Command; +import org.kie.api.runtime.KieSession; + public interface PersistenceContextManager { + + /** + * @return a {@link PersistenceContext} instance containing the Application Scoped {@link EntityManager}. + */ PersistenceContext getApplicationScopedPersistenceContext(); + /** + * @return a {@link PersistenceContext} instance containing the Command Scoped {@link EntityManager}. + */ PersistenceContext getCommandScopedPersistenceContext(); - + + /** + * This method should be called at the beginning of a {@link CommandService#execute(org.kie.api.command.Command)} method, + * when the given {@link CommandService} instance is responsible for handling persistence. + * See the {@link SingleSessionCommandService} class. + *

      + * The first responsibility of this method is to make sure that the Command Scoped {@link EntityManager} (CSEM) joins + * the ongoing transaction. + *

      + * When the CSEM is internally managed, this method is also responsible for creating a new CSEM for use during execution + * of the {@link Command} or operation being executed by the {@link KieSession}. + */ void beginCommandScopedEntityManager(); + /** + * This method should only called in the {@link Synchronization#afterCompletion(int)} method. + *

      + * It is responsible for cleaning up the Command Scoped {@link EntityManager} (CSEM) instance, but only when + * the CSEM is an internal one, and not one supplied (and managed) by the user. + *

      + * If the CSEM is (internally) managed, then this method will take the necessary actions in order to make sure that a + * new CSEM can be generated at the beginning of the next operation or command on the persistent {@link KieSession}. + *

      + * if the CSEM is supplied (and managed) by the user, this method will do nothing with the CSEM. + */ void endCommandScopedEntityManager(); - - void clearPersistenceContext(); + /** + * Executes the necessary actions in order to clean up and dispose of the internal fields of this instance. + */ void dispose(); } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/SingleSessionCommandService.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/SingleSessionCommandService.java index 0d5df467b74..7fd7f9258f8 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/SingleSessionCommandService.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/SingleSessionCommandService.java @@ -58,7 +58,7 @@ public class SingleSessionCommandService implements org.drools.core.command.SingleSessionCommandService { - Logger logger = LoggerFactory.getLogger( getClass() ); + private static Logger logger = LoggerFactory.getLogger( SingleSessionCommandService.class ); private SessionInfo sessionInfo; private SessionMarshallingHelper marshallingHelper; @@ -75,9 +75,6 @@ public class SingleSessionCommandService private static Map synchronizations = Collections.synchronizedMap( new IdentityHashMap() ); - private final ReentrantLock lock = new ReentrantLock(); - private boolean doSessionLocking = false; - public void checkEnvironment(Environment env) { if ( env.get( EnvironmentName.ENTITY_MANAGER_FACTORY ) == null && env.get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER ) == null ) { @@ -124,7 +121,6 @@ public SingleSessionCommandService(KieBase kbase, boolean transactionOwner = false; try { transactionOwner = txm.begin(); - registerRollbackSync(); persistenceContext.joinTransaction(); @@ -194,7 +190,6 @@ public SingleSessionCommandService(Integer sessionId, boolean transactionOwner = false; try { transactionOwner = txm.begin(); - registerRollbackSync(); persistenceContext.joinTransaction(); @@ -266,7 +261,7 @@ protected void initExistingKnowledgeSession(Integer sessionId, // if this.ksession is null, it'll create a new one, else it'll use the existing one this.ksession = (StatefulKnowledgeSession) - this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(), + this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(), this.ksession ); // update the session id to be the same as the session info id @@ -295,10 +290,10 @@ public void initTransactionManager(Environment env) { } else { if ( tm != null && isSpringTransactionManager(tm.getClass()) ) { try { + logger.debug( ""Instantiating KieSpringTransactionManager"" ); Class< ? > cls = Class.forName( ""org.kie.spring.persistence.KieSpringTransactionManager"" ); Constructor< ? > con = cls.getConstructors()[0]; this.txm = (TransactionManager) con.newInstance( tm ); - logger.debug( ""Instantiating KieSpringTransactionManager"" ); cls = Class.forName( ""org.kie.spring.persistence.KieSpringJpaManager"" ); con = cls.getConstructors()[0]; this.jpm = (PersistenceContextManager) con.newInstance( new Object[]{this.env} ); @@ -306,10 +301,10 @@ public void initTransactionManager(Environment env) { //fall back for drools5-legacy spring module logger.warn( ""Could not instantiate KieSpringTransactionManager. Trying with DroolsSpringTransactionManager."" ); try { + logger.debug( ""Instantiating DroolsSpringTransactionManager"" ); Class< ? > cls = Class.forName( ""org.drools.container.spring.beans.persistence.DroolsSpringTransactionManager"" ); Constructor< ? > con = cls.getConstructors()[0]; this.txm = (TransactionManager) con.newInstance( tm ); - logger.debug( ""Instantiating DroolsSpringTransactionManager"" ); // configure spring for JPA and local transactions cls = Class.forName( ""org.drools.container.spring.beans.persistence.DroolsSpringJpaManager"" ); @@ -317,11 +312,11 @@ public void initTransactionManager(Environment env) { this.jpm = (PersistenceContextManager) con.newInstance( new Object[]{this.env} ); } catch ( Exception ex ) { logger.warn( ""Could not instantiate DroolsSpringTransactionManager"" ); - throw new RuntimeException( ""Could not instatiate org.kie.container.spring.beans.persistence.DroolsSpringTransactionManager"", ex ); + throw new RuntimeException( ""Could not instantiate org.kie.container.spring.beans.persistence.DroolsSpringTransactionManager"", ex ); } } } else { - logger.debug( ""Instantiating JtaTransactionManager"" ); + logger.debug( ""Instantiating JtaTransactionManager"" ); this.txm = new JtaTransactionManager( env.get( EnvironmentName.TRANSACTION ), env.get( EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY ), tm ); @@ -340,15 +335,6 @@ public void initTransactionManager(Environment env) { this.jpm ); env.set( EnvironmentName.TRANSACTION_MANAGER, this.txm ); - - if( env.get(EnvironmentName.USE_SESSION_LOCKING) != null ) { - Object useSessionLockObj = env.get(EnvironmentName.USE_SESSION_LOCKING); - if( useSessionLockObj instanceof String ) { - this.doSessionLocking = Boolean.parseBoolean((String) useSessionLockObj); - } else if ( useSessionLockObj instanceof Boolean ) { - this.doSessionLocking = (Boolean) useSessionLockObj; - } - } } } @@ -415,6 +401,7 @@ public void destroy() { boolean transactionOwner = false; try { transactionOwner = txm.begin(); + persistenceContext.joinTransaction(); initExistingKnowledgeSession( this.sessionInfo.getId(), @@ -465,8 +452,6 @@ public void afterCompletion(int status) { // always cleanup thread local whatever the result SingleSessionCommandService.synchronizations.remove( this.service ); - this.service.jpm.clearPersistenceContext(); - this.service.jpm.endCommandScopedEntityManager(); KieSession ksession = this.service.ksession; @@ -477,20 +462,16 @@ public void afterCompletion(int status) { if (this.service.doRollback) { internalProcessRuntime.clearProcessInstancesState(); } - + internalProcessRuntime.clearProcessInstances(); } ((JPAWorkItemManager) ksession.getWorkItemManager()).clearWorkItems(); } - - // Unlock, if it was locked - while( this.service.lock.isLocked() ) { - this.service.lock.unlock(); - } + } public void beforeCompletion() { - + // not used } } @@ -521,30 +502,16 @@ public T execute(Command command) { jpm.dispose(); return result; } + // Open the entity manager before the transaction begins. PersistenceContext persistenceContext = jpm.getApplicationScopedPersistenceContext(); boolean transactionOwner = false; try { transactionOwner = txm.begin(); - if( ! transactionOwner && doSessionLocking ) { - /** - * There is a race condition when the tx is not owned by the SSCS. - * In that case, the commit happens *outside* of the synchronized - * SSCS.execute(..) block. - * However, the SynchronizationImpl.afterCompletion(..) method, - * called (just after) when the commit happens, will then also - * happen *outside* of the synchronized execute(...) block -- and - * this class does not expect that. When that happens, and another - * thread is calling .execute(..) on the same SSCS, bad things happen. - * - * This lock prevents the race condition described above from happening. - */ - lock.lock(); - } - - persistenceContext.joinTransaction(); - + + persistenceContext.joinTransaction(); + initExistingKnowledgeSession( sessionInfo.getId(), marshallingHelper.getKbase(), marshallingHelper.getConf(), @@ -561,6 +528,7 @@ public T execute(Command command) { result = ksession.execute(command); } else { + logger.trace(""Executing "" + command.getClass().getSimpleName()); result = executeNext((GenericCommand) command); } @@ -585,4 +553,5 @@ public T execute(Command command) { } } } + } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/TransactionablePersistentContext.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/TransactionablePersistentContext.java deleted file mode 100644 index b53a5440cdb..00000000000 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/TransactionablePersistentContext.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.drools.persistence; - -public interface TransactionablePersistentContext { - - boolean isOpen(); - - void joinTransaction(); - - void close(); -} diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContext.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContext.java index e77b857d55b..e4e8db9e875 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContext.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContext.java @@ -62,7 +62,7 @@ public boolean isOpen() { public void joinTransaction() { if (isJTA) { - this.em.joinTransaction(); + this.em.joinTransaction(); } } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContextManager.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContextManager.java index 3ac39ae1ce4..71e7e1419d8 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContextManager.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/JpaPersistenceContextManager.java @@ -21,21 +21,45 @@ import org.drools.persistence.PersistenceContext; import org.drools.persistence.PersistenceContextManager; +import org.drools.persistence.SingleSessionCommandService; import org.kie.api.runtime.Environment; import org.kie.api.runtime.EnvironmentName; +import org.kie.api.runtime.KieSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +/** + * This class manages {@link JpaPersistenceContext} objects, and the underlying persistence context ({@link EntityManager}) + * instances for a persistent {@link KieSession} and other infrastructure classes that use persistence in KIE projects. + *

      + * (For reference in the following documentation: the {@link EntityManager} is the class used to represent a persistence context) + *

      + * There are 2 issues to take into account when looking at or modifying the code here:
        + *
      1. One of the features made available here is the ability for the user to supply their own (Command Scoped) persistence + * context for use by the {@link KieSession}
      2. + *
      3. However, significant race-conditions arise when a Command Scoped persistence context is used in one persistent + * {@link KieSession} by multiple threads. In other words, when multiple threads call operations on a Singleton persistent + * {@link KieSession}.
      4. + *
      + * + * This class uses {@link ThreadLocal} instances for two things:
        + *
      1. The internal Command Scoped {@link EntityManager} instance.
      2. + *
      3. + *
      + */ public class JpaPersistenceContextManager implements PersistenceContextManager { - protected Environment env; + + protected final Environment env; - private EntityManagerFactory emf; + private final EntityManagerFactory emf; - private EntityManager appScopedEntityManager; - protected EntityManager cmdScopedEntityManager; + private volatile EntityManager appScopedEntityManager; + protected final ThreadLocal localInternalCmdScopedEntityManager = new ThreadLocal(); - private boolean internalAppScopedEntityManager; - private boolean internalCmdScopedEntityManager; + private volatile boolean internalAppScopedEntityManagerFlag; + private volatile boolean internalCmdScopedEntityManagerFlag; public JpaPersistenceContextManager(Environment env) { this.env = env; @@ -51,71 +75,103 @@ public PersistenceContext getApplicationScopedPersistenceContext() { } if ( this.appScopedEntityManager == null ) { - internalAppScopedEntityManager = true; + internalAppScopedEntityManagerFlag = true; this.appScopedEntityManager = this.emf.createEntityManager(); this.env.set( EnvironmentName.APP_SCOPED_ENTITY_MANAGER, this.appScopedEntityManager ); } else { - internalAppScopedEntityManager = false; + internalAppScopedEntityManagerFlag = false; } } return new JpaPersistenceContext( appScopedEntityManager ); } public PersistenceContext getCommandScopedPersistenceContext() { - return new JpaPersistenceContext( this.cmdScopedEntityManager ); + return new JpaPersistenceContext( getInternalCommandScopedEntityManager() ); } public void beginCommandScopedEntityManager() { - EntityManager cmdScopedEntityManager = (EntityManager) env.get( EnvironmentName.CMD_SCOPED_ENTITY_MANAGER ); - if ( cmdScopedEntityManager == null || - ( this.cmdScopedEntityManager != null && !this.cmdScopedEntityManager.isOpen() )) { - internalCmdScopedEntityManager = true; - this.cmdScopedEntityManager = this.emf.createEntityManager(); // no need to call joinTransaction as it will do so if one already exists - this.cmdScopedEntityManager.setFlushMode(FlushModeType.COMMIT); - this.env.set( EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, - this.cmdScopedEntityManager ); - cmdScopedEntityManager = this.cmdScopedEntityManager; - } else { - internalCmdScopedEntityManager = false; + EntityManager externalCmdScopedEntityManager = (EntityManager) this.env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER); + EntityManager internalCmdScopedEntityManager = getInternalCommandScopedEntityManager(); + + EntityManager cmdScopedEntityManager; + /** + * The following if() check is fairly important for KIE persistence. It should make sure + * to correctly implement the following logic: + * + * 1. If there's already an internal Command Scoped EntityManager (CSEM) for this thread, + * which is also open, then the existing CSEM should be used and *no* new CSEM should be created. + * 2. If 1 is not true, AND there's an open, externally managed CSEM (supplied by the user via the Environment), + * then the externally managed CSEM should be used (and *no* new CSEM should be created.) + * + * Notice that I'm specifying when a new CSEM should *not* be created, while the logic below does the + * opposite of this: it creates a new CSEM in accordance with the logic described above. + */ + boolean openInternalCSEM = internalCmdScopedEntityManager != null && internalCmdScopedEntityManager.isOpen(); + if ( openInternalCSEM || + (externalCmdScopedEntityManager != null && externalCmdScopedEntityManager.isOpen()) ) { + if( internalCmdScopedEntityManager != null ) { + cmdScopedEntityManager = internalCmdScopedEntityManager; + } else { + internalCmdScopedEntityManagerFlag = false; + cmdScopedEntityManager = externalCmdScopedEntityManager; + setInternalCommandScopedEntityManager(externalCmdScopedEntityManager); + } + } else { + internalCmdScopedEntityManagerFlag = true; + + // Create a new cmd scoped em + internalCmdScopedEntityManager = this.emf.createEntityManager(); + setInternalCommandScopedEntityManager(internalCmdScopedEntityManager); + internalCmdScopedEntityManager.setFlushMode(FlushModeType.COMMIT); + + cmdScopedEntityManager = internalCmdScopedEntityManager; } + cmdScopedEntityManager.joinTransaction(); appScopedEntityManager.joinTransaction(); } public void endCommandScopedEntityManager() { - if ( this.internalCmdScopedEntityManager ) { - this.env.set( EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, - null ); - } + EntityManager cmdScopedEntityManager = getInternalCommandScopedEntityManager(); + if ( this.internalCmdScopedEntityManagerFlag ) { + if (cmdScopedEntityManager != null && cmdScopedEntityManager.isOpen()) { + cmdScopedEntityManager.clear(); + } + } } public void dispose() { - if ( this.internalAppScopedEntityManager ) { + if ( this.internalAppScopedEntityManagerFlag ) { if ( this.appScopedEntityManager != null && this.appScopedEntityManager.isOpen() ) { this.appScopedEntityManager.close(); } - this.internalAppScopedEntityManager = false; + this.internalAppScopedEntityManagerFlag = false; this.env.set( EnvironmentName.APP_SCOPED_ENTITY_MANAGER, null ); this.appScopedEntityManager = null; } - if ( this.internalCmdScopedEntityManager ) { - if ( this.cmdScopedEntityManager != null && this.cmdScopedEntityManager.isOpen() ) { - this.cmdScopedEntityManager.close(); + if ( this.internalCmdScopedEntityManagerFlag ) { + EntityManager cmdScopedEntityManager = getInternalCommandScopedEntityManager(); + if ( cmdScopedEntityManager != null && cmdScopedEntityManager.isOpen() ) { + cmdScopedEntityManager.close(); } - this.internalCmdScopedEntityManager = false; - this.env.set( EnvironmentName.CMD_SCOPED_ENTITY_MANAGER, null ); - this.cmdScopedEntityManager = null; + this.internalCmdScopedEntityManagerFlag = false; + setInternalCommandScopedEntityManager(null); } } - public void clearPersistenceContext() { - if (this.cmdScopedEntityManager != null && this.cmdScopedEntityManager.isOpen()) { - this.cmdScopedEntityManager.clear(); - } - + /** + * Getter / Setter methods for the Command Scoped {@link EntityManager} + */ + + protected EntityManager getInternalCommandScopedEntityManager() { + return this.localInternalCmdScopedEntityManager.get(); + } + + protected void setInternalCommandScopedEntityManager(EntityManager entityManager) { + this.localInternalCmdScopedEntityManager.set(entityManager); } } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java index aafda777a42..77718aebc2c 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java @@ -71,7 +71,7 @@ public T execute(Command command) { return executeNext(command); } catch (RuntimeException ex) { - + logger.trace(ex.getClass().getSimpleName() + "" caught in "" + this.getClass().getSimpleName() + "": "" + ex.getMessage()); if (!isCausedByOptimisticLockingFailure(ex)) { throw ex; } diff --git a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/processinstance/JPAWorkItemManager.java b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/processinstance/JPAWorkItemManager.java index f203e31d29b..23d27df680d 100644 --- a/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/processinstance/JPAWorkItemManager.java +++ b/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/processinstance/JPAWorkItemManager.java @@ -82,9 +82,7 @@ public void retryWorkItem(long workItemId) { public void internalAbortWorkItem(long id) { Environment env = this.kruntime.getEnvironment(); - //EntityManager em = (EntityManager) env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER); PersistenceContext context = ((PersistenceContextManager) env.get( EnvironmentName.PERSISTENCE_CONTEXT_MANAGER )).getCommandScopedPersistenceContext(); - WorkItemInfo workItemInfo = context.findWorkItemInfo( id ); // work item may have been aborted diff --git a/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java b/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java index 0a9bec01ae4..79b0d2f324e 100644 --- a/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java +++ b/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java @@ -16,13 +16,13 @@ package org.drools.persistence.jta; import static junit.framework.Assert.assertTrue; -import static org.drools.persistence.util.PersistenceUtil.DROOLS_PERSISTENCE_UNIT_NAME; -import static org.drools.persistence.util.PersistenceUtil.createEnvironment; -import static org.drools.persistence.util.PersistenceUtil.getValueOfField; -import static org.drools.persistence.util.PersistenceUtil.setupWithPoolingDataSource; +import static org.drools.persistence.util.PersistenceUtil.*; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.kie.api.runtime.EnvironmentName.ENTITY_MANAGER_FACTORY; +import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.HashMap; import javax.naming.InitialContext; @@ -41,15 +41,15 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.kie.api.io.ResourceType; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.EnvironmentName; import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.io.ResourceFactory; -import org.kie.api.io.ResourceType; import org.kie.internal.persistence.jpa.JPAKnowledgeService; -import org.kie.api.runtime.Environment; -import org.kie.api.runtime.EnvironmentName; import org.kie.internal.runtime.StatefulKnowledgeSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -255,17 +255,18 @@ public void basicTransactionRollbackTest() { public static String COMMAND_ENTITY_MANAGER_FACTORY = ""drools.persistence.test.EntityManagerFactory""; @Test - public void testSingleSessionCommandServiceAndJtaTransactionManagerTogether() { - + public void testSingleSessionCommandServiceAndJtaTransactionManagerTogether() throws Exception { // Initialize drools environment stuff Environment env = createEnvironment(context); KnowledgeBase kbase = initializeKnowledgeBase(simpleRule); StatefulKnowledgeSession commandKSession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env ); + commandKSession.getId(); // initialize CSEM SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) commandKSession).getCommandService(); JpaPersistenceContextManager jpm = (JpaPersistenceContextManager) getValueOfField(""jpm"", commandService); - jpm.getApplicationScopedPersistenceContext(); - EntityManager em = (EntityManager) getValueOfField(""appScopedEntityManager"", jpm); + Method csemMethod = JpaPersistenceContextManager.class.getDeclaredMethod(""getInternalCommandScopedEntityManager""); + csemMethod.setAccessible(true); + EntityManager em = (EntityManager) csemMethod.invoke(jpm); TransactionTestObject mainObject = new TransactionTestObject(); mainObject.setName(""mainCommand""); @@ -278,10 +279,42 @@ public void testSingleSessionCommandServiceAndJtaTransactionManagerTogether() { emEnv.put(COMMAND_ENTITY_MANAGER, em); TransactionTestCommand txTestCmd = new TransactionTestCommand(mainObject, subObject, emEnv); - commandKSession.execute(txTestCmd); - } + /** + * Reflection method when doing ugly hacks in tests. + * + * @param fieldname + * The name of the field to be retrieved. + * @param source + * The object containing the field to be retrieved. + * @return The value (object instance) stored in the field requested from + * the given source object. + */ + public static Object getValueOfField(String fieldname, Object source) { + String sourceClassName = source.getClass().getSimpleName(); + + Field field = null; + try { + field = source.getClass().getDeclaredField(fieldname); + field.setAccessible(true); + } catch (SecurityException e) { + fail(""Unable to retrieve "" + fieldname + "" field from "" + sourceClassName + "": "" + e.getCause()); + } catch (NoSuchFieldException e) { + fail(""Unable to retrieve "" + fieldname + "" field from "" + sourceClassName + "": "" + e.getCause()); + } + + assertNotNull(""."" + fieldname + "" field is null!?!"", field); + Object fieldValue = null; + try { + fieldValue = field.get(source); + } catch (IllegalArgumentException e) { + fail(""Unable to retrieve value of "" + fieldname + "" from "" + sourceClassName + "": "" + e.getCause()); + } catch (IllegalAccessException e) { + fail(""Unable to retrieve value of "" + fieldname + "" from "" + sourceClassName + "": "" + e.getCause()); + } + return fieldValue; + } } diff --git a/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestCommand.java b/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestCommand.java index dfcbdbaf435..f9ee05dc5d9 100644 --- a/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestCommand.java +++ b/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestCommand.java @@ -70,6 +70,7 @@ public TransactionTestCommand(Object mainObject, HashMap env) { private void setPersistenceFields(HashMap env) { this.em = (EntityManager) env.get(COMMAND_ENTITY_MANAGER); + assert this.em != null : ""Command Entity Manager is null""; this.emf = (EntityManagerFactory) env.get(COMMAND_ENTITY_MANAGER_FACTORY); } diff --git a/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaOptLockPersistentStatefulSessionTest.java b/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaOptLockPersistentStatefulSessionTest.java index 10d3d8f2795..bd21b1e4b90 100644 --- a/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaOptLockPersistentStatefulSessionTest.java +++ b/drools-persistence-jpa/src/test/java/org/drools/persistence/session/JpaOptLockPersistentStatefulSessionTest.java @@ -23,6 +23,7 @@ import org.drools.persistence.SingleSessionCommandService; import org.drools.persistence.jpa.OptimisticLockRetryInterceptor; import org.drools.persistence.util.PersistenceUtil; +import org.hibernate.StaleObjectStateException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -125,6 +126,7 @@ public void run() { ksession2.insert( 3 ); ksession2.getWorkItemManager().completeWorkItem(0, null); ksession2.fireAllRules(); + logger.info(""The above "" + StaleObjectStateException.class.getSimpleName() + ""'s were expected in this test.""); ksession2.dispose(); } diff --git a/drools-persistence-jpa/src/test/java/org/drools/persistence/session/RuleFlowGroupRollbackTest.java b/drools-persistence-jpa/src/test/java/org/drools/persistence/session/RuleFlowGroupRollbackTest.java index 6d2a23ee4e5..a4c798f80fe 100644 --- a/drools-persistence-jpa/src/test/java/org/drools/persistence/session/RuleFlowGroupRollbackTest.java +++ b/drools-persistence-jpa/src/test/java/org/drools/persistence/session/RuleFlowGroupRollbackTest.java @@ -48,9 +48,13 @@ import org.kie.api.runtime.Environment; import org.kie.api.runtime.EnvironmentName; import org.kie.api.runtime.KieSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @RunWith(Parameterized.class) public class RuleFlowGroupRollbackTest { + + private static Logger logger = LoggerFactory.getLogger(RuleFlowGroupRollbackTest.class); private HashMap context; private boolean locking; @@ -91,7 +95,7 @@ public void testRuleFlowGroupRollback() throws Exception { ksession.execute(new ExceptionCommand()); fail(""Process must throw an exception""); } catch (Exception e) { - e.printStackTrace(); + logger.info(""The above "" + RuntimeException.class.getSimpleName() + "" was expected in this test.""); } ksession.insert(list); @@ -140,7 +144,7 @@ public Void execute(Context context) { public class ExceptionCommand implements GenericCommand { public Void execute(Context context) { - throw new RuntimeException(); + throw new RuntimeException(""(Expected) exception thrown by test""); } } diff --git a/drools-persistence-jpa/src/test/java/org/drools/persistence/util/PersistenceUtil.java b/drools-persistence-jpa/src/test/java/org/drools/persistence/util/PersistenceUtil.java index 2563700a28a..c3f052ae3f7 100644 --- a/drools-persistence-jpa/src/test/java/org/drools/persistence/util/PersistenceUtil.java +++ b/drools-persistence-jpa/src/test/java/org/drools/persistence/util/PersistenceUtil.java @@ -367,41 +367,6 @@ public static boolean useTransactions() { return useTransactions; } - /** - * Reflection method when doing ugly hacks in tests. - * - * @param fieldname - * The name of the field to be retrieved. - * @param source - * The object containing the field to be retrieved. - * @return The value (object instance) stored in the field requested from - * the given source object. - */ - public static Object getValueOfField(String fieldname, Object source) { - String sourceClassName = source.getClass().getSimpleName(); - - Field field = null; - try { - field = source.getClass().getDeclaredField(fieldname); - field.setAccessible(true); - } catch (SecurityException e) { - fail(""Unable to retrieve "" + fieldname + "" field from "" + sourceClassName + "": "" + e.getCause()); - } catch (NoSuchFieldException e) { - fail(""Unable to retrieve "" + fieldname + "" field from "" + sourceClassName + "": "" + e.getCause()); - } - - assertNotNull(""."" + fieldname + "" field is null!?!"", field); - Object fieldValue = null; - try { - fieldValue = field.get(source); - } catch (IllegalArgumentException e) { - fail(""Unable to retrieve value of "" + fieldname + "" from "" + sourceClassName + "": "" + e.getCause()); - } catch (IllegalAccessException e) { - fail(""Unable to retrieve value of "" + fieldname + "" from "" + sourceClassName + "": "" + e.getCause()); - } - return fieldValue; - } - public static Environment createEnvironment(HashMap context) { Environment env = EnvironmentFactory.newEnvironment();" 3ac3a72e910ce4734459e9359f979fbed8cb64a1,spring-framework,added test with custom repository annotation--,p,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java b/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java index 2c6fb3d81dcd..8099156006c1 100644 --- a/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java +++ b/org.springframework.transaction/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -16,6 +16,10 @@ package org.springframework.dao.annotation; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import javax.persistence.PersistenceException; import junit.framework.TestCase; @@ -109,6 +113,10 @@ public void testTranslationNeededForTheseExceptionsOnSuperclass() { doTestTranslationNeededForTheseExceptions(new MyStereotypedRepositoryInterfaceImpl()); } + public void testTranslationNeededForTheseExceptionsWithCustomStereotype() { + doTestTranslationNeededForTheseExceptions(new CustomStereotypedRepositoryInterfaceImpl()); + } + public void testTranslationNeededForTheseExceptionsOnInterface() { doTestTranslationNeededForTheseExceptions(new MyInterfaceStereotypedRepositoryInterfaceImpl()); } @@ -142,6 +150,7 @@ private void doTestTranslationNeededForTheseExceptions(RepositoryInterfaceImpl t } } + public interface RepositoryInterface { void noThrowsClause(); @@ -149,6 +158,7 @@ public interface RepositoryInterface { void throwsPersistenceException() throws PersistenceException; } + public static class RepositoryInterfaceImpl implements RepositoryInterface { private RuntimeException runtimeException; @@ -170,29 +180,49 @@ public void throwsPersistenceException() throws PersistenceException { } } + @Repository public static class StereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl { // Extends above class just to add repository annotation } + public static class MyStereotypedRepositoryInterfaceImpl extends StereotypedRepositoryInterfaceImpl { } + + @MyRepository + public static class CustomStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl { + + } + + + @Target({ElementType.TYPE}) + @Retention(RetentionPolicy.RUNTIME) + @Repository + public @interface MyRepository { + + } + + @Repository public interface StereotypedInterface { } + public static class MyInterfaceStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl implements StereotypedInterface { } + public interface StereotypedInheritingInterface extends StereotypedInterface { } + public static class MyInterfaceInheritedStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl implements StereotypedInheritingInterface {" 953a99c75cde29a18db58abde3fdee720fcddc4f,elasticsearch,"fix a bug in new checksum mechanism that caused- for replicas not to retain the _checksums file. Also, now that checksums are- widely used, consider files without checksums as ones that need to be- recovered--",c,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java b/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java index ffb8e217f1e02..71f405e1ced1a 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/common/lucene/Directories.java @@ -41,29 +41,6 @@ */ public class Directories { - /** - * Deletes all the files from a directory. - * - * @param directory The directory to delete all the files from - * @throws IOException if an exception occurs during the delete process - */ - public static void deleteFiles(Directory directory) throws IOException { - String[] files = directory.listAll(); - IOException lastException = null; - for (String file : files) { - try { - directory.deleteFile(file); - } catch (FileNotFoundException e) { - // ignore - } catch (IOException e) { - lastException = e; - } - } - if (lastException != null) { - throw lastException; - } - } - /** * Returns the estimated size of a {@link Directory}. */ diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java index f25b655e9f7cc..1791a50410ce8 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/gateway/CommitPoint.java @@ -62,10 +62,10 @@ public long length() { } public boolean isSame(StoreFileMetaData md) { - if (checksum != null && md.checksum() != null) { - return checksum.equals(md.checksum()); + if (checksum == null || md.checksum() == null) { + return false; } - return length == md.length(); + return length == md.length() && checksum.equals(md.checksum()); } } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java index 869d527fec9d7..986222f56a39d 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/shard/recovery/RecoverySource.java @@ -93,7 +93,8 @@ public static class Actions { this.translogSize = componentSettings.getAsBytesSize(""translog_size"", new ByteSizeValue(100, ByteSizeUnit.KB)); this.compress = componentSettings.getAsBoolean(""compress"", true); - logger.debug(""using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]"", concurrentStreams, fileChunkSize, translogOps, translogSize, compress); + logger.debug(""using concurrent_streams [{}], file_chunk_size [{}], translog_size [{}], translog_ops [{}], and compress [{}]"", + concurrentStreams, fileChunkSize, translogSize, translogOps, compress); transportService.registerHandler(Actions.START_RECOVERY, new StartRecoveryTransportRequestHandler()); } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java index cafd3aa200c6a..c1b7815b5e9ae 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/StoreFileMetaData.java @@ -66,10 +66,10 @@ public long length() { } public boolean isSame(StoreFileMetaData other) { - if (checksum != null && other.checksum != null) { - return checksum.equals(other.checksum); + if (checksum == null || other.checksum == null) { + return false; } - return length == other.length; + return length == other.length && checksum.equals(other.checksum); } public static StoreFileMetaData readStoreFileMetaData(StreamInput in) throws IOException { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java index 981c057aaff28..a516379bcc36b 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java @@ -46,6 +46,8 @@ */ public abstract class AbstractStore extends AbstractIndexShardComponent implements Store { + static final String CHECKSUMS_PREFIX = ""_checksums-""; + protected final IndexStore indexStore; private volatile ImmutableMap filesMetadata = ImmutableMap.of(); @@ -90,7 +92,24 @@ public StoreFileMetaData metaData(String name) throws IOException { } @Override public void deleteContent() throws IOException { - Directories.deleteFiles(directory()); + String[] files = directory().listAll(); + IOException lastException = null; + for (String file : files) { + if (file.startsWith(CHECKSUMS_PREFIX)) { + ((StoreDirectory) directory()).deleteFileChecksum(file); + } else { + try { + directory().deleteFile(file); + } catch (FileNotFoundException e) { + // ignore + } catch (IOException e) { + lastException = e; + } + } + } + if (lastException != null) { + throw lastException; + } } @Override public void fullDelete() throws IOException { @@ -104,10 +123,10 @@ public StoreFileMetaData metaData(String name) throws IOException { public static Map readChecksums(Directory dir) throws IOException { long lastFound = -1; for (String name : dir.listAll()) { - if (!name.startsWith(""_checksums-"")) { + if (!name.startsWith(CHECKSUMS_PREFIX)) { continue; } - long current = Long.parseLong(name.substring(""_checksums-"".length())); + long current = Long.parseLong(name.substring(CHECKSUMS_PREFIX.length())); if (current > lastFound) { lastFound = current; } @@ -115,7 +134,7 @@ public static Map readChecksums(Directory dir) throws IOExceptio if (lastFound == -1) { return ImmutableMap.of(); } - IndexInput indexInput = dir.openInput(""_checksums-"" + lastFound); + IndexInput indexInput = dir.openInput(CHECKSUMS_PREFIX + lastFound); try { indexInput.readInt(); // version return indexInput.readStringStringMap(); @@ -129,7 +148,7 @@ public void writeChecksums() throws IOException { } private void writeChecksums(StoreDirectory dir) throws IOException { - String checksumName = ""_checksums-"" + System.currentTimeMillis(); + String checksumName = CHECKSUMS_PREFIX + System.currentTimeMillis(); ImmutableMap files = list(); synchronized (mutex) { Map checksums = new HashMap(); @@ -144,9 +163,9 @@ private void writeChecksums(StoreDirectory dir) throws IOException { output.close(); } for (StoreFileMetaData metaData : files.values()) { - if (metaData.name().startsWith(""_checksums"") && !checksumName.equals(metaData.name())) { + if (metaData.name().startsWith(CHECKSUMS_PREFIX) && !checksumName.equals(metaData.name())) { try { - directory().deleteFile(metaData.name()); + dir.deleteFileChecksum(metaData.name()); } catch (Exception e) { // ignore } @@ -255,7 +274,19 @@ public Directory delegate() { } } + public void deleteFileChecksum(String name) throws IOException { + delegate.deleteFile(name); + synchronized (mutex) { + filesMetadata = MapBuilder.newMapBuilder(filesMetadata).remove(name).immutableMap(); + files = filesMetadata.keySet().toArray(new String[filesMetadata.size()]); + } + } + @Override public void deleteFile(String name) throws IOException { + // we don't allow to delete the checksums files, only using the deleteChecksum method + if (name.startsWith(CHECKSUMS_PREFIX)) { + return; + } delegate.deleteFile(name); synchronized (mutex) { filesMetadata = MapBuilder.newMapBuilder(filesMetadata).remove(name).immutableMap();" 57ec7d083a68abb23f009f9fdffb80197c138afd,hbase,HBASE-6400 Add getMasterAdmin() and- getMasterMonitor() to HConnection (Enis)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1363009 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java index 6161a643388a..b623bc260d39 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnection.java @@ -33,11 +33,11 @@ import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.HServerAddress; import org.apache.hadoop.hbase.HTableDescriptor; +import org.apache.hadoop.hbase.MasterAdminProtocol; +import org.apache.hadoop.hbase.MasterMonitorProtocol; import org.apache.hadoop.hbase.MasterNotRunningException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; import org.apache.hadoop.hbase.catalog.CatalogTracker; -import org.apache.hadoop.hbase.client.AdminProtocol; -import org.apache.hadoop.hbase.client.ClientProtocol; import org.apache.hadoop.hbase.client.coprocessor.Batch; import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; @@ -184,6 +184,17 @@ public HRegionLocation locateRegion(final byte [] regionName) public List locateRegions(byte[] tableName) throws IOException; + /** + * Returns a {@link MasterAdminProtocol} to the active master + */ + public MasterAdminProtocol getMasterAdmin() throws IOException; + + /** + * Returns an {@link MasterMonitorProtocol} to the active master + */ + public MasterMonitorProtocol getMasterMonitor() throws IOException; + + /** * Establishes a connection to the region server at the specified address. * @param hostname RegionServer hostname diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java index b4af521abc53..632586fb36ae 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/HConnectionManager.java @@ -27,8 +27,18 @@ import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.net.InetSocketAddress; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; @@ -52,7 +62,10 @@ import org.apache.hadoop.hbase.HServerAddress; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; +import org.apache.hadoop.hbase.MasterAdminProtocol; +import org.apache.hadoop.hbase.MasterMonitorProtocol; import org.apache.hadoop.hbase.MasterNotRunningException; +import org.apache.hadoop.hbase.MasterProtocol; import org.apache.hadoop.hbase.RegionMovedException; import org.apache.hadoop.hbase.RemoteExceptionHandler; import org.apache.hadoop.hbase.ServerName; @@ -65,11 +78,6 @@ import org.apache.hadoop.hbase.ipc.CoprocessorProtocol; import org.apache.hadoop.hbase.ipc.ExecRPCInvoker; import org.apache.hadoop.hbase.ipc.HBaseRPC; -import org.apache.hadoop.hbase.MasterProtocol; -import org.apache.hadoop.hbase.MasterMonitorProtocol; -import org.apache.hadoop.hbase.MasterAdminProtocol; -import org.apache.hadoop.hbase.client.MasterAdminKeepAliveConnection; -import org.apache.hadoop.hbase.client.MasterMonitorKeepAliveConnection; import org.apache.hadoop.hbase.ipc.VersionedProtocol; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.RequestConverter; @@ -77,10 +85,15 @@ import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsRequest; import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse; import org.apache.hadoop.hbase.security.User; -import org.apache.hadoop.hbase.util.*; -import org.apache.hadoop.hbase.zookeeper.ZKClusterId; +import org.apache.hadoop.hbase.util.Addressing; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.hadoop.hbase.util.Pair; +import org.apache.hadoop.hbase.util.SoftValueSortedMap; +import org.apache.hadoop.hbase.util.Triple; +import org.apache.hadoop.hbase.util.Writables; import org.apache.hadoop.hbase.zookeeper.MasterAddressTracker; import org.apache.hadoop.hbase.zookeeper.RootRegionTracker; +import org.apache.hadoop.hbase.zookeeper.ZKClusterId; import org.apache.hadoop.hbase.zookeeper.ZKTable; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; @@ -1615,6 +1628,16 @@ private Object getKeepAliveMasterProtocol( } } + @Override + public MasterAdminProtocol getMasterAdmin() throws MasterNotRunningException { + return getKeepAliveMasterAdmin(); + }; + + @Override + public MasterMonitorProtocol getMasterMonitor() throws MasterNotRunningException { + return getKeepAliveMasterMonitor(); + } + /** * This function allows HBaseAdmin and potentially others * to get a shared MasterAdminProtocol connection." 59d80ec19e7e6333a2af64b98f68d3efecc58a97,spring-framework,Fix minor issue in MockHttpServletRequest--Previously MockHttpServletRequest-sendRedirect did not set the HTTP status-or the Location header. This does not conform to the HttpServletRequest-interface.--MockHttpServletRequest will now:-- - Set the HTTP status to 302 on sendRedirect- - Set the Location header on sendRedirect- - Ensure the Location header and getRedirectedUrl are kept in synch--Issue: SPR-9594-,c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index b0b2db170658..3e2701c576b7 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -54,6 +54,8 @@ public class MockHttpServletResponse implements HttpServletResponse { private static final String CONTENT_LENGTH_HEADER = ""Content-Length""; + private static final String LOCATION_HEADER = ""Location""; + //--------------------------------------------------------------------- // ServletResponse properties //--------------------------------------------------------------------- @@ -95,8 +97,6 @@ public class MockHttpServletResponse implements HttpServletResponse { private String errorMessage; - private String redirectedUrl; - private String forwardedUrl; private final List includedUrls = new ArrayList(); @@ -306,7 +306,7 @@ public Set getHeaderNames() { /** * Return the primary value for the given header as a String, if any. * Will return the first value in case of multiple values. - *

      As of Servlet 3.0, this method is also defined HttpServletResponse. + *

      As of Servlet 3.0, this method is also defined in HttpServletResponse. * As of Spring 3.1, it returns a stringified value for Servlet 3.0 compatibility. * Consider using {@link #getHeaderValue(String)} for raw Object access. * @param name the name of the header @@ -319,7 +319,7 @@ public String getHeader(String name) { /** * Return all values for the given header as a List of Strings. - *

      As of Servlet 3.0, this method is also defined HttpServletResponse. + *

      As of Servlet 3.0, this method is also defined in HttpServletResponse. * As of Spring 3.1, it returns a List of stringified values for Servlet 3.0 compatibility. * Consider using {@link #getHeaderValues(String)} for raw Object access. * @param name the name of the header @@ -374,7 +374,7 @@ public String encodeURL(String url) { * returning the given URL String as-is. *

      Can be overridden in subclasses, appending a session id or the like * in a redirect-specific fashion. For general URL encoding rules, - * override the common {@link #encodeURL} method instead, appyling + * override the common {@link #encodeURL} method instead, applying * to redirect URLs as well as to general URLs. */ public String encodeRedirectURL(String url) { @@ -411,12 +411,13 @@ public void sendRedirect(String url) throws IOException { throw new IllegalStateException(""Cannot send redirect - response is already committed""); } Assert.notNull(url, ""Redirect URL must not be null""); - this.redirectedUrl = url; + setHeader(LOCATION_HEADER, url); + setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); setCommitted(true); } public String getRedirectedUrl() { - return this.redirectedUrl; + return getHeader(LOCATION_HEADER); } public void setDateHeader(String name, long value) { diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index 0a037c8f2c34..c16f7cab9e31 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -16,43 +16,54 @@ package org.springframework.mock.web; +import static org.junit.Assert.*; + import java.io.IOException; import java.util.Arrays; import java.util.Set; -import junit.framework.TestCase; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; import org.springframework.web.util.WebUtils; /** + * Unit tests for {@link MockHttpServletResponse}. + * * @author Juergen Hoeller * @author Rick Evans * @author Rossen Stoyanchev + * @author Rob Winch + * @author Sam Brannen * @since 19.02.2006 */ -public class MockHttpServletResponseTests extends TestCase { +public class MockHttpServletResponseTests { + + private MockHttpServletResponse response = new MockHttpServletResponse(); - public void testSetContentType() { + + @Test + public void setContentType() { String contentType = ""test/plain""; - MockHttpServletResponse response = new MockHttpServletResponse(); response.setContentType(contentType); assertEquals(contentType, response.getContentType()); assertEquals(contentType, response.getHeader(""Content-Type"")); assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding()); } - public void testSetContentTypeUTF8() { + @Test + public void setContentTypeUTF8() { String contentType = ""test/plain;charset=UTF-8""; - MockHttpServletResponse response = new MockHttpServletResponse(); response.setContentType(contentType); assertEquals(""UTF-8"", response.getCharacterEncoding()); assertEquals(contentType, response.getContentType()); assertEquals(contentType, response.getHeader(""Content-Type"")); } - - public void testContentTypeHeader() { + + @Test + public void contentTypeHeader() { String contentType = ""test/plain""; - MockHttpServletResponse response = new MockHttpServletResponse(); response.addHeader(""Content-Type"", contentType); assertEquals(contentType, response.getContentType()); assertEquals(contentType, response.getHeader(""Content-Type"")); @@ -65,9 +76,9 @@ public void testContentTypeHeader() { assertEquals(WebUtils.DEFAULT_CHARACTER_ENCODING, response.getCharacterEncoding()); } - public void testContentTypeHeaderUTF8() { + @Test + public void contentTypeHeaderUTF8() { String contentType = ""test/plain;charset=UTF-8""; - MockHttpServletResponse response = new MockHttpServletResponse(); response.setHeader(""Content-Type"", contentType); assertEquals(contentType, response.getContentType()); assertEquals(contentType, response.getHeader(""Content-Type"")); @@ -80,8 +91,8 @@ public void testContentTypeHeaderUTF8() { assertEquals(""UTF-8"", response.getCharacterEncoding()); } - public void testSetContentTypeThenCharacterEncoding() { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void setContentTypeThenCharacterEncoding() { response.setContentType(""test/plain""); response.setCharacterEncoding(""UTF-8""); assertEquals(""test/plain"", response.getContentType()); @@ -89,8 +100,8 @@ public void testSetContentTypeThenCharacterEncoding() { assertEquals(""UTF-8"", response.getCharacterEncoding()); } - public void testSetCharacterEncodingThenContentType() { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void setCharacterEncodingThenContentType() { response.setCharacterEncoding(""UTF-8""); response.setContentType(""test/plain""); assertEquals(""test/plain"", response.getContentType()); @@ -98,24 +109,23 @@ public void testSetCharacterEncodingThenContentType() { assertEquals(""UTF-8"", response.getCharacterEncoding()); } - public void testContentLength() { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void contentLength() { response.setContentLength(66); assertEquals(66, response.getContentLength()); assertEquals(""66"", response.getHeader(""Content-Length"")); } - - public void testContentLengthHeader() { - MockHttpServletResponse response = new MockHttpServletResponse(); + + @Test + public void contentLengthHeader() { response.addHeader(""Content-Length"", ""66""); - assertEquals(66,response.getContentLength()); + assertEquals(66, response.getContentLength()); assertEquals(""66"", response.getHeader(""Content-Length"")); } - - public void testHttpHeaderNameCasingIsPreserved() throws Exception { - final String headerName = ""Header1""; - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void httpHeaderNameCasingIsPreserved() throws Exception { + final String headerName = ""Header1""; response.addHeader(headerName, ""value1""); Set responseHeaders = response.getHeaderNames(); assertNotNull(responseHeaders); @@ -123,8 +133,8 @@ public void testHttpHeaderNameCasingIsPreserved() throws Exception { assertEquals(""HTTP header casing not being preserved"", headerName, responseHeaders.iterator().next()); } - public void testServletOutputStreamCommittedWhenBufferSizeExceeded() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletOutputStreamCommittedWhenBufferSizeExceeded() throws IOException { assertFalse(response.isCommitted()); response.getOutputStream().write('X'); assertFalse(response.isCommitted()); @@ -134,8 +144,8 @@ public void testServletOutputStreamCommittedWhenBufferSizeExceeded() throws IOEx assertEquals(size + 1, response.getContentAsByteArray().length); } - public void testServletOutputStreamCommittedOnFlushBuffer() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletOutputStreamCommittedOnFlushBuffer() throws IOException { assertFalse(response.isCommitted()); response.getOutputStream().write('X'); assertFalse(response.isCommitted()); @@ -144,8 +154,8 @@ public void testServletOutputStreamCommittedOnFlushBuffer() throws IOException { assertEquals(1, response.getContentAsByteArray().length); } - public void testServletWriterCommittedWhenBufferSizeExceeded() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletWriterCommittedWhenBufferSizeExceeded() throws IOException { assertFalse(response.isCommitted()); response.getWriter().write(""X""); assertFalse(response.isCommitted()); @@ -157,8 +167,8 @@ public void testServletWriterCommittedWhenBufferSizeExceeded() throws IOExceptio assertEquals(size + 1, response.getContentAsByteArray().length); } - public void testServletOutputStreamCommittedOnOutputStreamFlush() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletOutputStreamCommittedOnOutputStreamFlush() throws IOException { assertFalse(response.isCommitted()); response.getOutputStream().write('X'); assertFalse(response.isCommitted()); @@ -167,8 +177,8 @@ public void testServletOutputStreamCommittedOnOutputStreamFlush() throws IOExcep assertEquals(1, response.getContentAsByteArray().length); } - public void testServletWriterCommittedOnWriterFlush() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletWriterCommittedOnWriterFlush() throws IOException { assertFalse(response.isCommitted()); response.getWriter().write(""X""); assertFalse(response.isCommitted()); @@ -177,22 +187,39 @@ public void testServletWriterCommittedOnWriterFlush() throws IOException { assertEquals(1, response.getContentAsByteArray().length); } - public void testServletWriterAutoFlushedForString() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletWriterAutoFlushedForString() throws IOException { response.getWriter().write(""X""); assertEquals(""X"", response.getContentAsString()); } - public void testServletWriterAutoFlushedForChar() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletWriterAutoFlushedForChar() throws IOException { response.getWriter().write('X'); assertEquals(""X"", response.getContentAsString()); } - public void testServletWriterAutoFlushedForCharArray() throws IOException { - MockHttpServletResponse response = new MockHttpServletResponse(); + @Test + public void servletWriterAutoFlushedForCharArray() throws IOException { response.getWriter().write(""XY"".toCharArray()); assertEquals(""XY"", response.getContentAsString()); } + @Test + public void sendRedirect() throws IOException { + String redirectUrl = ""/redirect""; + response.sendRedirect(redirectUrl); + assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus()); + assertEquals(redirectUrl, response.getHeader(""Location"")); + assertEquals(redirectUrl, response.getRedirectedUrl()); + assertTrue(response.isCommitted()); + } + + @Test + public void locationHeaderUpdatesGetRedirectedUrl() { + String redirectUrl = ""/redirect""; + response.setHeader(""Location"", redirectUrl); + assertEquals(redirectUrl, response.getRedirectedUrl()); + } + }" f26b7b2321ba561c947da92510e95e22f059351c,ReactiveX-RxJava,Conditionals: Fix all but 2 tests--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java index f6c4f09ad0..44bb0c02c8 100644 --- a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java +++ b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java @@ -15,6 +15,7 @@ */ package rx.operators; +import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @@ -33,8 +34,10 @@ import rx.Observer; import rx.Statement; import rx.Subscription; +import rx.observers.TestObserver; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; +import rx.util.functions.Action1; import rx.util.functions.Func0; public class OperationConditionalsTest { @@ -108,7 +111,7 @@ public T call() { void observe(Observable source, T... values) { Observer o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver(o)); InOrder inOrder = inOrder(o); @@ -127,7 +130,7 @@ void observe(Observable source, T... values) { void observeSequence(Observable source, Iterable values) { Observer o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver(o)); InOrder inOrder = inOrder(o); @@ -146,7 +149,7 @@ void observeSequence(Observable source, Iterable v void observeError(Observable source, Class error, T... valuesBeforeError) { Observer o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver(o)); InOrder inOrder = inOrder(o); @@ -165,7 +168,7 @@ void observeError(Observable source, Class void observeSequenceError(Observable source, Class error, Iterable valuesBeforeError) { Observer o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver(o)); InOrder inOrder = inOrder(o); @@ -400,6 +403,7 @@ public Boolean call() { @Test public void testDoWhileManyTimes() { + fail(""deadlocking""); Observable source1 = Observable.from(1, 2, 3).subscribeOn(Schedulers.currentThread()); List expected = new ArrayList(numRecursion * 3);" 95ba62f83dfa05990d2165484330cdd0792064d8,elasticsearch,"Translog: Implement a file system based translog- and make it the default, closes -260.--",a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java index 61977707465c0..02c378097c250 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java @@ -22,7 +22,7 @@ import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.Scopes; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.index.translog.memory.MemoryTranslog; +import org.elasticsearch.index.translog.fs.FsTranslog; /** * @author kimchy (shay.banon) @@ -41,7 +41,7 @@ public TranslogModule(Settings settings) { @Override protected void configure() { bind(Translog.class) - .to(settings.getAsClass(TranslogSettings.TYPE, MemoryTranslog.class)) + .to(settings.getAsClass(TranslogSettings.TYPE, FsTranslog.class)) .in(Scopes.SINGLETON); } }" c03ff2ec9b64d6073b9130e11af00d0c655f25b6,drools,Implementing support to incremental updates on- kcontainers--,a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java index ad8e834922c..7a75099054d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java @@ -1,6 +1,8 @@ package org.drools.compiler.kie.builder.impl; import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase; +import static org.drools.core.rule.TypeMetaInfo.unmarshallMetaInfos; +import static org.drools.core.util.ClassUtils.convertResourceToClassName; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -16,16 +18,16 @@ import org.drools.compiler.kie.builder.impl.KieModuleCache.CompilationData; import org.drools.compiler.kie.builder.impl.KieModuleCache.Header; import org.drools.compiler.kie.builder.impl.KieModuleCache.KModuleCache; -import org.drools.compiler.kproject.models.KieModuleModelImpl; -import org.drools.core.rule.TypeMetaInfo; -import org.drools.core.util.StringUtils; import org.drools.compiler.kproject.models.KieBaseModelImpl; +import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.builder.conf.impl.DecisionTableConfigurationImpl; +import org.drools.core.rule.TypeMetaInfo; import org.drools.core.util.StringUtils; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.Results; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; +import org.kie.api.io.Resource; import org.kie.api.io.ResourceConfiguration; import org.kie.api.io.ResourceType; import org.kie.internal.builder.CompositeKnowledgeBuilder; @@ -35,26 +37,11 @@ import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.definition.KnowledgePackage; import org.kie.internal.io.ResourceFactory; -import org.kie.api.io.ResourceConfiguration; -import org.kie.api.io.ResourceType; import org.kie.internal.io.ResourceTypeImpl; -import org.kie.internal.utils.CompositeClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ExtensionRegistry; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase; -import static org.drools.core.rule.TypeMetaInfo.unmarshallMetaInfos; -import static org.drools.core.util.ClassUtils.convertResourceToClassName; public abstract class AbstractKieModule implements @@ -205,20 +192,7 @@ private static void addFiles( CompositeKnowledgeBuilder ckbuilder, int fileCount = 0; for ( String fileName : kieModule.getFileNames() ) { if ( filterFileInKBase(kieBaseModel, fileName) && !fileName.endsWith( "".properties"" ) ) { - ResourceConfiguration conf = getResourceConfiguration(kieModule, fileName); - byte[] bytes = kieModule.getBytes( fileName ); - if ( bytes == null || bytes.length == 0 ) { - continue; - } - if ( conf == null ) { - ckbuilder.add( ResourceFactory.newByteArrayResource( bytes ).setSourcePath( fileName ), - ResourceType.determineResourceType( fileName ) ); - } else { - ckbuilder.add( ResourceFactory.newByteArrayResource(bytes).setSourcePath(fileName), - ResourceType.determineResourceType( fileName ), - conf ); - } - fileCount++; + fileCount += addFile( ckbuilder, kieModule, fileName ) ? 1 : 0; } } if ( fileCount == 0 ) { @@ -230,6 +204,33 @@ private static void addFiles( CompositeKnowledgeBuilder ckbuilder, } } + + public static boolean addFile(CompositeKnowledgeBuilder ckbuilder, + InternalKieModule kieModule, + String fileName ) { + ResourceConfiguration conf = getResourceConfiguration(kieModule, fileName); + Resource resource = kieModule.getResource( fileName ); + if ( resource != null ) { + if ( conf == null ) { + ckbuilder.add( resource, + ResourceType.determineResourceType( fileName ) ); + } else { + ckbuilder.add( resource, + ResourceType.determineResourceType( fileName ), + conf ); + } + return true; + } + return false; + } + + public Resource getResource( String fileName ) { + byte[] bytes = getBytes( fileName ); + if ( bytes != null && bytes.length > 0 ) { + return ResourceFactory.newByteArrayResource( bytes ).setSourcePath( fileName ); + } + return null; + } public static ResourceConfiguration getResourceConfiguration(InternalKieModule kieModule, String fileName) { ResourceConfiguration conf = null; diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java index f4a0f1c9dc1..af72ac65289 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java @@ -103,4 +103,12 @@ protected void indexParts(Collection kieModules, } } } + + protected void cleanIndex() { + kBaseModels.clear(); + kSessionModels.clear(); + defaultKieBase = null; + defaultKieSession = null; + defaultStatelessKieSession = null; + } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java index 40f64e334c3..f9627acabb5 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java @@ -5,6 +5,7 @@ import org.kie.api.builder.KieModule; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.Results; +import org.kie.api.io.Resource; import org.kie.internal.definition.KnowledgePackage; import java.io.File; @@ -25,7 +26,9 @@ public interface InternalKieModule extends KieModule { KieModuleModel getKieModuleModel(); - byte[] getBytes( ); + byte[] getBytes( ); + + Resource getResource( String fileName ); Map getDependencies(); diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java index d3896a9203a..01cbc2693f6 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieBuilderImpl.java @@ -325,8 +325,8 @@ private void addMetaInfBuilder() { } } - static boolean filterFileInKBase(KieBaseModel kieBase, - String fileName) { + public static boolean filterFileInKBase(KieBaseModel kieBase, + String fileName) { return FormatsManager.isKieExtension( fileName ) && isFileInKieBase( kieBase, fileName ); } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java index 4437446c5bb..37971dea921 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java @@ -1,9 +1,22 @@ package org.drools.compiler.kie.builder.impl; +import static org.drools.compiler.kie.builder.impl.AbstractKieModule.buildKnowledgePackages; +import static org.drools.compiler.kie.util.CDIHelper.wireListnersAndWIHs; + +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; - +import java.util.Map.Entry; + +import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; +import org.drools.compiler.compiler.PackageBuilder; +import org.drools.compiler.kie.util.ChangeSetBuilder; +import org.drools.compiler.kie.util.ChangeType; +import org.drools.compiler.kie.util.KieJarChangeSet; +import org.drools.compiler.kie.util.ResourceChangeSet; import org.drools.compiler.kproject.models.KieBaseModelImpl; import org.drools.compiler.kproject.models.KieSessionModelImpl; import org.drools.core.impl.InternalKnowledgeBase; @@ -20,15 +33,15 @@ import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.StatelessKieSession; +import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; +import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilder; +import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.definition.KnowledgePackage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.drools.compiler.kie.builder.impl.AbstractKieModule.*; -import static org.drools.compiler.kie.util.CDIHelper.*; - public class KieContainerImpl implements InternalKieContainer { @@ -55,12 +68,78 @@ public ReleaseId getReleaseId() { return kProject.getGAV(); } - public void updateToVersion(ReleaseId releaseId) { - kBases.clear(); - this.kProject = new KieModuleKieProject( (InternalKieModule)kr.getKieModule(releaseId) ); - this.kProject.init(); + public void updateToVersion(ReleaseId newReleaseId) { + if( kProject instanceof ClasspathKieProject ) { + throw new UnsupportedOperationException( ""It is not possible to update a classpath container to a new version."" ); + } + ReleaseId currentReleaseId = kProject.getGAV(); + InternalKieModule currentKM = (InternalKieModule) kr.getKieModule( currentReleaseId ); + InternalKieModule newKM = (InternalKieModule) kr.getKieModule( newReleaseId ); + + ChangeSetBuilder csb = new ChangeSetBuilder(); + KieJarChangeSet cs = csb.build( currentKM, newKM ); + + ((KieModuleKieProject) kProject).updateToModule( newKM ); + + List kbasesToRemove = new ArrayList(); + for( Map.Entry kBaseEntry : kBases.entrySet() ) { + String kbaseName = kBaseEntry.getKey(); + KieBaseModel kieBaseModel = kProject.getKieBaseModel( kbaseName ); + // if a kbase no longer exists, just remove it from the cache + if( kieBaseModel == null ) { + // have to save for later removal to avoid iteration errors + kbasesToRemove.add( kbaseName ); + } else { + // attaching the builder to the kbase + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( (KnowledgeBase) kBaseEntry.getValue() ); + PackageBuilder pkgbuilder = kbuilder instanceof PackageBuilder ? ((PackageBuilder) kbuilder) : ((KnowledgeBuilderImpl)kbuilder).getPackageBuilder(); + CompositeKnowledgeBuilder ckbuilder = kbuilder.batch(); + int fileCount = 0; + + // remove resources first + for( ResourceChangeSet rcs : cs.getChanges().values() ) { + if( rcs.getChangeType().equals( ChangeType.REMOVED ) ) { + String resourceName = rcs.getResourceName(); + if( KieBuilderImpl.filterFileInKBase( kieBaseModel, resourceName ) && ! resourceName.endsWith( "".properties"" ) ) { + pkgbuilder.removeObjectsGeneratedFromResource( currentKM.getResource( resourceName ) ); + } + } + } + + // then update and add new resources + for( ResourceChangeSet rcs : cs.getChanges().values() ) { + if( ! rcs.getChangeType().equals( ChangeType.REMOVED ) ) { + String resourceName = rcs.getResourceName(); + if( KieBuilderImpl.filterFileInKBase( kieBaseModel, resourceName ) && ! resourceName.endsWith( "".properties"" ) ) { + fileCount += AbstractKieModule.addFile( ckbuilder, + newKM, + resourceName ) ? 1 : 0; + } + } + } + if( fileCount > 0 ) { + ckbuilder.build(); + } + } + } + + for( Iterator> it = this.kSessions.entrySet().iterator(); it.hasNext(); ) { + Entry ksession = it.next(); + if( kProject.getKieSessionModel( ksession.getKey() ) == null ) { + // remove sessions that no longer exist + it.remove(); + } + } + + for( Iterator> it = this.statelessKSessions.entrySet().iterator(); it.hasNext(); ) { + Entry ksession = it.next(); + if( kProject.getKieSessionModel( ksession.getKey() ) == null ) { + // remove sessions that no longer exist + it.remove(); + } + } } - + public KieBase getKieBase() { KieBaseModel defaultKieBaseModel = kProject.getDefaultKieBaseModel(); if (defaultKieBaseModel == null) { @@ -165,7 +244,7 @@ public KieSession newKieSession(Environment environment, KieSessionConfiguration private KieSessionModel findKieSessionModel(boolean stateless) { KieSessionModel defaultKieSessionModel = stateless ? kProject.getDefaultStatelessKieSession() : kProject.getDefaultKieSession(); if (defaultKieSessionModel == null) { - throw new RuntimeException(stateless ? ""Cannot find a defualt StatelessKieSession"" : ""Cannot find a defualt KieSession""); + throw new RuntimeException(stateless ? ""Cannot find a default StatelessKieSession"" : ""Cannot find a default KieSession""); } return defaultKieSessionModel; } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java index fc00c2c333a..40e3b59d18d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java @@ -22,15 +22,15 @@ */ public class KieModuleKieProject extends AbstractKieProject { - private static final Logger log = LoggerFactory.getLogger( KieModuleKieProject.class ); + private static final Logger log = LoggerFactory.getLogger( KieModuleKieProject.class ); - private List kieModules; + private List kieModules; - private final Map kJarFromKBaseName = new HashMap(); + private Map kJarFromKBaseName = new HashMap(); - private final InternalKieModule kieModule; + private InternalKieModule kieModule; - private final ProjectClassLoader cl; + private ProjectClassLoader cl; public KieModuleKieProject(InternalKieModule kieModule) { this.kieModule = kieModule; @@ -43,16 +43,16 @@ public void init() { kieModules.addAll( kieModule.getDependencies().values() ); kieModules.add( kieModule ); indexParts( kieModules, kJarFromKBaseName ); - initClassLoader(cl); + initClassLoader( cl ); } } private void initClassLoader(ProjectClassLoader projectCL) { - for (Map.Entry entry : getClassesMap().entrySet()) { - if (entry.getValue() != null) { + for ( Map.Entry entry : getClassesMap().entrySet() ) { + if ( entry.getValue() != null ) { String resourceName = entry.getKey(); - String className = convertResourceToClassName(resourceName); - projectCL.storeClass(className, resourceName, entry.getValue()); + String className = convertResourceToClassName( resourceName ); + projectCL.storeClass( className, resourceName, entry.getValue() ); } } } @@ -61,7 +61,7 @@ private Map getClassesMap() { Map classes = new HashMap(); for ( InternalKieModule kModule : kieModules ) { // avoid to take type declarations defined directly in this kieModule since they have to be recompiled - classes.putAll(kModule.getClassesMap(kModule != this.kieModule)); + classes.putAll( kModule.getClassesMap( kModule != this.kieModule ) ); } return classes; } @@ -71,7 +71,7 @@ public ReleaseId getGAV() { } public InternalKieModule getKieModuleForKBase(String kBaseName) { - return this.kJarFromKBaseName.get(kBaseName); + return this.kJarFromKBaseName.get( kBaseName ); } public ClassLoader getClassLoader() { @@ -79,8 +79,18 @@ public ClassLoader getClassLoader() { } public ClassLoader getClonedClassLoader() { - ProjectClassLoader clonedCL = createProjectClassLoader(cl.getParent()); - initClassLoader(clonedCL); + ProjectClassLoader clonedCL = createProjectClassLoader( cl.getParent() ); + initClassLoader( clonedCL ); return clonedCL; } + + public void updateToModule(InternalKieModule kieModule) { + this.kieModules = null; + this.kJarFromKBaseName.clear(); + cleanIndex(); + + this.kieModule = kieModule; + //this.cl.getStore().clear(); // can we do this in order to preserve the reference to the classloader? + this.init(); // this might override class definitions, not sure we can do it any other way though + } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java index 6c6cc3d19cd..14e53a08419 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java @@ -27,4 +27,5 @@ public interface KieProject { ClassLoader getClonedClassLoader(); ResultsImpl verify(); + } diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java index 460d6355ed0..bd172104dca 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java @@ -1,21 +1,26 @@ package org.drools.compiler.integrationtests; +import static junit.framework.Assert.assertEquals; + import org.drools.compiler.Message; +import org.drools.compiler.kie.builder.impl.InternalKieModule; +import org.junit.Ignore; import org.junit.Test; import org.kie.api.KieServices; -import org.kie.internal.builder.IncrementalResults; -import org.kie.internal.builder.InternalKieBuilder; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; +import org.kie.api.builder.KieModule; +import org.kie.api.builder.ReleaseId; +import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; - -import static junit.framework.Assert.assertEquals; +import org.kie.internal.builder.IncrementalResults; +import org.kie.internal.builder.InternalKieBuilder; public class IncrementalCompilationTest { @Test - public void testIncrementalCompilation() throws Exception { + public void testKJarUpgrade() throws Exception { String drl1 = ""package org.drools.compiler\n"" + ""rule R1 when\n"" + "" $m : Message()\n"" + @@ -35,28 +40,97 @@ public void testIncrementalCompilation() throws Exception { ""end\n""; KieServices ks = KieServices.Factory.get(); + + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + + // Create a session and fire rules + KieContainer kc = ks.newKieContainer( km.getReleaseId() ); + KieSession ksession = kc.newKieSession(); + ksession.insert(new Message(""Hello World"")); + assertEquals( 1, ksession.fireAllRules() ); + ksession.dispose(); - KieFileSystem kfs = ks.newKieFileSystem() - .write(""src/main/resources/r1.drl"", drl1) - .write(""src/main/resources/r2.drl"", drl2_1); + // Create a new jar for version 1.1.0 + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.1.0""); + km = createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); - KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); - KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()); + // try to update the container to version 1.1.0 + kc.updateToVersion(releaseId2); + + // create and use a new session + ksession = kc.newKieSession(); + ksession.insert(new Message(""Hello World"")); + assertEquals( 2, ksession.fireAllRules() ); + } - KieSession ksession = kieContainer.newKieSession(); + @Test + public void testKJarUpgradeSameSession() throws Exception { + String drl1 = ""package org.drools.compiler\n"" + + ""rule R1 when\n"" + + "" $m : Message()\n"" + + ""then\n"" + + ""end\n""; + + String drl2_1 = ""package org.drools.compiler\n"" + + ""rule R2_1 when\n"" + + "" $m : Message( message == \""Hi Universe\"" )\n"" + + ""then\n"" + + ""end\n""; + + String drl2_2 = ""package org.drools.compiler\n"" + + ""rule R2_2 when\n"" + + "" $m : Message( message == \""Hello World\"" )\n"" + + ""then\n"" + + ""end\n""; + + KieServices ks = KieServices.Factory.get(); + + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + + // Create a session and fire rules + KieContainer kc = ks.newKieContainer( km.getReleaseId() ); + KieSession ksession = kc.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 1, ksession.fireAllRules() ); - kfs.write(""src/main/resources/r2.drl"", drl2_2); - ((InternalKieBuilder)kieBuilder).createFileSet(""src/main/resources/r2.drl"").build(); + // Create a new jar for version 1.1.0 + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.1.0""); + km = createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); - kieContainer.updateToVersion(ks.getRepository().getDefaultReleaseId()); - ksession = kieContainer.newKieSession(); + // try to update the container to version 1.1.0 + kc.updateToVersion(releaseId2); + + // continue working with the session ksession.insert(new Message(""Hello World"")); - assertEquals( 2, ksession.fireAllRules() ); + assertEquals( 3, ksession.fireAllRules() ); + } + + private KieModule createAndDeployJar(KieServices ks, + ReleaseId releaseId, + String... drls ) { + KieFileSystem kfs = ks.newKieFileSystem() + .generateAndWritePomXML(releaseId); + for( int i = 0; i < drls.length; i++ ) { + if( drls[i] != null ) { + kfs.write(""src/main/resources/r""+i+"".drl"", drls[i]); + } + } + ks.newKieBuilder( kfs ).buildAll(); + InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule( releaseId ); + byte[] jar = kieModule.getBytes(); + + // Deploy jar into the repository + Resource jarRes = ks.getResources().newByteArrayResource( jar ); + KieModule km = ks.getRepository().addKieModule( jarRes ); + return km; } @Test + @Ignore public void testDeletedFile() throws Exception { String drl1 = ""package org.drools.compiler\n"" + ""rule R1 when\n"" + @@ -72,21 +146,21 @@ public void testDeletedFile() throws Exception { KieServices ks = KieServices.Factory.get(); - KieFileSystem kfs = ks.newKieFileSystem() - .write(""src/main/resources/r1.drl"", drl1) - .write(""src/main/resources/r2.drl"", drl2); + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-delete"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2 ); - KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); - KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()); + KieContainer kieContainer = ks.newKieContainer(releaseId1); KieSession ksession = kieContainer.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 2, ksession.fireAllRules() ); - kfs.delete(""src/main/resources/r1.drl""); - ((InternalKieBuilder)kieBuilder).createFileSet(""src/main/resources/r1.drl"").build(); + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-delete"", ""1.0.1""); + km = createAndDeployJar( ks, releaseId2, null, drl2 ); - kieContainer.updateToVersion(ks.getRepository().getDefaultReleaseId()); + kieContainer.updateToVersion(releaseId2); + ksession = kieContainer.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 1, ksession.fireAllRules() ); diff --git a/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java b/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java index 901bb4e06ab..30e239ea8f1 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java @@ -45,7 +45,6 @@ public void testNoChanges() { ChangeSetBuilder builder = new ChangeSetBuilder(); KieJarChangeSet changes = builder.build( kieJar1, kieJar2 ); - System.out.println( builder.toProperties( changes ) ); assertThat( changes.getChanges().size(), is(0)); } @@ -85,9 +84,8 @@ public void testModified() { assertThat( cs.getChanges().get( 1 ), is( new ResourceChange(ChangeType.ADDED, Type.RULE, ""R3"") ) ); assertThat( cs.getChanges().get( 0 ), is( new ResourceChange(ChangeType.REMOVED, Type.RULE, ""R2"") ) ); - ChangeSetBuilder builder = new ChangeSetBuilder(); - System.out.println( builder.toProperties( changes ) ); - +// ChangeSetBuilder builder = new ChangeSetBuilder(); +// System.out.println( builder.toProperties( changes ) ); } @Test @@ -166,7 +164,7 @@ public void testModified2() { ChangeSetBuilder builder = new ChangeSetBuilder(); KieJarChangeSet changes = builder.build( kieJar1, kieJar2 ); - System.out.println( builder.toProperties( changes ) ); +// System.out.println( builder.toProperties( changes ) ); String modifiedFile = (String) kieJar2.getFileNames().toArray()[0]; String addedFile = (String) kieJar2.getFileNames().toArray()[1]; @@ -202,7 +200,7 @@ private InternalKieModule createKieJar( String... drls) { for( int i=0; i entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); - if (entry.getName().matches(""/lib/[^/]+\\.jar"")) { + if (entry.getName().matches(""[/]?lib/[^/]+\\.jar"")) { File file = new File(parentDir, ""."" + pathPrefix + ""."" + path.getName() + ""."" + System.currentTimeMillis() + ""."" + entry.getName().substring(5)); IOUtils.copyBytes(jarFile.getInputStream(entry), new FileOutputStream(file), conf, true); diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestClassLoading.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestClassLoading.java index 2eb3300f54db..b6b92c35e84b 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestClassLoading.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestClassLoading.java @@ -382,6 +382,15 @@ public void testHBase3810() throws Exception { @Test public void testClassLoadingFromLibDirInJar() throws Exception { + loadingClassFromLibDirInJar(""/lib/""); + } + + @Test + public void testClassLoadingFromRelativeLibDirInJar() throws Exception { + loadingClassFromLibDirInJar(""lib/""); + } + + void loadingClassFromLibDirInJar(String libPrefix) throws Exception { FileSystem fs = cluster.getFileSystem(); File innerJarFile1 = buildCoprocessorJar(cpName1); @@ -397,7 +406,7 @@ public void testClassLoadingFromLibDirInJar() throws Exception { for (File jarFile: new File[] { innerJarFile1, innerJarFile2 }) { // Add archive entry - JarEntry jarAdd = new JarEntry(""/lib/"" + jarFile.getName()); + JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName()); jarAdd.setTime(jarFile.lastModified()); out.putNextEntry(jarAdd);" 662f0972b4af7430f6d008b933f4faa15f5788d3,orientdb,Huge refactoring on GraphDB: - changed class- names in vertex and edge - Optimized memory consumption by removing nested- records - Optimized speed in ORecord.equals() and hashCode(): now avoid field- checks (experimental)--,p,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java index 2ceeceb3741..90204a28c4b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java @@ -38,17 +38,18 @@ public ODatabaseGraphTx(final String iURL) { } @SuppressWarnings(""unchecked"") - public THISDB open(String iUserName, String iUserPassword) { + public THISDB open(final String iUserName, final String iUserPassword) { underlying.open(iUserName, iUserPassword); - if (!underlying.getMetadata().getSchema().existsClass(""OGraphNode"")) { + if (!underlying.getMetadata().getSchema().existsClass(OGraphVertex.CLASS_NAME)) { final OClass node = underlying.getMetadata().getSchema() - .createClass(""OGraphNode"", underlying.addPhysicalCluster(""OGraphNode"")); - final OClass arc = underlying.getMetadata().getSchema().createClass(""OGraphArc"", underlying.addPhysicalCluster(""OGraphArc"")); + .createClass(OGraphVertex.CLASS_NAME, underlying.addPhysicalCluster(OGraphVertex.CLASS_NAME)); + final OClass arc = underlying.getMetadata().getSchema() + .createClass(OGraphEdge.CLASS_NAME, underlying.addPhysicalCluster(OGraphEdge.CLASS_NAME)); - arc.createProperty(""from"", OType.LINK, node); - arc.createProperty(""to"", OType.LINK, node); - node.createProperty(""arcs"", OType.EMBEDDEDLIST, arc); + arc.createProperty(OGraphEdge.SOURCE, OType.LINK, node); + arc.createProperty(OGraphEdge.DESTINATION, OType.LINK, node); + node.createProperty(OGraphVertex.FIELD_EDGES, OType.EMBEDDEDLIST, arc); underlying.getMetadata().getSchema().save(); } @@ -56,25 +57,25 @@ public THISDB open(String iUserName, String iUserPass return (THISDB) this; } - public OGraphNode createNode() { - return new OGraphNode(this); + public OGraphVertex createVertex() { + return new OGraphVertex(this); } - public OGraphNode getRoot(final String iName) { - return new OGraphNode(underlying.getDictionary().get(iName)); + public OGraphVertex getRoot(final String iName) { + return new OGraphVertex(underlying.getDictionary().get(iName)); } - public OGraphNode getRoot(final String iName, final String iFetchPlan) { - return new OGraphNode(underlying.getDictionary().get(iName), iFetchPlan); + public OGraphVertex getRoot(final String iName, final String iFetchPlan) { + return new OGraphVertex(underlying.getDictionary().get(iName), iFetchPlan); } - public ODatabaseGraphTx setRoot(final String iName, final OGraphNode iNode) { + public ODatabaseGraphTx setRoot(final String iName, final OGraphVertex iNode) { underlying.getDictionary().put(iName, iNode.getDocument()); return this; } public OGraphElement newInstance() { - return new OGraphNode(this); + return new OGraphVertex(this); } public OGraphElement load(final OGraphElement iObject) { @@ -91,10 +92,10 @@ public OGraphElement load(final ORID iRecordId) { if (doc == null) return null; - if (doc.getClassName().equals(OGraphNode.class.getSimpleName())) - return new OGraphNode(doc); - else if (doc.getClassName().equals(OGraphArc.class.getSimpleName())) - return new OGraphArc(doc); + if (doc.getClassName().equals(OGraphVertex.class.getSimpleName())) + return new OGraphVertex(doc); + else if (doc.getClassName().equals(OGraphEdge.class.getSimpleName())) + return new OGraphEdge(doc); else throw new IllegalArgumentException(""RecordID is not of supported type. Class="" + doc.getClassName()); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphArc.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java similarity index 52% rename from core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphArc.java rename to core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java index f631d15cd1f..580f97a1505 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphArc.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java @@ -23,44 +23,56 @@ /** * GraphDB Node. */ -public class OGraphArc extends OGraphElement { - private static final String CLASS_NAME = ""OGraphArc""; - private static final String SOURCE = ""source""; - private static final String DESTINATION = ""destination""; +public class OGraphEdge extends OGraphElement { + public static final String CLASS_NAME = ""OGraphEdge""; + public static final String SOURCE = ""source""; + public static final String DESTINATION = ""destination""; - private OGraphNode source; - private OGraphNode destination; + private OGraphVertex source; + private OGraphVertex destination; - public OGraphArc(final ODatabaseRecord iDatabase, final ORID iRID) { + public OGraphEdge(final ODatabaseRecord iDatabase, final ORID iRID) { super(iDatabase, iRID); } - public OGraphArc(final ODatabaseRecord iDatabase) { + public OGraphEdge(final ODatabaseRecord iDatabase) { super(iDatabase, CLASS_NAME); } - public OGraphArc(final ODatabaseRecord database, final OGraphNode iSourceNode, final OGraphNode iDestinationNode) { + public OGraphEdge(final ODatabaseRecord database, final OGraphVertex iSourceNode, final OGraphVertex iDestinationNode) { this(database); + source = iSourceNode; + destination = iDestinationNode; set(SOURCE, iSourceNode.getDocument()).set(DESTINATION, iDestinationNode.getDocument()); } - public OGraphArc(final ODocument iDocument) { + public OGraphEdge(final ODocument iDocument) { super(iDocument); if (iDocument.getInternalStatus() == STATUS.NOT_LOADED) iDocument.load(); } - public OGraphNode getSource() { + public OGraphVertex getSource() { if (source == null) - source = new OGraphNode((ODocument) document.field(SOURCE)); + source = new OGraphVertex((ODocument) document.field(SOURCE)); return source; } - public OGraphNode getDestination() { + public void setSource(final OGraphVertex iSource) { + this.source = iSource; + document.field(SOURCE, iSource.getDocument()); + } + + public OGraphVertex getDestination() { if (destination == null) - destination = new OGraphNode((ODocument) document.field(DESTINATION)); + destination = new OGraphVertex((ODocument) document.field(DESTINATION)); return destination; } + + public void setDestination(final OGraphVertex iDestination) { + this.destination = iDestination; + document.field(DESTINATION, iDestination.getDocument()); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphElement.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphElement.java index 1e50d270d9b..1b480a9f866 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphElement.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphElement.java @@ -58,4 +58,34 @@ public void save() { public ODocument getDocument() { return document; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((document == null) ? 0 : document.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; + OGraphElement other = (OGraphElement) obj; + if (document == null) { + if (other.document != null) + return false; + } else if (!document.equals(other.document)) + return false; + return true; + } + + @Override + public String toString() { + return document != null ? document.toString() : ""?""; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphNode.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphVertex.java similarity index 53% rename from core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphNode.java rename to core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphVertex.java index 1cb1c534dc7..f2534da418a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphNode.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphVertex.java @@ -26,62 +26,84 @@ /** * GraphDB Node. */ -public class OGraphNode extends OGraphElement { - private static final String CLASS_NAME = ""OGraphNode""; +public class OGraphVertex extends OGraphElement { + public static final String CLASS_NAME = ""OGraphVertex""; + public static final String FIELD_EDGES = ""edges""; - private List arcs; + private List edges; - public OGraphNode(final ODatabaseGraphTx iDatabase, final ORID iRID) { + public OGraphVertex(final ODatabaseGraphTx iDatabase, final ORID iRID) { super(new ODocument((ODatabaseRecord) iDatabase.getUnderlying(), iRID)); } - public OGraphNode(final ODatabaseGraphTx iDatabase) { + public OGraphVertex(final ODatabaseGraphTx iDatabase) { super(new ODocument((ODatabaseRecord) iDatabase.getUnderlying(), CLASS_NAME)); } - public OGraphNode(final ODocument iDocument) { + public OGraphVertex(final ODocument iDocument) { super(iDocument); if (iDocument.getInternalStatus() == STATUS.NOT_LOADED) iDocument.load(); } - public OGraphNode(final ODocument iDocument, final String iFetchPlan) { + public OGraphVertex(final ODocument iDocument, final String iFetchPlan) { super(iDocument); if (iDocument.getInternalStatus() == STATUS.NOT_LOADED) iDocument.load(iFetchPlan); } @SuppressWarnings(""unchecked"") - public OGraphArc link(final OGraphNode iDestinationNode) { + public OGraphEdge link(final OGraphVertex iDestinationNode) { if (iDestinationNode == null) throw new IllegalArgumentException(""Missed the arc destination property""); - final OGraphArc arc = new OGraphArc(document.getDatabase(), this, iDestinationNode); - getArcs().add(arc); - ((List) document.field(""arcs"")).add(arc.getDocument()); + final OGraphEdge arc = new OGraphEdge(document.getDatabase(), this, iDestinationNode); + getEdges().add(arc); + ((List) document.field(FIELD_EDGES)).add(arc.getDocument()); return arc; } /** * Returns the arcs of current node. If there are no arcs, then an empty list is returned. */ - public List getArcs() { - if (arcs == null) { - arcs = new ArrayList(); + public List getEdges() { + if (edges == null) { + edges = new ArrayList(); - List docs = document.field(""arcs""); + List docs = document.field(FIELD_EDGES); if (docs == null) { docs = new ArrayList(); - document.field(""arcs"", docs); + document.field(FIELD_EDGES, docs); } else { // TRANSFORM ALL THE ARCS for (ODocument d : docs) { - arcs.add(new OGraphArc(d)); + edges.add(new OGraphEdge(d)); } } } - return arcs; + return edges; + } + + @SuppressWarnings(""unchecked"") + public List browseEdgeDestinations() { + final List resultset = new ArrayList(); + + if (edges == null) { + List docEdges = (List) document.field(FIELD_EDGES); + + // TRANSFORM ALL THE ARCS + if (docEdges != null) + for (ODocument d : docEdges) { + resultset.add(new OGraphVertex((ODocument) d.field(OGraphEdge.DESTINATION))); + } + } else { + for (OGraphEdge edge : edges) { + resultset.add(edge.getDestination()); + } + } + + return resultset; } } diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTest.java deleted file mode 100644 index 26bcc7d3487..00000000000 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) - * - * Licensed under the Apache License, Version 2.0 (the ""License""); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.orientechnologies.orient.test.database.auto; - -import java.util.Date; - -import org.testng.Assert; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import com.orientechnologies.orient.client.remote.OEngineRemote; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; -import com.orientechnologies.orient.core.db.graph.OGraphArc; -import com.orientechnologies.orient.core.db.graph.OGraphNode; - -@Test(sequential = true) -public class GraphTest { - protected static final int TOT_RECORDS = 100; - protected long startRecordNumber; - private ODatabaseGraphTx database; - - @Parameters(value = ""url"") - public GraphTest(String iURL) { - Orient.instance().registerEngine(new OEngineRemote()); - database = new ODatabaseGraphTx(iURL); - } - - @Test - public void populate() { - database.open(""admin"", ""admin""); - - OGraphNode rootNode = database.createNode().set(""id"", 0); - - OGraphNode newNode; - OGraphNode currentNode = rootNode; - - for (int i = 1; i <= TOT_RECORDS; ++i) { - - newNode = database.createNode().set(""id"", i); - currentNode.link(newNode).set(""createdOn"", new Date()); - - currentNode = newNode; - } - - database.setRoot(""test"", rootNode); - - database.close(); - } - - @Test(dependsOnMethods = ""populate"") - public void checkPopulation() { - database.open(""admin"", ""admin""); - - int counter = 0; - OGraphNode currentNode = database.getRoot(""test""); - while (!currentNode.getArcs().isEmpty()) { - Assert.assertEquals(((Number) currentNode.get(""id"")).intValue(), counter); - - for (OGraphArc arc : currentNode.getArcs()) { - counter++; - currentNode = arc.getDestination(); - } - } - - Assert.assertEquals(counter, TOT_RECORDS); - - database.close(); - } -} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestFixedDensity.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestFixedDensity.java new file mode 100644 index 00000000000..1619e104e4f --- /dev/null +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestFixedDensity.java @@ -0,0 +1,110 @@ +/* + * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.orientechnologies.orient.test.database.auto; + +import org.testng.Assert; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import com.orientechnologies.orient.client.remote.OEngineRemote; +import com.orientechnologies.orient.core.Orient; +import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; +import com.orientechnologies.orient.core.db.graph.OGraphVertex; + +@Test(sequential = true) +public class GraphTestFixedDensity { + private static final int MAX_DEEP = 1000; + private static final int DENSITY = 1; + + private ODatabaseGraphTx database; + private int nodeWrittenCounter = 0; + private int nodeReadCounter = -1; + + @Parameters(value = ""url"") + public GraphTestFixedDensity(String iURL) { + Orient.instance().registerEngine(new OEngineRemote()); + database = new ODatabaseGraphTx(iURL); + } + + @Test + public void populate() { + database.open(""admin"", ""admin""); + + long time = System.currentTimeMillis(); + + OGraphVertex rootNode = database.createVertex().set(""id"", 0); + + createSubNodes(rootNode, 0); + + database.setRoot(""LinearGraph"", rootNode); + + System.out.println(""Creation of the graph with deep="" + MAX_DEEP + "" and fixed density=1"" + + ((System.currentTimeMillis() - time) / 1000f) + "" sec.""); + + database.close(); + } + + @Test(dependsOnMethods = ""populate"") + public void checkPopulation() { + database.open(""admin"", ""admin""); + + long time = System.currentTimeMillis(); + + readSubNodes(database.getRoot(""LinearGraph"")); + + System.out.println(""Read of the entire graph with deep="" + nodeReadCounter + "" and fixed density="" + DENSITY + "" in "" + + ((System.currentTimeMillis() - time) / 1000f) + "" sec.""); + + Assert.assertEquals(nodeReadCounter, nodeWrittenCounter); + } + + @Test(dependsOnMethods = ""populate"") + public void checkPopulationHotCache() { + long time = System.currentTimeMillis(); + + nodeReadCounter = -1; + readSubNodes(database.getRoot(""LinearGraph"")); + + System.out.println(""Read with hot cache of the entire graph with deep="" + nodeReadCounter + "" and fixed density="" + DENSITY + + "" in "" + ((System.currentTimeMillis() - time) / 1000f) + "" sec.""); + + Assert.assertEquals(nodeReadCounter, nodeWrittenCounter); + + database.close(); + } + + private void readSubNodes(final OGraphVertex iNode) { + Assert.assertEquals(((Number) iNode.get(""id"")).intValue(), ++nodeReadCounter); + + for (OGraphVertex node : iNode.browseEdgeDestinations()) { + readSubNodes(node); + } + } + + private void createSubNodes(final OGraphVertex iNode, final int iDeepLevel) { + OGraphVertex newNode; + + for (int i = 0; i < DENSITY; ++i) { + newNode = database.createVertex().set(""id"", ++nodeWrittenCounter); + iNode.link(newNode); + + if (iDeepLevel < MAX_DEEP) + createSubNodes(newNode, iDeepLevel + 1); + } + + iNode.save(); + } +} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestVariableDensity.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestVariableDensity.java new file mode 100644 index 00000000000..e875970ddc8 --- /dev/null +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/GraphTestVariableDensity.java @@ -0,0 +1,131 @@ +/* + * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.orientechnologies.orient.test.database.auto; + +import org.testng.Assert; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import com.orientechnologies.orient.client.remote.OEngineRemote; +import com.orientechnologies.orient.core.Orient; +import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; +import com.orientechnologies.orient.core.db.graph.OGraphVertex; + +@Test(sequential = true) +public class GraphTestVariableDensity { + private static final int MAX_NODES = 1000000; + private static final int MAX_DEEP = 5; + private static final int START_DENSITY = 184; + private static final int DENSITY_FACTOR = 13; + + private static int nodeWrittenCounter = 0; + private static int arcWrittenCounter = 0; + private static int nodeReadCounter = 0; + private static int arcReadCounter = 0; + + private ODatabaseGraphTx database; + + @Parameters(value = ""url"") + public GraphTestVariableDensity(String iURL) { + Orient.instance().registerEngine(new OEngineRemote()); + database = new ODatabaseGraphTx(iURL); + } + + @Test(dependsOnMethods = ""checkPopulation"") + public void populateWithHighDensity() { + database.open(""admin"", ""admin""); + + long time = System.currentTimeMillis(); + + OGraphVertex rootNode = database.createVertex().set(""id"", 0); + + nodeWrittenCounter = 1; + createSubNodes(rootNode, 0, START_DENSITY); + + long lap = System.currentTimeMillis(); + + database.setRoot(""HighDensityGraph"", rootNode); + + System.out.println(""Creation of the graph with deep="" + MAX_DEEP + "" and density variable <=30. Total "" + nodeWrittenCounter + + "" nodes and "" + arcWrittenCounter + "" arcs in "" + ((lap - time) / 1000f) + "" sec.""); + database.close(); + } + + @Test(dependsOnMethods = ""populateWithHighDensity"") + public void checkHighDensityPopulation() { + database.open(""admin"", ""admin""); + + long time = System.currentTimeMillis(); + + readSubNodes(database.getRoot(""HighDensityGraph"")); + + System.out.println(""Read of the entire graph with deep="" + MAX_DEEP + "" and density variable <=30 Total "" + nodeReadCounter + + "" nodes and "" + arcReadCounter + "" arcs in "" + ((System.currentTimeMillis() - time) / 1000f) + "" sec.""); + + Assert.assertEquals(nodeReadCounter, nodeWrittenCounter); + } + + @Test(dependsOnMethods = ""checkHighDensityPopulation"") + public void checkHighDensityPopulationHotCache() { + + long time = System.currentTimeMillis(); + + nodeReadCounter = arcReadCounter = 0; + readSubNodes(database.getRoot(""HighDensityGraph"")); + + System.out.println(""Read of the entire graph with deep="" + MAX_DEEP + "" and density variable <=30 Total "" + nodeReadCounter + + "" nodes and "" + arcReadCounter + "" arcs in "" + ((System.currentTimeMillis() - time) / 1000f) + "" sec.""); + + Assert.assertEquals(nodeReadCounter, nodeWrittenCounter); + + database.close(); + } + + private void readSubNodes(final OGraphVertex iNode) { + Assert.assertEquals(((Number) iNode.get(""id"")).intValue(), nodeReadCounter); + + nodeReadCounter++; + + for (OGraphVertex node : iNode.browseEdgeDestinations()) { + arcReadCounter++; + readSubNodes(node); + } + } + + private void createSubNodes(final OGraphVertex iNode, final int iDeepLevel, int iDensity) { + System.out.println(""Creating "" + iDensity + "" sub nodes...""); + + OGraphVertex newNode; + + for (int i = 0; i <= iDensity && nodeWrittenCounter < MAX_NODES; ++i) { + newNode = database.createVertex().set(""id"", nodeWrittenCounter++); + iNode.link(newNode); + arcWrittenCounter++; + + if (iDeepLevel < MAX_DEEP) { + if (iDensity * DENSITY_FACTOR / 100 > 0) + iDensity -= iDensity * DENSITY_FACTOR / 100; + else + iDensity -= 1; + + createSubNodes(newNode, iDeepLevel + 1, iDensity); + } + } + + iNode.save(); + } + +} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml index b5163e9948d..43460cfeaae 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/remote-test-db-from-scratch.xml @@ -60,6 +60,12 @@ + + + + + + " 19152416a44473325a6c3605f9accc4fee379b63,elasticsearch,add an index level setting to disable/enable- purging of expired docs (issue -1791)--,a,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java index ae4a010e95c40..f000ba6987225 100644 --- a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java +++ b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java @@ -31,6 +31,8 @@ import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.client.Client; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.component.AbstractLifecycleComponent; import org.elasticsearch.common.inject.Inject; @@ -65,8 +67,13 @@ public class IndicesTTLService extends AbstractLifecycleComponent getShardsToPurge() { List shardsToPurge = new ArrayList(); for (IndexService indexService : indicesService) { + // check the value of disable_purge for this index + IndexMetaData indexMetaData = clusterService.state().metaData().index(indexService.index().name()); + boolean disablePurge = indexMetaData.settings().getAsBoolean(""index.ttl.disable_purge"", false); + if (disablePurge) { + continue; + } + // should be optimized with the hasTTL flag FieldMappers ttlFieldMappers = indexService.mapperService().name(TTLFieldMapper.NAME); if (ttlFieldMappers == null) {" fe164471124f357d20acb18f6a6059eb5f91be07,spring-framework,more work on enabling non-namespace extensions of- xml parsing--,a,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java index b0719aa07db9..eb86869264ee 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java @@ -1417,4 +1417,14 @@ public String getNamespaceURI(Node node) { public boolean nodeNameEquals(Node node, String desiredName) { return DomUtils.nodeNameEquals(node, desiredName); } + + /** + * Gets the local name for the supplied {@link Node}. The default implementation calls {@link Node#getLocalName}. + * Subclasses may override the default implementation to provide a different mechanism for getting the local name. + * @param node the Node + * @return the local name of the supplied Node. + */ + public String getLocalName(Node node) { + return node.getLocalName(); + } } diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java index ae1e28e3d176..ee996402b83a 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/factory/xml/NamespaceHandlerSupport.java @@ -77,10 +77,11 @@ public final BeanDefinition parse(Element element, ParserContext parserContext) * the local name of the supplied {@link Element}. */ private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) { - BeanDefinitionParser parser = this.parsers.get(element.getLocalName()); + String localName = parserContext.getDelegate().getLocalName(element); + BeanDefinitionParser parser = this.parsers.get(localName); if (parser == null) { parserContext.getReaderContext().fatal( - ""Cannot locate BeanDefinitionParser for element ["" + element.getLocalName() + ""]"", element); + ""Cannot locate BeanDefinitionParser for element ["" + localName + ""]"", element); } return parser; } @@ -102,11 +103,12 @@ public final BeanDefinitionHolder decorate( */ private BeanDefinitionDecorator findDecoratorForNode(Node node, ParserContext parserContext) { BeanDefinitionDecorator decorator = null; + String localName = parserContext.getDelegate().getLocalName(node); if (node instanceof Element) { - decorator = this.decorators.get(node.getLocalName()); + decorator = this.decorators.get(localName); } else if (node instanceof Attr) { - decorator = this.attributeDecorators.get(node.getLocalName()); + decorator = this.attributeDecorators.get(localName); } else { parserContext.getReaderContext().fatal( @@ -114,7 +116,7 @@ else if (node instanceof Attr) { } if (decorator == null) { parserContext.getReaderContext().fatal(""Cannot locate BeanDefinitionDecorator for "" + - (node instanceof Element ? ""element"" : ""attribute"") + "" ["" + node.getLocalName() + ""]"", node); + (node instanceof Element ? ""element"" : ""attribute"") + "" ["" + localName + ""]"", node); } return decorator; }" ae3c13a83d610f3003cf800e2286a8bba69bf2b1,intellij-community,Cleanup code--,p,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java index 6be07ffa52927..ac81fea6270d7 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndex.java @@ -20,6 +20,7 @@ import gnu.trove.THashMap; import gnu.trove.THashSet; import org.apache.lucene.search.Query; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.jetbrains.idea.maven.model.MavenArtifactInfo; @@ -137,7 +138,7 @@ public MavenIndex(MavenIndexerWrapper indexer, open(); } - private String normalizePathOrUrl(String pathOrUrl) { + private static String normalizePathOrUrl(String pathOrUrl) { pathOrUrl = pathOrUrl.trim(); pathOrUrl = FileUtil.toSystemIndependentName(pathOrUrl); while (pathOrUrl.endsWith(""/"")) { @@ -169,10 +170,16 @@ private void open() throws MavenIndexException { private void doOpen() throws Exception { try { + File dataDir; if (myDataDirName == null) { - myDataDirName = findAvailableDataDirName(); + dataDir = createNewDataDir(); + myDataDirName = dataDir.getName(); } - myData = openData(myDataDirName); + else { + dataDir = new File(myDir, myDataDirName); + dataDir.mkdirs(); + } + myData = new IndexData(dataDir); } catch (Exception e) { cleanupBrokenData(); @@ -309,17 +316,16 @@ private void updateContext(int indexId, MavenGeneralSettings settings, MavenProg } private void updateData(MavenProgressIndicator progress) throws MavenIndexException { - String newDataDirName; IndexData newData; - newDataDirName = findAvailableDataDirName(); + File newDataDir = createNewDataDir(); try { - FileUtil.copyDir(getUpdateDir(), getDataContextDir(getDataDir(newDataDirName))); + FileUtil.copyDir(getUpdateDir(), getDataContextDir(newDataDir)); } catch (IOException e) { throw new MavenIndexException(e); } - newData = openData(newDataDirName); + newData = new IndexData(newDataDir); try { doUpdateIndexData(newData, progress); @@ -327,7 +333,7 @@ private void updateData(MavenProgressIndicator progress) throws MavenIndexExcept } catch (Throwable e) { newData.close(true); - FileUtil.delete(getDataDir(newDataDirName)); + FileUtil.delete(newDataDir); if (e instanceof MavenServerIndexerException) throw new MavenIndexException(e); if (e instanceof IOException) throw new MavenIndexException(e); @@ -338,18 +344,15 @@ private void updateData(MavenProgressIndicator progress) throws MavenIndexExcept IndexData oldData = myData; myData = newData; - myDataDirName = newDataDirName; + myDataDirName = newDataDir.getName(); myUpdateTimestamp = System.currentTimeMillis(); oldData.close(true); - File[] children = myDir.listFiles(); - if (children != null) { - for (File each : children) { - if (each.getName().startsWith(DATA_DIR_PREFIX) && !each.getName().equals(newDataDirName)) { - FileUtil.delete(each); - } + for (File each : FileUtil.notNullize(myDir.listFiles())) { + if (each.getName().startsWith(DATA_DIR_PREFIX) && !each.getName().equals(myDataDirName)) { + FileUtil.delete(each); } } } @@ -366,7 +369,7 @@ private void doUpdateIndexData(IndexData data, progress.setIndeterminate(true); try { - data.processArtifacts(new MavenIndicesProcessor() { + myIndexer.processArtifacts(data.indexId, new MavenIndicesProcessor() { @Override public void processArtifacts(Collection artifacts) { for (MavenId each : artifacts) { @@ -393,7 +396,7 @@ public void processArtifacts(Collection artifacts) { } } - private Set getOrCreate(Map> map, String key) { + private static Set getOrCreate(Map> map, String key) { Set result = map.get(key); if (result == null) { result = new THashSet(); @@ -408,18 +411,6 @@ private static void persist(Map map, PersistentHashMap } } - private static void persist(Set groups, PersistentStringEnumerator persistent) throws IOException { - for (String each : groups) { - persistent.enumerate(each); - } - } - - private IndexData openData(String dataDir) throws MavenIndexException { - File dir = getDataDir(dataDir); - dir.mkdirs(); - return new IndexData(dir); - } - @TestOnly public File getDir() { return myDir; @@ -427,19 +418,16 @@ public File getDir() { @TestOnly protected synchronized File getCurrentDataDir() { - return getDataDir(myDataDirName); - } - - private File getDataDir(String dataDirName) { - return new File(myDir, dataDirName); + return new File(myDir, myDataDirName); } private static File getDataContextDir(File dataDir) { return new File(dataDir, ""context""); } - private String findAvailableDataDirName() { - return MavenIndices.findAvailableDir(myDir, DATA_DIR_PREFIX, 100).getName(); + @NotNull + private File createNewDataDir() { + return MavenIndices.createNewDir(myDir, DATA_DIR_PREFIX, 100); } public synchronized void addArtifact(final File artifactFile) { @@ -659,10 +647,6 @@ public void flush() throws IOException { groupWithArtifactToVersionMap.force(); } - public void processArtifacts(MavenIndicesProcessor processor) throws MavenServerIndexerException { - myIndexer.processArtifacts(indexId, processor); - } - public MavenId addArtifact(File artifactFile) throws MavenServerIndexerException { return myIndexer.addArtifact(indexId, artifactFile); } diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java index 68554ed62af57..bb46e9d7ab1c3 100644 --- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java +++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndices.java @@ -16,6 +16,7 @@ package org.jetbrains.idea.maven.indices; import com.intellij.openapi.util.io.FileUtil; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.server.MavenIndexerWrapper; @@ -83,7 +84,7 @@ public synchronized MavenIndex add(String repositoryId, String repositoryPathOrU MavenIndex index = find(repositoryId, repositoryPathOrUrl, kind); if (index != null) return index; - File dir = getAvailableIndexDir(); + File dir = createNewIndexDir(); index = new MavenIndex(myIndexer, dir, repositoryId, repositoryPathOrUrl, kind, myListener); myIndices.add(index); return index; @@ -97,11 +98,12 @@ public MavenIndex find(String repositoryId, String repositoryPathOrUrl, MavenInd return null; } - private File getAvailableIndexDir() { - return findAvailableDir(myIndicesDir, ""Index"", 1000); + private File createNewIndexDir() { + return createNewDir(myIndicesDir, ""Index"", 1000); } - static File findAvailableDir(File parent, String prefix, int max) { + @NotNull + static File createNewDir(File parent, String prefix, int max) { synchronized (ourDirectoryLock) { for (int i = 0; i < max; i++) { String name = prefix + i;" a9a93876f2ead9468fd50eba715083c9a7e8a52a,drools,JBRULES-3714 Add capability to configure- date-effective/date-expires for SpreadSheet--,a,https://github.com/kiegroup/drools,"diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java index 73cb78135c8..9fe46429cd8 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java @@ -46,6 +46,8 @@ public enum Code { ACTIVATIONGROUP( ""ACTIVATION-GROUP"", ""X"", 1 ), AGENDAGROUP( ""AGENDA-GROUP"", ""G"", 1 ), RULEFLOWGROUP( ""RULEFLOW-GROUP"", ""R"", 1 ), + DATEEFFECTIVE( ""DATE-EFFECTIVE"", ""V"", 1 ), + DATEEXPIRES( ""DATE-EXPIRES"", ""Z"", 1 ), METADATA( ""METADATA"", ""@"" ); private String colHeader; @@ -80,7 +82,7 @@ public int getMaxCount() { } } - public static final EnumSet ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.RULEFLOWGROUP ); + public static final EnumSet ATTRIBUTE_CODE_SET = EnumSet.range( Code.SALIENCE, Code.DATEEXPIRES ); private static final Map tag2code = new HashMap(); static { diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java index 1e513078472..c5ba2bb178d 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java @@ -240,6 +240,12 @@ private Package buildRuleSet() { case RULEFLOWGROUP: ruleset.setRuleFlowGroup( value ); break; + case DATEEFFECTIVE: + ruleset.setDateEffective( value ); + break; + case DATEEXPIRES: + ruleset.setDateExpires( value ); + break; } } } @@ -648,6 +654,12 @@ private void nextDataCell(final int row, case CALENDARS: this._currentRule.setCalendars( value ); break; + case DATEEFFECTIVE: + this._currentRule.setDateEffective( value ); + break; + case DATEEXPIRES: + this._currentRule.setDateExpires( value ); + break; } } diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java index 1b6e45ff102..150eac13869 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java @@ -192,6 +192,10 @@ public void testAttributesXLS() { rule1 ) > -1 ); assertTrue( drl.indexOf( ""calendars \""CAL1\"""", rule1 ) > -1 ); + assertTrue( drl.indexOf( ""date-effective \""01-Jan-2007\"""", + rule1 ) > -1 ); + assertTrue( drl.indexOf( ""date-expires \""31-Dec-2007\"""", + rule1 ) > -1 ); int rule2 = drl.indexOf( ""rule \""N2\"""" ); assertFalse( rule2 == -1 ); @@ -216,6 +220,10 @@ public void testAttributesXLS() { rule2 ) > -1 ); assertTrue( drl.indexOf( ""calendars \""CAL2\"""", rule2 ) > -1 ); + assertTrue( drl.indexOf( ""date-effective \""01-Jan-2012\"""", + rule2 ) > -1 ); + assertTrue( drl.indexOf( ""date-expires \""31-Dec-2015\"""", + rule2 ) > -1 ); } @Test diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java index cbfc6e9644a..6d7bf450be7 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java @@ -156,6 +156,26 @@ public void testChooseActionType() { type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals(Code.RULEFLOWGROUP, type.getCode()); + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""V"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEFFECTIVE, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""DATE-EFFECTIVE"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEFFECTIVE, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""Z"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEXPIRES, type.getCode()); + + actionTypeMap = new HashMap(); + ActionType.addNewActionType( actionTypeMap, ""DATE-EXPIRES"", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DATEEXPIRES, type.getCode()); + actionTypeMap = new HashMap(); ActionType.addNewActionType( actionTypeMap, ""@"", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); diff --git a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls index 3159e4ffeb6..1819888649a 100644 Binary files a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls and b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls differ diff --git a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java index b46e25c7c45..3232fb349be 100644 --- a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java +++ b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java @@ -105,6 +105,14 @@ public void setAutoFocus(final boolean value) { this._attr2value.put( ""auto-focus"", Boolean.toString( value ) ); } + public void setDateEffective(final String value) { + this._attr2value.put( ""date-effective"", asStringLiteral( value ) ); + } + + public void setDateExpires(final String value) { + this._attr2value.put( ""date-expires"", asStringLiteral( value ) ); + } + public String getAttribute( String name ){ return this._attr2value.get( name ).toString(); }" ec463a32ba825d678a230c7ab5f3eb2e1e0c2e42,spring-framework,added DataSourceFactory strategy; promoted- EmbeddedDatabaseConfigurer strategy to public API; added ability to add any- number of SQL scripts for db population--,a,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ConnectionProperties.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ConnectionProperties.java new file mode 100644 index 000000000000..b0276e7be041 --- /dev/null +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ConnectionProperties.java @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.jdbc.datasource.embedded; + +/** + * Allows DataSource connection properties to be configured in a DataSource implementation independent manner. + * @author Keith Donald + * @see DataSourceFactory + */ +public interface ConnectionProperties { + + /** + * Set the JDBC driver to use to connect to the database. + * @param driverClass the jdbc driver class + */ + void setDriverClass(Class driverClass); + + /** + * Sets the JDBC connection URL of the database. + * @param url the connection url + */ + void setUrl(String url); + + /** + * Sets the username to use to connect to the database. + * @param username the username + */ + void setUsername(String username); + + /** + * Sets the password to use to connect to the database. + * @param password the password + */ + void setPassword(String password); +} diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DataSourceFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DataSourceFactory.java new file mode 100644 index 000000000000..0313294a4f23 --- /dev/null +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DataSourceFactory.java @@ -0,0 +1,39 @@ +/* + * Copyright 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.jdbc.datasource.embedded; + +import javax.sql.DataSource; + +import org.springframework.jdbc.datasource.SimpleDriverDataSource; + +/** + * A factory for a kind of DataSource, such as a {@link SimpleDriverDataSource} or connection pool such as Apache DBCP or c3p0. + * Call {@link #getConnectionProperties()} to configure normalized DataSource properties before calling {@link #getDataSource()} to actually get the configured DataSource instance. + * @author Keith Donald + */ +public interface DataSourceFactory { + + /** + * Allows properties of the DataSource to be configured. + */ + ConnectionProperties getConnectionProperties(); + + /** + * Returns the DataSource with the connection properties applied. + */ + DataSource getDataSource(); + +} diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DatabasePopulator.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DatabasePopulator.java index 1b2c6bfbc992..a8929c7f5c80 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DatabasePopulator.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/DatabasePopulator.java @@ -20,7 +20,7 @@ /** * Strategy for populating a database with data. - * + * @author Keith Donald * @see ResourceDatabasePopulator */ public interface DatabasePopulator { diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabase.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabase.java index 057ef92ec7f6..075eca8d3eff 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabase.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabase.java @@ -21,11 +21,12 @@ * A handle to an EmbeddedDatabase instance. * Is a {@link DataSource}. * Adds a shutdown operation so the embedded database instance can be shutdown. + * @author Keith Donald */ public interface EmbeddedDatabase extends DataSource { /** * Shutdown this embedded database. */ - public void shutdown(); + void shutdown(); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.java index cb51166c87e6..2afd35d31565 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.java @@ -28,9 +28,6 @@ * EmbeddedDatabase db = builder.schema(""schema.sql"").testData(""test-data.sql"").build(); * db.shutdown(); * - * - * TODO - should we replace schema/testdata with more general 'script' method? - * * @author Keith Donald */ public class EmbeddedDatabaseBuilder { @@ -71,24 +68,12 @@ public EmbeddedDatabaseBuilder type(EmbeddedDatabaseType databaseType) { } /** - * Sets the location of the schema SQL to run to create the database structure. - * Defaults to classpath:schema.sql if not called. + * Adds a SQL script to execute to populate the database. * @param sqlResource the sql resource location * @return this, for fluent call chaining */ - public EmbeddedDatabaseBuilder schema(String sqlResource) { - databasePopulator.setSchemaLocation(resourceLoader.getResource(sqlResource)); - return this; - } - - /** - * Sets the location of the schema SQL to run to create the database structure. - * Defaults to classpath:test-data.sql if not called - * @param sqlResource the sql resource location - * @return this, for fluent call chaining - */ - public EmbeddedDatabaseBuilder testData(String sqlResource) { - databasePopulator.setTestDataLocation(resourceLoader.getResource(sqlResource)); + public EmbeddedDatabaseBuilder script(String sqlResource) { + databasePopulator.addScript(resourceLoader.getResource(sqlResource)); return this; } @@ -120,11 +105,11 @@ public Resource getResource(String location) { /** * Factory method that builds a default EmbeddedDatabase instance. - * The default is HSQL with a schema created from classpath:schema.sql and test-data loaded from classpatH:test-data.sql. + * The default is HSQL with a schema created from classpath:schema.sql and test-data loaded from classpath:test-data.sql. * @return an embedded database */ public static EmbeddedDatabase buildDefault() { - return new EmbeddedDatabaseBuilder().build(); + return new EmbeddedDatabaseBuilder().script(""schema.sql"").script(""test-data.sql"").build(); } private EmbeddedDatabaseBuilder(ResourceLoader loader) { diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurer.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurer.java index a96c753970e7..98e16b0b7219 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurer.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurer.java @@ -17,29 +17,24 @@ import javax.sql.DataSource; -import org.springframework.jdbc.datasource.SimpleDriverDataSource; - /** * Encapsulates the configuration required to create, connect to, and shutdown a specific type of embedded database such as HSQLdb or H2. - * Create a subclass for each database type we wish to support. - * - * TODO - introduce ConfigurableDataSource strategy for configuring connection properties? - * - * @see EmbeddedDatabaseConfigurerFactory + * Create a implementation for each database type we wish to support. + * @author Keith Donald */ -abstract class EmbeddedDatabaseConfigurer { +public interface EmbeddedDatabaseConfigurer { /** * Configure the properties required to create and connect to the embedded database instance. * @param dataSource the data source to configure * @param databaseName the name of the test database */ - public abstract void configureConnectionProperties(SimpleDriverDataSource dataSource, String databaseName); + void configureConnectionProperties(ConnectionProperties properties, String databaseName); /** * Shutdown the embedded database instance that backs dataSource. * @param dataSource the data source */ - public abstract void shutdown(DataSource dataSource); + void shutdown(DataSource dataSource); } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurerFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurerFactory.java index 57d51a94d4b2..fa618d1895f2 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurerFactory.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseConfigurerFactory.java @@ -15,9 +15,16 @@ */ package org.springframework.jdbc.datasource.embedded; +import org.springframework.util.Assert; + +/** + * Package private factory for mapping well-known embedded database types to database configurer strategies. + * @author Keith Donald + */ class EmbeddedDatabaseConfigurerFactory { public static EmbeddedDatabaseConfigurer getConfigurer(EmbeddedDatabaseType type) throws IllegalStateException { + Assert.notNull(type, ""The EmbeddedDatabaseType is required""); try { if (type == EmbeddedDatabaseType.HSQL) { return HsqlEmbeddedDatabaseConfigurer.getInstance(); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java index b52700178b78..608928954fd9 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java @@ -25,7 +25,6 @@ import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; @@ -36,10 +35,13 @@ * When the database is returned, callers are guaranteed that the database schema and test data will have already been loaded. * * Can be configured. - * Call {@link #setDatabaseName(String)} to change the name of the test database. - * Call {@link #setDatabaseType(EmbeddedDatabaseType)} to set the test database type. + * Call {@link #setDatabaseName(String)} to change the name of the database. + * Call {@link #setDatabaseType(EmbeddedDatabaseType)} to set the database type if you wish to use one of the supported types. + * Call {@link #setDatabaseConfigurer(EmbeddedDatabaseConfigurer)} to set a configuration strategy for your own embedded database type. * Call {@link #setDatabasePopulator(DatabasePopulator)} to change the algorithm used to populate the database. - * Call {@link #getDatabase()} to the {@link EmbeddedDatabase} instance. + * Call {@link #setDataSourceFactory(DataSourceFactory)} to change the type of DataSource used to connect to the database. + * Call {@link #getDatabase()} to get the {@link EmbeddedDatabase} instance. + * @author Keith Donald */ public class EmbeddedDatabaseFactory { @@ -47,19 +49,22 @@ public class EmbeddedDatabaseFactory { private String databaseName; - private EmbeddedDatabaseConfigurer dataSourceConfigurer; + private DataSourceFactory dataSourceFactory; + + private EmbeddedDatabaseConfigurer databaseConfigurer; private DatabasePopulator databasePopulator; private EmbeddedDatabase database; /** - * Creates a new EmbeddedDatabaseFactory that uses the default {@link ResourceDatabasePopulator}. + * Creates a default {@link EmbeddedDatabaseFactory}. + * Calling {@link #getDatabase()} will create a embedded HSQL database of name 'testdb'. */ public EmbeddedDatabaseFactory() { setDatabaseName(""testdb""); setDatabaseType(EmbeddedDatabaseType.HSQL); - setDatabasePopulator(new ResourceDatabasePopulator()); + setDataSourceFactory(new SimpleDriverDataSourceFactory()); } /** @@ -73,25 +78,44 @@ public void setDatabaseName(String name) { } /** - * Sets the type of test database to use. + * Sets the type of embedded database to use. + * Call this when you wish to configure one of the pre-supported types. * Defaults to HSQL. * @param type the test database type */ public void setDatabaseType(EmbeddedDatabaseType type) { - Assert.notNull(type, ""The TestDatabaseType is required""); - dataSourceConfigurer = EmbeddedDatabaseConfigurerFactory.getConfigurer(type); + setDatabaseConfigurer(EmbeddedDatabaseConfigurerFactory.getConfigurer(type)); } /** - * Sets the helper that will be invoked to populate the test database with data. - * Defaults a {@link ResourceDatabasePopulator}. - * @param populator + * Sets the strategy that will be used to configure the embedded database instance. + * Call this when you wish to use an embedded database type not already supported. + * @param configurer the embedded database configurer + */ + public void setDatabaseConfigurer(EmbeddedDatabaseConfigurer configurer) { + this.databaseConfigurer = configurer; + } + + /** + * Sets the strategy that will be used to populate the embedded database. + * Defaults to null. + * @param populator the database populator */ public void setDatabasePopulator(DatabasePopulator populator) { Assert.notNull(populator, ""The TestDatabasePopulator is required""); databasePopulator = populator; } - + + /** + * Sets the factory to use to create the DataSource instance that connects to the embedded database. + * Defaults to {@link SimpleDriverDataSourceFactory}. + * @param dataSourceFactory the data source factory + */ + public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { + Assert.notNull(dataSourceFactory, ""The DataSourceFactory is required""); + this.dataSourceFactory = dataSourceFactory; + } + // other public methods /** @@ -106,9 +130,8 @@ public EmbeddedDatabase getDatabase() { // internal helper methods - // encapsulates the steps involved in initializing the data source: creating it, and populating it private void initDatabase() { - // create the in-memory database source first + // create the embedded database source first database = new EmbeddedDataSourceProxy(createDataSource()); if (logger.isInfoEnabled()) { logger.info(""Created embedded database '"" + databaseName + ""'""); @@ -120,9 +143,8 @@ private void initDatabase() { } private DataSource createDataSource() { - SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); - dataSourceConfigurer.configureConnectionProperties(dataSource, databaseName); - return dataSource; + databaseConfigurer.configureConnectionProperties(dataSourceFactory.getConnectionProperties(), databaseName); + return dataSourceFactory.getDataSource(); } private void populateDatabase() { @@ -183,7 +205,7 @@ public void shutdown() { private void shutdownDatabase() { if (database != null) { - dataSourceConfigurer.shutdown(database); + databaseConfigurer.shutdown(database); database = null; } } diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType.java index 30085eb3ebf2..93c12798fa94 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseType.java @@ -18,6 +18,7 @@ /** * A supported embedded database type. * @author Keith Donald + * @see HsqlEmbeddedDatabaseConfigurer */ public enum EmbeddedDatabaseType { HSQL; diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java index b5ee37ef39a0..50be662dc758 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java @@ -18,10 +18,9 @@ import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.SimpleDriverDataSource; import org.springframework.util.ClassUtils; -class HsqlEmbeddedDatabaseConfigurer extends EmbeddedDatabaseConfigurer { +public class HsqlEmbeddedDatabaseConfigurer implements EmbeddedDatabaseConfigurer { private static HsqlEmbeddedDatabaseConfigurer INSTANCE; @@ -33,11 +32,11 @@ public static synchronized HsqlEmbeddedDatabaseConfigurer getInstance() throws C return INSTANCE; } - public void configureConnectionProperties(SimpleDriverDataSource dataSource, String databaseName) { - dataSource.setDriverClass(org.hsqldb.jdbcDriver.class); - dataSource.setUrl(""jdbc:hsqldb:mem:"" + databaseName); - dataSource.setUsername(""sa""); - dataSource.setPassword(""""); + public void configureConnectionProperties(ConnectionProperties properties, String databaseName) { + properties.setDriverClass(org.hsqldb.jdbcDriver.class); + properties.setUrl(""jdbc:hsqldb:mem:"" + databaseName); + properties.setUsername(""sa""); + properties.setPassword(""""); } public void shutdown(DataSource dataSource) { diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.java index aee842d81827..7ed5468b2c87 100644 --- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.java +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.java @@ -17,12 +17,12 @@ import java.io.IOException; import java.io.LineNumberReader; +import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; @@ -43,26 +43,16 @@ public class ResourceDatabasePopulator implements DatabasePopulator { private static final Log logger = LogFactory.getLog(ResourceDatabasePopulator.class); - private Resource schemaLocation = new ClassPathResource(""schema.sql""); - - private Resource testDataLocation = new ClassPathResource(""test-data.sql""); - private String sqlScriptEncoding; - - /** - * Sets the location of .sql file containing the database schema to create. - * @param schemaLocation the path to the db schema definition - */ - public void setSchemaLocation(Resource schemaLocation) { - this.schemaLocation = schemaLocation; - } + private List scripts = new ArrayList(); + /** - * Sets the location of the .sql file containing the test data to populate. - * @param testDataLocation the path to the db test data file + * Add a script to execute to populate the database. + * @param script the path to a SQL script */ - public void setTestDataLocation(Resource testDataLocation) { - this.testDataLocation = testDataLocation; + public void addScript(Resource script) { + scripts.add(script); } /** @@ -73,18 +63,9 @@ public void setSqlScriptEncoding(String sqlScriptEncoding) { } public void populate(JdbcTemplate template) { - createDatabaseSchema(template); - insertTestData(template); - } - - // create the application's database schema (tables, indexes, etc.) - private void createDatabaseSchema(JdbcTemplate template) { - executeSqlScript(template, new EncodedResource(schemaLocation, sqlScriptEncoding), false); - } - - // populate the tables with test data - private void insertTestData(JdbcTemplate template) { - executeSqlScript(template, new EncodedResource(testDataLocation, sqlScriptEncoding), false); + for (Resource script : scripts) { + executeSqlScript(template, new EncodedResource(script, sqlScriptEncoding), false); + } } // From SimpleJdbcTestUtils - TODO address duplication @@ -94,16 +75,13 @@ private void insertTestData(JdbcTemplate template) { *

      The script will normally be loaded by classpath. There should be one statement * per line. Any semicolons will be removed. Do not use this method to execute * DDL if you expect rollback. - * @param simpleJdbcTemplate the SimpleJdbcTemplate with which to perform JDBC operations + * @param template the SimpleJdbcTemplate with which to perform JDBC operations * @param resource the resource (potentially associated with a specific encoding) * to load the SQL script from. * @param continueOnError whether or not to continue without throwing an * exception in the event of an error. - * @throws DataAccessException if there is an error executing a statement - * and continueOnError was false */ - static void executeSqlScript(JdbcTemplate jdbcTemplate, - EncodedResource resource, boolean continueOnError) throws DataAccessException { + static void executeSqlScript(JdbcTemplate template, EncodedResource resource, boolean continueOnError) { if (logger.isInfoEnabled()) { logger.info(""Executing SQL script from "" + resource); } @@ -119,7 +97,7 @@ static void executeSqlScript(JdbcTemplate jdbcTemplate, splitSqlScript(script, delimiter, statements); for (String statement : statements) { try { - int rowsAffected = jdbcTemplate.update(statement); + int rowsAffected = template.update(statement); if (logger.isDebugEnabled()) { logger.debug(rowsAffected + "" rows affected by SQL: "" + statement); } @@ -145,7 +123,7 @@ static void executeSqlScript(JdbcTemplate jdbcTemplate, } } - // From JdbcTestUtils - TODO address duplication + // From JdbcTestUtils - TODO address duplication - these do not seem as useful as the one above /** * Read a script from the LineNumberReader and build a String containing the lines. @@ -153,7 +131,7 @@ static void executeSqlScript(JdbcTemplate jdbcTemplate, * @return String containing the script lines * @throws IOException */ - static String readScript(LineNumberReader lineNumberReader) throws IOException { + private static String readScript(LineNumberReader lineNumberReader) throws IOException { String currentStatement = lineNumberReader.readLine(); StringBuilder scriptBuilder = new StringBuilder(); while (currentStatement != null) { @@ -173,7 +151,7 @@ static String readScript(LineNumberReader lineNumberReader) throws IOException { * @param script the SQL script * @param delim charecter delimiting each statement - typically a ';' character */ - static boolean containsSqlScriptDelimiters(String script, char delim) { + private static boolean containsSqlScriptDelimiters(String script, char delim) { boolean inLiteral = false; char[] content = script.toCharArray(); for (int i = 0; i < script.length(); i++) { @@ -194,7 +172,7 @@ static boolean containsSqlScriptDelimiters(String script, char delim) { * @param delim charecter delimiting each statement - typically a ';' character * @param statements the List that will contain the individual statements */ - static void splitSqlScript(String script, char delim, List statements) { + private static void splitSqlScript(String script, char delim, List statements) { StringBuilder sb = new StringBuilder(); boolean inLiteral = false; char[] content = script.toCharArray(); diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/SimpleDriverDataSourceFactory.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/SimpleDriverDataSourceFactory.java new file mode 100644 index 000000000000..3b4ca73ebe06 --- /dev/null +++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/SimpleDriverDataSourceFactory.java @@ -0,0 +1,38 @@ +package org.springframework.jdbc.datasource.embedded; + +import javax.sql.DataSource; + +import org.springframework.jdbc.datasource.SimpleDriverDataSource; + +public class SimpleDriverDataSourceFactory implements DataSourceFactory { + + private SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); + + public ConnectionProperties getConnectionProperties() { + return new ConnectionProperties() { + + public void setDriverClass(Class driverClass) { + dataSource.setDriverClass(driverClass); + } + + public void setUrl(String url) { + dataSource.setUrl(url); + } + + public void setUsername(String username) { + dataSource.setUsername(username); + } + + public void setPassword(String password) { + dataSource.setPassword(password); + } + + }; + } + + public DataSource getDataSource() { + return dataSource; + } + + +} diff --git a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java index e292e46d3c7f..94cea3cd5d53 100644 --- a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java +++ b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilderTests.java @@ -22,31 +22,20 @@ public void testBuildDefaults() { @Test public void testBuild() { EmbeddedDatabaseBuilder builder = EmbeddedDatabaseBuilder.relativeTo(getClass()); - EmbeddedDatabase db = builder.schema(""db-schema.sql"").testData(""db-test-data.sql"").build(); + EmbeddedDatabase db = builder.script(""db-schema.sql"").script(""db-test-data.sql"").build(); JdbcTemplate template = new JdbcTemplate(db); assertEquals(""Keith"", template.queryForObject(""select NAME from T_TEST"", String.class)); db.shutdown(); } @Test - public void testBuildNoSuchSchema() { + public void testBuildNoSuchScript() { try { - new EmbeddedDatabaseBuilder().schema(""bogus.sql"").build(); + new EmbeddedDatabaseBuilder().script(""bogus.sql"").build(); fail(""Should have failed""); } catch (DataAccessException e) { } } - - @Test - public void testBuildNoSuchTestdata() { - try { - new EmbeddedDatabaseBuilder().testData(""bogus.sql"").build(); - fail(""Should have failed""); - } catch (DataAccessException e) { - - } - } - -} +} \ No newline at end of file" 455ca1d72361e66afc01cc39d6d79155a2551e2d,camel,CAMEL-2206: Added new Sampler EIP. Thanks to- Stephen Gargan for the contribution.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@883614 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/builder/xml/TimeUnitAdapter.java b/camel-core/src/main/java/org/apache/camel/builder/xml/TimeUnitAdapter.java new file mode 100644 index 0000000000000..a6e6ac8a564b6 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/builder/xml/TimeUnitAdapter.java @@ -0,0 +1,47 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.builder.xml; + +import java.util.concurrent.TimeUnit; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +/** + * TimeUnitAdapter is a simple adapter to convert between Strings + * and instances of the {@link TimeUnit} enumeration + */ +public class TimeUnitAdapter extends XmlAdapter { + + @Override + public String marshal(TimeUnit v) throws Exception { + String result = null; + if (v != null) { + result = v.toString(); + } + return result; + } + + @Override + public TimeUnit unmarshal(String v) throws Exception { + TimeUnit result = null; + if (v != null) { + result = TimeUnit.valueOf(v.toUpperCase()); + } + return result; + } + +} diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java index 1714724f58a7b..ff529fa529d04 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java @@ -24,6 +24,7 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.concurrent.TimeUnit; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -1136,6 +1137,39 @@ public Type routingSlip(String header) { return (Type) this; } + /** + * Sampling Throttler + * Creates a sampling throttler allowing you to extract a sample of + * exchanges from the traffic on a route. It is configured with a sampling + * period, during which only a single exchange is allowed to pass through. + * All other exchanges will be stopped. + *

      + * Default period is one second. + * + * @return the builder + */ + public SamplingDefinition sample() { + return sample(1, TimeUnit.SECONDS); + } + + /** + * Sampling Throttler + * Creates a sampling throttler allowing you to extract a sample of exchanges + * from the traffic through a route. It is configured with a sampling period + * during which only a single exchange is allowed to pass through. + * All other exchanges will be stopped. + * + * @param samplePeriod this is the sample interval, only one exchange is + * allowed through in this interval + * @param unit this is the units for the samplePeriod e.g. Seconds + * @return the builder + */ + public SamplingDefinition sample(long samplePeriod, TimeUnit unit) { + SamplingDefinition answer = new SamplingDefinition(samplePeriod, unit); + addOutput(answer); + return answer; + } + /** * Splitter EIP: * Creates a splitter allowing you split a message into a number of pieces and process them individually. diff --git a/camel-core/src/main/java/org/apache/camel/model/SamplingDefinition.java b/camel-core/src/main/java/org/apache/camel/model/SamplingDefinition.java new file mode 100644 index 0000000000000..0334aad4ed7dc --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/model/SamplingDefinition.java @@ -0,0 +1,138 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElementRef; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.apache.camel.Processor; +import org.apache.camel.builder.xml.TimeUnitAdapter; +import org.apache.camel.processor.SamplingThrottler; +import org.apache.camel.spi.RouteContext; + +/** + * Represents an XML <sample/> element + * + * @version $Revision$ + */ +@XmlRootElement(name = ""sample"") +@XmlAccessorType(XmlAccessType.FIELD) +@SuppressWarnings(""unchecked"") +public class SamplingDefinition extends ProcessorDefinition { + + // use Long to let it be optional in JAXB so when using XML the default is 1 second + + @XmlAttribute() + private Long samplePeriod = 1L; + + @XmlAttribute() + @XmlJavaTypeAdapter(TimeUnitAdapter.class) + private TimeUnit units = TimeUnit.SECONDS; + + @XmlElementRef + private List outputs = new ArrayList(); + + public SamplingDefinition() { + } + + public SamplingDefinition(long samplePeriod, TimeUnit units) { + this.samplePeriod = samplePeriod; + this.units = units; + } + + @Override + public String toString() { + return ""Sample[1 Exchange per "" + samplePeriod + "" "" + units.toString().toLowerCase() + "" -> "" + getOutputs() + ""]""; + } + + @Override + public String getShortName() { + return ""sample""; + } + + @Override + public String getLabel() { + return ""sample[1 Exchange per "" + samplePeriod + "" "" + units.toString().toLowerCase() + ""]""; + } + + @Override + public Processor createProcessor(RouteContext routeContext) throws Exception { + Processor childProcessor = routeContext.createProcessor(this); + return new SamplingThrottler(childProcessor, samplePeriod, units); + } + + // Fluent API + // ------------------------------------------------------------------------- + + /** + * Sets the sample period during which only a single {@link org.apache.camel.Exchange} will pass through. + * + * @param samplePeriod the period + * @return the builder + */ + public SamplingDefinition samplePeriod(long samplePeriod) { + setSamplePeriod(samplePeriod); + return this; + } + + /** + * Sets the time units for the sample period, defaulting to seconds. + * + * @param units the time unit of the sample period. + * @return the builder + */ + public SamplingDefinition timeUnits(TimeUnit units) { + setUnits(units); + return this; + } + + // Properties + // ------------------------------------------------------------------------- + + public List getOutputs() { + return outputs; + } + + public void setOutputs(List outputs) { + this.outputs = outputs; + } + + public long getSamplePeriod() { + return samplePeriod; + } + + public void setSamplePeriod(long samplePeriod) { + this.samplePeriod = samplePeriod; + } + + public void setUnits(String units) { + this.units = TimeUnit.valueOf(units); + } + + public void setUnits(TimeUnit units) { + this.units = units; + } + +} diff --git a/camel-core/src/main/java/org/apache/camel/processor/SamplingThrottler.java b/camel-core/src/main/java/org/apache/camel/processor/SamplingThrottler.java new file mode 100644 index 0000000000000..c3b15545e4754 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/processor/SamplingThrottler.java @@ -0,0 +1,129 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.processor; + +import static java.lang.String.format; + +import java.util.concurrent.TimeUnit; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * A SamplingThrottler is a special kind of throttler. It also + * limits the number of exchanges sent to a downstream endpoint. It differs from + * a normal throttler in that it will not queue exchanges above the threshold + * for a given period. Instead these exchanges will be stopped, precluding them + * from being processed at all by downstream consumers. + *

      + * This kind of throttling can be useful for taking a sample from + * an exchange stream, rough consolidation of noisy and bursty exchange traffic + * or where queuing of throttled exchanges is undesirable. + * + * @version $Revision$ + */ +public class SamplingThrottler extends DelegateProcessor { + protected final transient Log log = LogFactory.getLog(getClass()); + private long samplePeriod; + private long periodInNanos; + private TimeUnit units; + private long timeOfLastExchange; + private StopProcessor stopper = new StopProcessor(); + private Object calculationLock = new Object(); + private SampleStats sampled = new SampleStats(); + + public SamplingThrottler(Processor processor, long samplePeriod, TimeUnit units) { + super(processor); + + if (samplePeriod <= 0) { + throw new IllegalArgumentException(""A positive value is required for the sampling period""); + } + if (units == null) { + throw new IllegalArgumentException(""A invalid null value was supplied for the units of the sampling period""); + } + this.samplePeriod = samplePeriod; + this.units = units; + periodInNanos = units.toNanos(samplePeriod); + } + + @Override + public String toString() { + return ""SamplingThrottler[1 exchange per: "" + samplePeriod + "" "" + units.toString().toLowerCase() + "" -> "" + getProcessor() + ""]""; + } + + public String getTraceLabel() { + return ""samplingThrottler[1 exchange per: "" + samplePeriod + "" "" + units.toString().toLowerCase() + ""]""; + } + + public void process(Exchange exchange) throws Exception { + boolean doSend = false; + + synchronized (calculationLock) { + long now = System.nanoTime(); + if (now >= timeOfLastExchange + periodInNanos) { + doSend = true; + if (log.isTraceEnabled()) { + log.trace(sampled.sample()); + } + timeOfLastExchange = now; + } else { + if (log.isTraceEnabled()) { + log.trace(sampled.drop()); + } + } + } + + if (doSend) { + super.process(exchange); + } else { + stopper.process(exchange); + } + } + + private static class SampleStats { + private long droppedThisPeriod; + private long totalDropped; + private long totalSampled; + private long totalThisPeriod; + + String drop() { + droppedThisPeriod++; + totalThisPeriod++; + totalDropped++; + return getDroppedLog(); + } + + String sample() { + totalThisPeriod = 1; // a new period, reset to 1 + totalSampled++; + droppedThisPeriod = 0; + return getSampledLog(); + } + + String getSampledLog() { + return format(""Sampled %d of %d total exchanges"", totalSampled, totalSampled + totalDropped); + } + + String getDroppedLog() { + return format(""Dropped %d of %d exchanges in this period, totalling %d dropped of %d exchanges overall."", + droppedThisPeriod, totalThisPeriod, totalDropped, totalSampled + totalDropped); + } + } + +} diff --git a/camel-core/src/main/resources/org/apache/camel/model/jaxb.index b/camel-core/src/main/resources/org/apache/camel/model/jaxb.index index 8a41eac1a9302..61be76a4fbbc0 100644 --- a/camel-core/src/main/resources/org/apache/camel/model/jaxb.index +++ b/camel-core/src/main/resources/org/apache/camel/model/jaxb.index @@ -58,6 +58,7 @@ RouteBuilderDefinition RouteDefinition RoutesDefinition RoutingSlipDefinition +SamplingDefinition SetBodyDefinition SetExchangePatternDefinition SetHeaderDefinition diff --git a/camel-core/src/test/java/org/apache/camel/processor/SamplingThrottlerTest.java b/camel-core/src/test/java/org/apache/camel/processor/SamplingThrottlerTest.java new file mode 100644 index 0000000000000..0ce492e2e0f0e --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/processor/SamplingThrottlerTest.java @@ -0,0 +1,123 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.processor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.apache.camel.ContextTestSupport; +import org.apache.camel.Exchange; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.direct.DirectEndpoint; +import org.apache.camel.component.mock.MockEndpoint; + +/** + * @version $Revision$ + */ +public class SamplingThrottlerTest extends ContextTestSupport { + + public void testSamplingFromExchangeStream() throws Exception { + MockEndpoint mock = getMockEndpoint(""mock:result""); + mock.expectedMessageCount(2); + mock.setResultWaitTime(3000); + + List sentExchanges = new ArrayList(); + sendExchangesThroughDroppingThrottler(sentExchanges, 15); + + mock.assertIsSatisfied(); + validateDroppedExchanges(sentExchanges, 2); + } + + public void testBurstySampling() throws Exception { + MockEndpoint mock = getMockEndpoint(""mock:result""); + mock.expectedMessageCount(2); + mock.setResultWaitTime(3000); + + List sentExchanges = new ArrayList(); + + // send a burst of 5 exchanges, expecting only one to get through + sendExchangesThroughDroppingThrottler(sentExchanges, 5); + // sleep through a complete period + Thread.sleep(1100); + // send another 5 now + sendExchangesThroughDroppingThrottler(sentExchanges, 5); + + mock.assertIsSatisfied(); + validateDroppedExchanges(sentExchanges, 2); + } + + public void testSendLotsOfMessagesSimultaneouslyButOnly3GetThrough() throws Exception { + MockEndpoint mock = getMockEndpoint(""mock:result""); + mock.expectedMessageCount(3); + mock.setResultWaitTime(4000); + + final List sentExchanges = Collections.synchronizedList(new ArrayList()); + ExecutorService executor = Executors.newFixedThreadPool(5); + for (int i = 0; i < 5; i++) { + executor.execute(new Runnable() { + public void run() { + try { + sendExchangesThroughDroppingThrottler(sentExchanges, 35); + } catch (InterruptedException e) {} + } + }); + } + + mock.assertIsSatisfied(); + } + + private void sendExchangesThroughDroppingThrottler(List sentExchanges, int messages) throws InterruptedException { + DirectEndpoint targetEndpoint = resolveMandatoryEndpoint(""direct:sample"", DirectEndpoint.class); + for (int i = 0; i < messages; i++) { + Exchange e = targetEndpoint.createExchange(); + e.getIn().setBody("""" + i + """"); + template.send(targetEndpoint, e); + sentExchanges.add(e); + Thread.sleep(100); + } + } + + private void validateDroppedExchanges(List sentExchanges, int expectedNotDroppedCount) { + int notDropped = 0; + for (Exchange e : sentExchanges) { + Boolean stopped = e.getProperty(Exchange.ROUTE_STOP, Boolean.class); + if (stopped == null) { + notDropped++; + } + } + assertEquals(expectedNotDroppedCount, notDropped); + } + + + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + public void configure() { + // START SNIPPET: e1 + from(""direct:sample"").sample().to(""mock:result""); + + from(""direct:sample-configured"").sample(1, TimeUnit.SECONDS).to(""mock:result""); + + from(""direct:sample-configured-via-dsl"").sample().samplePeriod(1).timeUnits(TimeUnit.SECONDS).to(""mock:result""); + // END SNIPPET: e1 + } + }; + } +} diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerTest.java new file mode 100644 index 0000000000000..98b208c8e46f0 --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerTest.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring.processor; + +import org.apache.camel.CamelContext; +import org.apache.camel.processor.SamplingThrottlerTest; + +import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext; + +public class SpringSamplingThrottlerTest extends SamplingThrottlerTest { + + protected CamelContext createCamelContext() throws Exception { + return createSpringCamelContext(this, ""org/apache/camel/spring/processor/samplingThrottler.xml""); + } + +} diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerWithDefaultTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerWithDefaultTest.java new file mode 100644 index 0000000000000..72dbb93aef8b5 --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringSamplingThrottlerWithDefaultTest.java @@ -0,0 +1,30 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring.processor; + +import org.apache.camel.CamelContext; +import org.apache.camel.processor.SamplingThrottlerTest; + +import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext; + +public class SpringSamplingThrottlerWithDefaultTest extends SamplingThrottlerTest { + + protected CamelContext createCamelContext() throws Exception { + return createSpringCamelContext(this, ""org/apache/camel/spring/processor/samplingThrottler.xml""); + } + +} \ No newline at end of file diff --git a/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottler.xml b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottler.xml new file mode 100644 index 0000000000000..6e8ca803ae8a8 --- /dev/null +++ b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottler.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + diff --git a/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottlerWithDefault.xml b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottlerWithDefault.xml new file mode 100644 index 0000000000000..1a0ec51ec6902 --- /dev/null +++ b/components/camel-spring/src/test/resources/org/apache/camel/spring/processor/samplingThrottlerWithDefault.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + +" 267016758de3143e80244b266a8b27978b115320,elasticsearch,"improve handling of memory caching with file- system, only force compound file when really needed (when an extension that- exists within the compound file is part of the memory cached extensions)--",p,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/FsStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/FsStore.java index 5a76267a27cce..35ef502f0141b 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/FsStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/FsStore.java @@ -22,6 +22,7 @@ import org.apache.lucene.store.*; import org.elasticsearch.cache.memory.ByteBufferCache; import org.elasticsearch.common.collect.ImmutableSet; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.io.FileSystemUtils; import org.elasticsearch.common.lucene.store.SwitchDirectory; import org.elasticsearch.common.settings.Settings; @@ -73,7 +74,7 @@ protected LockFactory buildLockFactory() throws IOException { return lockFactory; } - protected SwitchDirectory buildSwitchDirectoryIfNeeded(Directory fsDirectory, ByteBufferCache byteBufferCache) { + protected Tuple buildSwitchDirectoryIfNeeded(Directory fsDirectory, ByteBufferCache byteBufferCache) { boolean cache = componentSettings.getAsBoolean(""memory.enabled"", false); if (!cache) { return null; @@ -81,6 +82,17 @@ protected SwitchDirectory buildSwitchDirectoryIfNeeded(Directory fsDirectory, By Directory memDir = new ByteBufferDirectory(byteBufferCache); // see http://lucene.apache.org/java/3_0_1/fileformats.html String[] primaryExtensions = componentSettings.getAsArray(""memory.extensions"", new String[]{"""", ""del"", ""gen""}); - return new SwitchDirectory(ImmutableSet.copyOf(primaryExtensions), memDir, fsDirectory, true); + if (primaryExtensions == null || primaryExtensions.length == 0) { + return null; + } + Boolean forceUseCompound = null; + for (String extension : primaryExtensions) { + if (!("""".equals(extension) || ""del"".equals(extension) || ""gen"".equals(extension))) { + // caching internal CFS extension, don't use compound file extension + forceUseCompound = false; + } + } + + return new Tuple(new SwitchDirectory(ImmutableSet.copyOf(primaryExtensions), memDir, fsDirectory, true), forceUseCompound); } } diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/MmapFsStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/MmapFsStore.java index b15e4d762f6b3..c0a2f78f17812 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/MmapFsStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/MmapFsStore.java @@ -24,6 +24,7 @@ import org.apache.lucene.store.LockFactory; import org.apache.lucene.store.MMapDirectory; import org.elasticsearch.cache.memory.ByteBufferCache; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.store.SwitchDirectory; import org.elasticsearch.common.settings.Settings; @@ -52,16 +53,21 @@ public class MmapFsStore extends FsStore { location.mkdirs(); this.fsDirectory = new MMapDirectory(location, lockFactory); - SwitchDirectory switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); + boolean suggestUseCompoundFile; + Tuple switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); if (switchDirectory != null) { - suggestUseCompoundFile = false; - logger.debug(""Using [mmap_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.primaryExtensions()); - directory = wrapDirectory(switchDirectory); + suggestUseCompoundFile = true; + if (switchDirectory.v2() != null) { + suggestUseCompoundFile = switchDirectory.v2(); + } + logger.debug(""Using [mmap_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.v1().primaryExtensions()); + directory = wrapDirectory(switchDirectory.v1()); } else { suggestUseCompoundFile = true; directory = wrapDirectory(fsDirectory); logger.debug(""Using [mmap_fs] Store with path [{}]"", fsDirectory.getFile()); } + this.suggestUseCompoundFile = suggestUseCompoundFile; } @Override public FSDirectory fsDirectory() { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/NioFsStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/NioFsStore.java index 8e30bdc105905..49de22d296422 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/NioFsStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/NioFsStore.java @@ -24,6 +24,7 @@ import org.apache.lucene.store.LockFactory; import org.apache.lucene.store.NIOFSDirectory; import org.elasticsearch.cache.memory.ByteBufferCache; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.store.SwitchDirectory; import org.elasticsearch.common.settings.Settings; @@ -52,16 +53,21 @@ public class NioFsStore extends FsStore { location.mkdirs(); this.fsDirectory = new NIOFSDirectory(location, lockFactory); - SwitchDirectory switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); + boolean suggestUseCompoundFile; + Tuple switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); if (switchDirectory != null) { - suggestUseCompoundFile = false; - logger.debug(""Using [nio_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.primaryExtensions()); - directory = wrapDirectory(switchDirectory); + suggestUseCompoundFile = true; + if (switchDirectory.v2() != null) { + suggestUseCompoundFile = switchDirectory.v2(); + } + logger.debug(""Using [nio_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.v1().primaryExtensions()); + directory = wrapDirectory(switchDirectory.v1()); } else { suggestUseCompoundFile = true; directory = wrapDirectory(fsDirectory); logger.debug(""Using [nio_fs] Store with path [{}]"", fsDirectory.getFile()); } + this.suggestUseCompoundFile = suggestUseCompoundFile; } @Override public FSDirectory fsDirectory() { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/SimpleFsStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/SimpleFsStore.java index f7aa18e17f075..68f0d5c591404 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/SimpleFsStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/fs/SimpleFsStore.java @@ -24,6 +24,7 @@ import org.apache.lucene.store.LockFactory; import org.apache.lucene.store.SimpleFSDirectory; import org.elasticsearch.cache.memory.ByteBufferCache; +import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.store.SwitchDirectory; import org.elasticsearch.common.settings.Settings; @@ -52,16 +53,21 @@ public class SimpleFsStore extends FsStore { location.mkdirs(); this.fsDirectory = new SimpleFSDirectory(location, lockFactory); - SwitchDirectory switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); + boolean suggestUseCompoundFile; + Tuple switchDirectory = buildSwitchDirectoryIfNeeded(fsDirectory, byteBufferCache); if (switchDirectory != null) { - suggestUseCompoundFile = false; - logger.debug(""Using [simple_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.primaryExtensions()); - directory = wrapDirectory(switchDirectory); + suggestUseCompoundFile = true; + if (switchDirectory.v2() != null) { + suggestUseCompoundFile = switchDirectory.v2(); + } + logger.debug(""Using [simple_fs] Store with path [{}], cache [true] with extensions [{}]"", fsDirectory.getFile(), switchDirectory.v1().primaryExtensions()); + directory = wrapDirectory(switchDirectory.v1()); } else { suggestUseCompoundFile = true; directory = wrapDirectory(fsDirectory); logger.debug(""Using [simple_fs] Store with path [{}]"", fsDirectory.getFile()); } + this.suggestUseCompoundFile = suggestUseCompoundFile; } @Override public FSDirectory fsDirectory() { diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java index 807a6c5ba1e7d..4c798c743b8a4 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/store/support/AbstractStore.java @@ -167,7 +167,11 @@ class StoreDirectory extends Directory implements ForceSyncDirectory { synchronized (mutex) { MapBuilder builder = MapBuilder.newMapBuilder(); for (String file : delegate.listAll()) { - builder.put(file, new StoreFileMetaData(file, delegate.fileLength(file), delegate.fileModified(file), preComputedMd5(file))); + try { + builder.put(file, new StoreFileMetaData(file, delegate.fileLength(file), delegate.fileModified(file), preComputedMd5(file))); + } catch (FileNotFoundException e) { + // ignore + } } filesMetadata = builder.immutableMap(); files = filesMetadata.keySet().toArray(new String[filesMetadata.size()]);" 661fd64481a0db75c501b782a60e89f7e348a9e6,orientdb,Fixed issue -255 about hooks: wasn't called- during TX - added new test cases - check of recursive call for the same- record in hook.--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java index 27fc70adca5..93733836765 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseComplex.java @@ -21,6 +21,7 @@ import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.db.object.ODatabaseObject; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; +import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.dictionary.ODictionary; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; @@ -276,5 +277,5 @@ public interface ODatabaseComplex extends ODatabase, OUserObje * POJO for {@link ODatabaseObject} implementations. * @return True if the input record is changed, otherwise false */ - public boolean callbackHooks(TYPE iType, Object iObject); + public boolean callbackHooks(TYPE iType, OIdentifiable iObject); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java index 7dd62b2edb0..eba5cfcf05d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabasePojoAbstract.java @@ -33,6 +33,7 @@ import com.orientechnologies.orient.core.db.object.OLazyObjectSet; import com.orientechnologies.orient.core.db.object.OObjectNotDetachedException; import com.orientechnologies.orient.core.db.object.OObjectNotManagedException; +import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; @@ -243,7 +244,7 @@ public > DBTYPE registerHook(final ORecordHoo return (DBTYPE) this; } - public boolean callbackHooks(final TYPE iType, final Object iObject) { + public boolean callbackHooks(final TYPE iType, final OIdentifiable iObject) { return underlying.callbackHooks(iType, iObject); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java index b80187412be..00d10e2e440 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseRecordWrapperAbstract.java @@ -20,6 +20,7 @@ import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; +import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.dictionary.ODictionary; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; @@ -189,7 +190,7 @@ public > DBTYPE registerHook(final ORecordHoo return (DBTYPE) this; } - public boolean callbackHooks(final TYPE iType, final Object iObject) { + public boolean callbackHooks(final TYPE iType, final OIdentifiable iObject) { return underlying.callbackHooks(iType, iObject); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java index 952727e790d..4599bb54ec7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ODatabaseRecordAbstract.java @@ -33,6 +33,7 @@ import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.exception.ODatabaseException; import com.orientechnologies.orient.core.exception.OSecurityAccessException; +import com.orientechnologies.orient.core.hook.OHookThreadLocal; import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; import com.orientechnologies.orient.core.id.ORID; @@ -108,7 +109,7 @@ public DB open(final String iUserName, final String iUser registerHook(new OPropertyIndexManager()); if (getStorage() instanceof OStorageEmbedded) { - + if (!user.checkPassword(iUserPassword)) { // WAIT A BIT TO AVOID BRUTE FORCE Thread.sleep(200); @@ -139,10 +140,10 @@ public DB create() { dictionary = (ODictionaryInternal>) getStorage().createDictionary(this); dictionary.create(); - //if (getStorage() instanceof OStorageEmbedded) { - registerHook(new OUserTrigger()); - registerHook(new OPropertyIndexManager()); - //} + // if (getStorage() instanceof OStorageEmbedded) { + registerHook(new OUserTrigger()); + registerHook(new OPropertyIndexManager()); + // } } catch (Exception e) { throw new ODatabaseException(""Can't create database"", e); @@ -606,13 +607,20 @@ public Set getHooks() { * Record received in the callback * @return True if the input record is changed, otherwise false */ - public boolean callbackHooks(final TYPE iType, final Object iRecord) { - boolean recordChanged = false; - for (ORecordHook hook : hooks) - if (hook.onTrigger(iType, (ORecord) iRecord)) - recordChanged = true; + public boolean callbackHooks(final TYPE iType, final OIdentifiable iRecord) { + if (!OHookThreadLocal.INSTANCE.push(iRecord)) + return false; - return recordChanged; + try { + boolean recordChanged = false; + for (ORecordHook hook : hooks) + if (hook.onTrigger(iType, (ORecord) iRecord)) + recordChanged = true; + return recordChanged; + + } finally { + OHookThreadLocal.INSTANCE.pop(iRecord); + } } protected ORecordSerializer resolveFormat(final Object iObject) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java index 1baf31ea7b6..09bcdd2a38a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java @@ -139,4 +139,9 @@ public void clear() { public byte getRecordType() { return delegate.getRecordType(); } + + @Override + public String toString() { + return delegate.toString(); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java b/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java new file mode 100644 index 00000000000..36363a0ca26 --- /dev/null +++ b/core/src/main/java/com/orientechnologies/orient/core/hook/OHookThreadLocal.java @@ -0,0 +1,49 @@ +/* + * Copyright 1999-2011 Luca Garulli (l.garulli--at--orientechnologies.com) + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.orientechnologies.orient.core.hook; + +import java.util.HashSet; +import java.util.Set; + +import com.orientechnologies.orient.core.db.record.OIdentifiable; + +/** + * Avoid recursion when hooks call themselves on the same record instances. + * + * @author Luca Garulli (l.garulli--at--orientechnologies.com) + * + */ +public class OHookThreadLocal extends ThreadLocal> { + public static OHookThreadLocal INSTANCE = new OHookThreadLocal(); + + @Override + protected Set initialValue() { + return new HashSet(); + } + + public boolean push(final OIdentifiable iRecord) { + Set set = get(); + if (set.contains(iRecord)) + return false; + + set.add(iRecord); + return true; + } + + public boolean pop(final OIdentifiable iRecord) { + return get().remove(iRecord); + } +} \ No newline at end of file diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java index 5842d76740d..7347ef7ed86 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordSchemaAwareAbstract.java @@ -86,6 +86,7 @@ public OClass getSchemaClass() { } public String getClassName() { + checkForLoading(); checkForFields(); return _clazz != null ? _clazz.getName() : null; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java index 1ee7ba8580e..80def6c7925 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/impl/ODocument.java @@ -974,7 +974,7 @@ public ORecord placeholder() { cloned._source = _source; cloned._database = _database; cloned._recordId = _recordId.copy(); - cloned._status = _status; + cloned._status = STATUS.NOT_LOADED; return cloned; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java index 02b2a040e5b..eacb57c309c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/object/OObjectSerializerHelper.java @@ -137,7 +137,7 @@ else if (o instanceof Field) public static Class getFieldType(ODocument iDocument, final OEntityManager iEntityManager) { if (iDocument.getInternalStatus() == STATUS.NOT_LOADED) iDocument = (ODocument) iDocument.load(); - + if (iDocument.getClassName() == null) { return null; } else { @@ -369,9 +369,9 @@ public static String setObjectID(final ORID iIdentity, final Object iPojo) { if (ORID.class.isAssignableFrom(fieldType)) setFieldValue(iPojo, idFieldName, iIdentity); else if (Number.class.isAssignableFrom(fieldType)) - setFieldValue(iPojo, idFieldName, iIdentity.getClusterPosition()); + setFieldValue(iPojo, idFieldName, iIdentity != null ? iIdentity.getClusterPosition() : null); else if (fieldType.equals(String.class)) - setFieldValue(iPojo, idFieldName, iIdentity.toString()); + setFieldValue(iPojo, idFieldName, iIdentity != null ? iIdentity.toString() : null); else if (fieldType.equals(Object.class)) setFieldValue(iPojo, idFieldName, iIdentity); else diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java index e8e100b97cc..9fd254e72b2 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java @@ -444,9 +444,7 @@ private List> searchIndexedProperty(final List> iResultSet iResultSet.add(database.load((ORID) o)); else iResultSet.add((ORecord) o); - } - } } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java b/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java index 93ad3792461..25d94319ad6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/query/OSQLSynchQuery.java @@ -19,6 +19,7 @@ import java.util.List; import com.orientechnologies.orient.core.command.OCommandResultListener; +import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.hook.ORecordHook.TYPE; /** @@ -53,9 +54,9 @@ public void reset() { } public boolean result(final Object iRecord) { - database.callbackHooks(TYPE.BEFORE_READ, iRecord); + database.callbackHooks(TYPE.BEFORE_READ, (OIdentifiable) iRecord); result.add((T) iRecord); - database.callbackHooks(TYPE.AFTER_READ, iRecord); + database.callbackHooks(TYPE.AFTER_READ, (OIdentifiable) iRecord); return true; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java index 045f3d519fd..110d5d636a0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java @@ -24,6 +24,7 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.config.OStorageTxConfiguration; import com.orientechnologies.orient.core.exception.OTransactionException; +import com.orientechnologies.orient.core.hook.ORecordHook; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.storage.OCluster; import com.orientechnologies.orient.core.storage.OPhysicalPosition; @@ -154,7 +155,7 @@ protected void commitAllPendingRecords(final int iRequesterId, final OTransactio if (tmpEntries.size() > 0) { for (OTransactionEntry txEntry : tmpEntries) // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE - commitEntry(iRequesterId, iTx.getId(), txEntry); + commitEntry(iRequesterId, iTx, txEntry); allEntries.addAll(tmpEntries); tmpEntries.clear(); @@ -174,7 +175,7 @@ protected void rollback() { // TODO } - private void commitEntry(final int iRequesterId, final int iTxId, final OTransactionEntry txEntry) throws IOException { + private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry) throws IOException { if (txEntry.status != OTransactionEntry.DELETED && !txEntry.getRecord().isDirty()) return; @@ -197,26 +198,44 @@ private void commitEntry(final int iRequesterId, final int iTxId, final OTransac case OTransactionEntry.CREATED: // CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD - final byte[] stream = txEntry.getRecord().toStream(); + byte[] stream = txEntry.getRecord().toStream(); if (rid.isNew()) { - rid.clusterPosition = createRecord(iRequesterId, iTxId, cluster, stream, txEntry.getRecord().getRecordType()); + if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord())) + // RECORD CHANGED: RE-STREAM IT + stream = txEntry.getRecord().toStream(); + + rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType()); rid.clusterId = cluster.getId(); + + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord()); } else { txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry .getRecord().getRecordType())); } break; case OTransactionEntry.UPDATED: + if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord())) + // RECORD CHANGED: RE-STREAM IT + stream = txEntry.getRecord().toStream(); + txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord() + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord() .getVersion(), txEntry.getRecord().getRecordType())); + + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_UPDATE, txEntry.getRecord()); break; case OTransactionEntry.DELETED: - deleteRecord(iRequesterId, iTxId, cluster, rid.clusterPosition, txEntry.getRecord().getVersion()); + if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord())) + // RECORD CHANGED: RE-STREAM IT + stream = txEntry.getRecord().toStream(); + + deleteRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().getVersion()); + + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_DELETE, txEntry.getRecord()); break; } diff --git a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java index 56390c502be..c413f7eb923 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java +++ b/server/src/main/java/com/orientechnologies/orient/server/handler/distributed/ODistributedServerRecordHook.java @@ -26,6 +26,7 @@ import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.tx.OTransactionEntry; +import com.orientechnologies.orient.server.tx.OTransactionRecordProxy; /** * Record hook implementation. Catches all the relevant events and propagates to the cluster's slave nodes. @@ -49,6 +50,9 @@ public boolean onTrigger(final TYPE iType, final ORecord iRecord) { // if (!manager.isDistributedConfiguration()) // return; + if (iRecord instanceof OTransactionRecordProxy) + return false; + try { switch (iType) { case BEFORE_CREATE: @@ -66,18 +70,15 @@ public boolean onTrigger(final TYPE iType, final ORecord iRecord) { break; case AFTER_CREATE: - manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, - OTransactionEntry.CREATED, null)); + manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, OTransactionEntry.CREATED, null)); break; case AFTER_UPDATE: - manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, - OTransactionEntry.UPDATED, null)); + manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, OTransactionEntry.UPDATED, null)); break; case AFTER_DELETE: - manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, - OTransactionEntry.DELETED, null)); + manager.distributeRequest(new OTransactionEntry((ORecordInternal) iRecord, OTransactionEntry.DELETED, null)); break; } } catch (IOException e) { diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java new file mode 100644 index 00000000000..36a21d6f500 --- /dev/null +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/HookTxTest.java @@ -0,0 +1,165 @@ +/* + * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.orientechnologies.orient.test.database.auto; + +import java.io.IOException; +import java.util.List; + +import org.testng.Assert; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import com.orientechnologies.orient.core.db.object.ODatabaseObjectTx; +import com.orientechnologies.orient.core.hook.ORecordHookAbstract; +import com.orientechnologies.orient.core.record.ORecord; +import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; +import com.orientechnologies.orient.test.domain.whiz.Profile; + +@Test(groups = ""hook"") +public class HookTxTest extends ORecordHookAbstract { + private ODatabaseObjectTx database; + private int callbackCount = 0; + private Profile p; + + @Parameters(value = ""url"") + public HookTxTest(String iURL) { + database = new ODatabaseObjectTx(iURL); + } + + @Test + public void testRegisterHook() throws IOException { + database.open(""writer"", ""writer""); + database.registerHook(this); + database.getEntityManager().registerEntityClasses(""com.orientechnologies.orient.test.domain""); + } + + @Test(dependsOnMethods = ""testRegisterHook"") + public void testHookCalls() throws IOException { + + p = new Profile(""HookTxTest""); + + // TEST HOOKS ON CREATE + Assert.assertEquals(callbackCount, 0); + database.begin(); + database.save(p); + database.commit(); + + Assert.assertEquals(callbackCount, 11); + + // TEST HOOKS ON READ + database.begin(); + List result = database.query(new OSQLSynchQuery(""select * from Profile where nick = 'HookTxTest'"")); + Assert.assertFalse(result.size() == 0); + + for (int i = 0; i < result.size(); ++i) { + Assert.assertEquals(callbackCount, 46); + + p = result.get(i); + } + Assert.assertEquals(callbackCount, 46); + database.commit(); + + database.begin(); + // TEST HOOKS ON UPDATE + p.setValue(p.getValue() + 1000); + database.save(p); + + database.commit(); + Assert.assertEquals(callbackCount, 136); + + // TEST HOOKS ON DELETE + database.begin(); + database.delete(p); + database.commit(); + Assert.assertEquals(callbackCount, 266); + + database.unregisterHook(this); + database.close(); + } + + @Override + @Test(enabled = false) + public boolean onRecordBeforeCreate(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 1; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordAfterCreate(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 10; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordBeforeRead(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 20; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordAfterRead(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 15; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordBeforeUpdate(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 40; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordAfterUpdate(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 50; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordBeforeDelete(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 60; + return false; + } + + @Override + @Test(enabled = false) + public boolean onRecordAfterDelete(ORecord iRecord) { + if (iRecord instanceof ODocument && ((ODocument) iRecord).getClassName() != null + && ((ODocument) iRecord).getClassName().equals(""Profile"")) + callbackCount += 70; + return false; + } +} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml index e1802f897fd..0d45d890070 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/local-test-db-from-scratch.xml @@ -29,6 +29,7 @@ + diff --git a/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java b/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java index f507625e10a..3494e71eb70 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/domain/whiz/Profile.java @@ -19,11 +19,14 @@ import java.util.Set; import com.orientechnologies.orient.core.annotation.OId; +import com.orientechnologies.orient.core.annotation.OVersion; import com.orientechnologies.orient.test.domain.business.Address; public class Profile { @OId private String id; + @OVersion + private Integer version; private String nick; private Set followings = new HashSet(); private Set followers = new HashSet();" 439b7750d4750722a03d60465da2e4b62bbcf626,spring-framework,"fixed ""hibernateManagedSession"" mode to actually- work against Hibernate 4.0 (SPR-8776)--",c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java index 93f362367c50..28983de9e5ba 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java @@ -16,6 +16,7 @@ package org.springframework.orm.hibernate4; +import java.lang.reflect.Method; import java.sql.Connection; import javax.sql.DataSource; @@ -44,6 +45,8 @@ import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.ResourceTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * {@link org.springframework.transaction.PlatformTransactionManager} @@ -102,6 +105,15 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionManager implements ResourceTransactionManager, InitializingBean { + /** + * A Method handle for the SessionFactory.getCurrentSession() method. + * The return value differs between Hibernate 3.x and 4.x; for cross-compilation purposes, + * we have to use reflection here as long as we keep compiling against Hibernate 3.x jars. + */ + private static final Method getCurrentSessionMethod = + ClassUtils.getMethod(SessionFactory.class, ""getCurrentSession""); + + private SessionFactory sessionFactory; private DataSource dataSource; @@ -281,7 +293,7 @@ protected Object doGetTransaction() { } else if (this.hibernateManagedSession) { try { - Session session = getSessionFactory().getCurrentSession(); + Session session = (Session) ReflectionUtils.invokeMethod(getCurrentSessionMethod, this.sessionFactory); if (logger.isDebugEnabled()) { logger.debug(""Found Hibernate-managed Session ["" + session + ""] for Spring-managed transaction""); }" 7181fa35a35a4aa8e2f1bf8d2db39fa87a81e69d,hbase,HBASE-8062 Replace HBaseFsck.debugLsr() in- TestFlushSnapshotFromClient with FSUtils.logFileSystemState()--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1463646 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hbase,"diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java index 456df24d6593..7f1308e7ef7c 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/snapshot/TestFlushSnapshotFromClient.java @@ -55,7 +55,6 @@ import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSTableDescriptors; import org.apache.hadoop.hbase.util.FSUtils; -import org.apache.hadoop.hbase.util.HBaseFsck; import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread; import org.apache.log4j.Level; import org.junit.After; @@ -233,14 +232,16 @@ public void testAsyncFlushSnapshot() throws Exception { HMaster master = UTIL.getMiniHBaseCluster().getMaster(); SnapshotTestingUtils.waitForSnapshotToComplete(master, snapshot, 200); LOG.info("" === Async Snapshot Completed ===""); - HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration())); + FSUtils.logFileSystemState(UTIL.getTestFileSystem(), + FSUtils.getRootDir(UTIL.getConfiguration()), LOG); // make sure we get the snapshot SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshot); // test that we can delete the snapshot admin.deleteSnapshot(snapshot.getName()); LOG.info("" === Async Snapshot Deleted ===""); - HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration())); + FSUtils.logFileSystemState(UTIL.getTestFileSystem(), + FSUtils.getRootDir(UTIL.getConfiguration()), LOG); // make sure we don't have any snapshots SnapshotTestingUtils.assertNoSnapshots(admin); LOG.info("" === Async Snapshot Test Completed ===""); @@ -278,7 +279,7 @@ public void testFlushCreateListDestroy() throws Exception { Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir(); Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshots.get(0), rootDir); assertTrue(fs.exists(snapshotDir)); - HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), snapshotDir); + FSUtils.logFileSystemState(UTIL.getTestFileSystem(), snapshotDir, LOG); Path snapshotinfo = new Path(snapshotDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE); assertTrue(fs.exists(snapshotinfo)); @@ -304,7 +305,8 @@ public void testFlushCreateListDestroy() throws Exception { // test that we can delete the snapshot admin.deleteSnapshot(snapshotName); - HBaseFsck.debugLsr(UTIL.getHBaseCluster().getConfiguration(), FSUtils.getRootDir(UTIL.getConfiguration())); + FSUtils.logFileSystemState(UTIL.getTestFileSystem(), + FSUtils.getRootDir(UTIL.getConfiguration()), LOG); // make sure we don't have any snapshots SnapshotTestingUtils.assertNoSnapshots(admin);" 6215606577657832b408fb11b8e030950de5ea7f,drools,"JBRULES-3343 Property Specific -Added fix for- byPassModifyToLeftTupleSink, which was not working for LIANodes--",c,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java b/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java index d5e0ae72165..7660bec4421 100644 --- a/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java +++ b/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java @@ -219,10 +219,12 @@ public void modifyObject(final InternalFactHandle factHandle, } private void byPassModifyToBetaNode (ModifyPreviousTuples modifyPreviousTuples) { - for (ObjectSink objectSink : sink.getSinks()) { + for (ObjectSink objectSink : sink.getSinks()) { if (objectSink instanceof BetaNode) { RightTuple rightTuple = modifyPreviousTuples.removeRightTuple( (BetaNode) objectSink ); if ( rightTuple != null ) rightTuple.reAdd(); + } else if ( objectSink instanceof LeftInputAdapterNode ) { + ((LeftInputAdapterNode) objectSink).getSinkPropagator().byPassModifyToLeftTupleSink( modifyPreviousTuples ); } else if (objectSink instanceof AlphaNode) { ((AlphaNode)objectSink).byPassModifyToBetaNode( modifyPreviousTuples ); } diff --git a/drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java b/drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java index c4f70b898ea..9e7bd4212cc 100644 --- a/drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java +++ b/drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java @@ -180,6 +180,8 @@ public BaseNode getMatchingNode(BaseNode candidate) { } return null; //To change body of implemented methods use File | Settings | File Templates. } + + public LeftTupleSink[] getSinks() { final LeftTupleSink[] sinkArray = new LeftTupleSink[this.sinks.size()]; @@ -371,4 +373,10 @@ public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple, return childLeftTuple; } + public void byPassModifyToLeftTupleSink(ModifyPreviousTuples modifyPreviousTuples) { + for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) { + modifyPreviousTuples.removeLeftTuple( (LeftTupleSink) sink ); + } + } + } diff --git a/drools-core/src/main/java/org/drools/reteoo/LeftTupleSinkPropagator.java b/drools-core/src/main/java/org/drools/reteoo/LeftTupleSinkPropagator.java index bb6a632196e..5ce687e5d0a 100644 --- a/drools-core/src/main/java/org/drools/reteoo/LeftTupleSinkPropagator.java +++ b/drools-core/src/main/java/org/drools/reteoo/LeftTupleSinkPropagator.java @@ -74,6 +74,8 @@ public void doPropagateAssertLeftTuple(PropagationContext context, public BaseNode getMatchingNode(BaseNode candidate); public LeftTupleSink[] getSinks(); + + public void byPassModifyToLeftTupleSink (ModifyPreviousTuples modifyPreviousTuples); // public void propagateNewTupleSink(TupleMatch tupleMatch, // PropagationContext context, diff --git a/drools-core/src/main/java/org/drools/reteoo/SingleLeftTupleSinkAdapter.java b/drools-core/src/main/java/org/drools/reteoo/SingleLeftTupleSinkAdapter.java index f6d314f4a42..5866775d041 100644 --- a/drools-core/src/main/java/org/drools/reteoo/SingleLeftTupleSinkAdapter.java +++ b/drools-core/src/main/java/org/drools/reteoo/SingleLeftTupleSinkAdapter.java @@ -302,4 +302,8 @@ public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple, childLeftTuple.unlinkFromLeftParent(); return temp; } + + public void byPassModifyToLeftTupleSink(ModifyPreviousTuples modifyPreviousTuples) { + modifyPreviousTuples.removeLeftTuple( (LeftTupleSink) sink ); + } }" e917c77d296109edead50146691b09c91d3ea748,ReactiveX-RxJava,Add takeUntil support in Single--,a,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index 8f0db3e56b..813dc61a0d 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -12,6 +12,9 @@ */ package rx; +import java.util.Collection; +import java.util.concurrent.*; + import rx.Observable.Operator; import rx.annotations.Beta; import rx.annotations.Experimental; @@ -23,15 +26,13 @@ import rx.internal.util.ScalarSynchronousSingle; import rx.internal.util.UtilityFunctions; import rx.observers.SafeSubscriber; +import rx.observers.SerializedSubscriber; import rx.plugins.RxJavaObservableExecutionHook; import rx.plugins.RxJavaPlugins; import rx.schedulers.Schedulers; import rx.singles.BlockingSingle; import rx.subscriptions.Subscriptions; -import java.util.Collection; -import java.util.concurrent.*; - /** * The Single class implements the Reactive Pattern for a single value response. See {@link Observable} for the * implementation of the Reactive Pattern for a stream or vector of values. @@ -1800,6 +1801,156 @@ public void onError(Throwable error) { } }); } + + /** + * Returns a Single that emits the item emitted by the source Single until an Observable emits an item. Upon + * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to + * {@link SingleSubscriber#onSuccess(Object)}. + *

      + * + *

      + *
      Scheduler:
      + *
      {@code takeUntil} does not operate by default on a particular {@link Scheduler}.
      + *
      + * + * @param other + * the Observable whose first emitted item will cause {@code takeUntil} to emit the item from the source + * Single + * @param + * the type of items emitted by {@code other} + * @return a Single that emits the item emitted by the source Single until such time as {@code other} emits + * its first item + * @see ReactiveX operators documentation: TakeUntil + */ + public final Single takeUntil(final Observable other) { + return lift(new Operator() { + @Override + public Subscriber call(Subscriber child) { + final Subscriber serial = new SerializedSubscriber(child, false); + + final Subscriber main = new Subscriber(serial, false) { + @Override + public void onNext(T t) { + serial.onNext(t); + } + @Override + public void onError(Throwable e) { + try { + serial.onError(e); + } finally { + serial.unsubscribe(); + } + } + @Override + public void onCompleted() { + try { + serial.onCompleted(); + } finally { + serial.unsubscribe(); + } + } + }; + + final Subscriber so = new Subscriber() { + + @Override + public void onCompleted() { + onError(new CancellationException(""Stream was canceled before emitting a terminal event."")); + } + + @Override + public void onError(Throwable e) { + main.onError(e); + } + + @Override + public void onNext(E e) { + onError(new CancellationException(""Stream was canceled before emitting a terminal event."")); + } + }; + + serial.add(main); + serial.add(so); + + child.add(serial); + + other.unsafeSubscribe(so); + + return main; + } + }); + } + + /** + * Returns a Single that emits the item emitted by the source Single until a second Single emits an item. Upon + * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to + * {@link SingleSubscriber#onSuccess(Object)}. + *

      + * + *

      + *
      Scheduler:
      + *
      {@code takeUntil} does not operate by default on a particular {@link Scheduler}.
      + *
      + * + * @param other + * the Single whose emitted item will cause {@code takeUntil} to emit the item from the source Single + * @param + * the type of item emitted by {@code other} + * @return a Single that emits the item emitted by the source Single until such time as {@code other} emits its item + * @see ReactiveX operators documentation: TakeUntil + */ + public final Single takeUntil(final Single other) { + return lift(new Operator() { + @Override + public Subscriber call(Subscriber child) { + final Subscriber serial = new SerializedSubscriber(child, false); + + final Subscriber main = new Subscriber(serial, false) { + @Override + public void onNext(T t) { + serial.onNext(t); + } + @Override + public void onError(Throwable e) { + try { + serial.onError(e); + } finally { + serial.unsubscribe(); + } + } + @Override + public void onCompleted() { + try { + serial.onCompleted(); + } finally { + serial.unsubscribe(); + } + } + }; + + final SingleSubscriber so = new SingleSubscriber() { + @Override + public void onSuccess(E value) { + onError(new CancellationException(""Stream was canceled before emitting a terminal event."")); + } + + @Override + public void onError(Throwable e) { + main.onError(e); + } + }; + + serial.add(main); + serial.add(so); + + child.add(serial); + + other.subscribe(so); + + return main; + } + }); + } /** * Converts this Single into an {@link Observable}. diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java index 393088562c..0b934e65e6 100644 --- a/src/test/java/rx/SingleTest.java +++ b/src/test/java/rx/SingleTest.java @@ -15,6 +15,12 @@ import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; + import rx.Single.OnSubscribe; import rx.exceptions.CompositeException; import rx.functions.*; @@ -22,13 +28,9 @@ import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; import rx.singles.BlockingSingle; +import rx.subjects.PublishSubject; import rx.subscriptions.Subscriptions; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.*; - import static org.junit.Assert.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; @@ -1353,4 +1355,362 @@ public Observable call(Throwable throwable) { int numberOfErrors = retryCounter.getOnErrorEvents().size(); assertEquals(retryCount, numberOfErrors); } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilSuccess() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + other.sendOnSuccess(""one""); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilSourceSuccess() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + source.sendOnSuccess(""one""); + + result.assertValue(""one""); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilNext() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnNext(""one""); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilSourceSuccessObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + source.sendOnSuccess(""one""); + + result.assertValue(""one""); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilSourceError() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + Throwable error = new Throwable(); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + source.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilSourceErrorObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + Throwable error = new Throwable(); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + source.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilOtherError() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestSingle other = new TestSingle(sOther); + Throwable error = new Throwable(); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Single.create(other)); + stringSingle.subscribe(result); + other.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilOtherErrorObservable() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + Throwable error = new Throwable(); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnError(error); + + result.assertError(error); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + } + + @Test + @SuppressWarnings(""unchecked"") + public void takeUntilOtherCompleted() { + Subscription sSource = mock(Subscription.class); + Subscription sOther = mock(Subscription.class); + TestSingle source = new TestSingle(sSource); + TestObservable other = new TestObservable(sOther); + + TestSubscriber result = new TestSubscriber(); + Single stringSingle = Single.create(source).takeUntil(Observable.create(other)); + stringSingle.subscribe(result); + other.sendOnCompleted(); + + result.assertError(CancellationException.class); + verify(sSource).unsubscribe(); + verify(sOther).unsubscribe(); + + } + + private static class TestObservable implements Observable.OnSubscribe { + + Observer observer = null; + Subscription s; + + public TestObservable(Subscription s) { + this.s = s; + } + + /* used to simulate subscription */ + public void sendOnCompleted() { + observer.onCompleted(); + } + + /* used to simulate subscription */ + public void sendOnNext(String value) { + observer.onNext(value); + } + + /* used to simulate subscription */ + public void sendOnError(Throwable e) { + observer.onError(e); + } + + @Override + public void call(Subscriber observer) { + this.observer = observer; + observer.add(s); + } + } + + private static class TestSingle implements Single.OnSubscribe { + + SingleSubscriber subscriber = null; + Subscription s; + + public TestSingle(Subscription s) { + this.s = s; + } + + /* used to simulate subscription */ + public void sendOnSuccess(String value) { + subscriber.onSuccess(value); + } + + /* used to simulate subscription */ + public void sendOnError(Throwable e) { + subscriber.onError(e); + } + + @Override + public void call(SingleSubscriber observer) { + this.subscriber = observer; + observer.add(s); + } + } + + @Test + public void takeUntilFires() { + PublishSubject source = PublishSubject.create(); + PublishSubject until = PublishSubject.create(); + + TestSubscriber ts = new TestSubscriber(); + + source.take(1).toSingle().takeUntil(until.take(1).toSingle()).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + until.onNext(1); + + ts.assertError(CancellationException.class); + + assertFalse(""Source still has observers"", source.hasObservers()); + assertFalse(""Until still has observers"", until.hasObservers()); + assertFalse(""TestSubscriber is unsubscribed"", ts.isUnsubscribed()); + } + + @Test + public void takeUntilFiresObservable() { + PublishSubject source = PublishSubject.create(); + PublishSubject until = PublishSubject.create(); + + TestSubscriber ts = new TestSubscriber(); + + source.take(1).toSingle().takeUntil(until.take(1)).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + until.onNext(1); + + ts.assertError(CancellationException.class); + + assertFalse(""Source still has observers"", source.hasObservers()); + assertFalse(""Until still has observers"", until.hasObservers()); + assertFalse(""TestSubscriber is unsubscribed"", ts.isUnsubscribed()); + } + + @Test + public void takeUntilDownstreamUnsubscribes() { + PublishSubject source = PublishSubject.create(); + PublishSubject until = PublishSubject.create(); + + TestSubscriber ts = new TestSubscriber(); + + source.take(1).toSingle().takeUntil(until).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + source.onNext(1); + + ts.assertValue(1); + ts.assertNoErrors(); + ts.assertTerminalEvent(); + + assertFalse(""Source still has observers"", source.hasObservers()); + assertFalse(""Until still has observers"", until.hasObservers()); + assertFalse(""TestSubscriber is unsubscribed"", ts.isUnsubscribed()); + } + + @Test + public void takeUntilDownstreamUnsubscribesObservable() { + PublishSubject source = PublishSubject.create(); + PublishSubject until = PublishSubject.create(); + + TestSubscriber ts = new TestSubscriber(); + + source.take(1).toSingle().takeUntil(until.take(1).toSingle()).unsafeSubscribe(ts); + + assertTrue(source.hasObservers()); + assertTrue(until.hasObservers()); + + source.onNext(1); + + ts.assertValue(1); + ts.assertNoErrors(); + ts.assertTerminalEvent(); + + assertFalse(""Source still has observers"", source.hasObservers()); + assertFalse(""Until still has observers"", until.hasObservers()); + assertFalse(""TestSubscriber is unsubscribed"", ts.isUnsubscribed()); + } + + @Test + public void takeUntilSimple() { + PublishSubject stringSubject = PublishSubject.create(); + Single single = stringSubject.toSingle(); + + Subscription singleSubscription = single.takeUntil(Single.just(""Hello"")).subscribe( + new Action1() { + @Override + public void call(String s) { + fail(); + } + }, + new Action1() { + @Override + public void call(Throwable throwable) { + assertTrue(throwable instanceof CancellationException); + } + } + ); + assertTrue(singleSubscription.isUnsubscribed()); + } + + @Test + public void takeUntilObservable() { + PublishSubject stringSubject = PublishSubject.create(); + Single single = stringSubject.toSingle(); + PublishSubject otherSubject = PublishSubject.create(); + + Subscription singleSubscription = single.takeUntil(otherSubject.asObservable()).subscribe( + new Action1() { + @Override + public void call(String s) { + fail(); + } + }, + new Action1() { + @Override + public void call(Throwable throwable) { + assertTrue(throwable instanceof CancellationException); + } + } + ); + otherSubject.onNext(""Hello""); + assertTrue(singleSubscription.isUnsubscribed()); + } }" 51b603c850765b2734549a1962581ebe5f5f2125,restlet-framework-java,JAX-RS extension continued: - Added an- ObjectFactory to the JAX-RS extension for customized root resource class and- provider instantiation. Contributed by Bruno Dumon.--,a,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 050ac19537..ee28f2d5a0 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -66,6 +66,8 @@ Changes log parsing and formatting into three new classes: MessageRepresentation, MessagesRepresentation and RepresentationMessage. Suggested by Matthieu Hug. + - Added an ObjectFactory to the JAX-RS extension for customized root + resource class and provider instantiation. Contributed by Bruno Dumon. - Misc - Updated Grizzly to 1.7.3. - Improved logging consistency. diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java index d3c2a84bc5..0a304ee739 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsApplication.java @@ -73,7 +73,10 @@ */ public class JaxRsApplication extends Application { - /** the {@link Guard} to use. May be null. */ + /** Indicates if any {@link ApplicationConfig} is attached yet */ + private volatile boolean appConfigAttached = false; + + /** The {@link Guard} to use. May be null. */ private volatile Guard guard; /** The {@link JaxRsRouter} to use. */ @@ -82,9 +85,6 @@ public class JaxRsApplication extends Application { /** Indicates, if an {@link HtmlPreferer} should be used or not. */ private volatile boolean preferHtml = true; - /** indicates if any {@link ApplicationConfig} is attached yet */ - private volatile boolean appConfigAttached = false; - /** * Creates an new JaxRsApplication. You should typically use one of the * other constructors, see {@link Restlet#Restlet()}. @@ -248,6 +248,17 @@ public Guard getGuard() { return this.guard; } + /** + * Returns the ObjectFactory for root resource class and provider + * instantiation, if given. + * + * @return the ObjectFactory for root resource class and provider + * instantiation, if given. + */ + public ObjectFactory getObjectFactory() { + return this.jaxRsRouter.getObjectFactory(); + } + /** * Returns the current RoleChecker * @@ -337,6 +348,18 @@ public void setGuard(Guard guard) { this.guard = guard; } + /** + * Sets the ObjectFactory for root resource class and provider + * instantiation. + * + * @param objectFactory + * the ObjectFactory for root resource class and provider + * instantiation. + */ + public void setObjectFactory(ObjectFactory objectFactory) { + this.jaxRsRouter.setObjectFactory(objectFactory); + } + /** * Some browsers (e.g. Internet Explorer 7.0 and Firefox 2.0) sends as * accepted media type XML with a higher quality than HTML. The consequence diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java index 44ce111066..e0249faad5 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/JaxRsRouter.java @@ -166,6 +166,8 @@ public class JaxRsRouter extends Restlet { @SuppressWarnings(""unchecked"") private final ThreadLocalizedContext tlContext = new ThreadLocalizedContext(); + private volatile ObjectFactory objectFactory; + /** * Creates a new JaxRsRouter with the given Context. Only the default * providers are loaded. If a resource class later wants to check if a user @@ -330,8 +332,9 @@ private boolean addProvider(Class jaxRsProviderClass, } Provider provider; try { - provider = new Provider(jaxRsProviderClass, tlContext, - this.entityProviders, contextResolvers, getLogger()); + provider = new Provider(jaxRsProviderClass, objectFactory, + tlContext, this.entityProviders, contextResolvers, + getLogger()); } catch (InstantiateException e) { String msg = ""Ignore provider "" + jaxRsProviderClass.getName() + ""Could not instantiate the Provider, class "" @@ -507,7 +510,7 @@ private ResourceObject instantiateRrc(RootResourceClass rrc) throws WebApplicationException, RequestHandledException { ResourceObject o; try { - o = rrc.createInstance(); + o = rrc.createInstance(this.objectFactory); } catch (WebApplicationException e) { throw e; } catch (RuntimeException e) { @@ -1078,4 +1081,27 @@ public Collection getRootUris() { uris.add(rrc.getPathRegExp().getPathPattern()); return Collections.unmodifiableCollection(uris); } + + /** + * Returns the ObjectFactory for root resource class and provider + * instantiation, if given. + * + * @return the ObjectFactory for root resource class and provider + * instantiation, if given. + */ + public ObjectFactory getObjectFactory() { + return this.objectFactory; + } + + /** + * Sets the ObjectFactory for root resource class and provider + * instantiation. + * + * @param objectFactory + * the ObjectFactory for root resource class and provider + * instantiation. + */ + public void setObjectFactory(ObjectFactory objectFactory) { + this.objectFactory = objectFactory; + } } \ No newline at end of file diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java new file mode 100644 index 0000000000..dc4e8134a4 --- /dev/null +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/ObjectFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2005-2008 Noelios Consulting. + * + * The contents of this file are subject to the terms of the Common Development + * and Distribution License (the ""License""). You may not use this file except in + * compliance with the License. + * + * You can obtain a copy of the license at + * http://www.opensource.org/licenses/cddl1.txt See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each file and + * include the License file at http://www.opensource.org/licenses/cddl1.txt If + * applicable, add the following below this CDDL HEADER, with the fields + * enclosed by brackets ""[]"" replaced with your own identifying information: + * Portions Copyright [yyyy] [name of copyright owner] + */ +package org.restlet.ext.jaxrs; + +import org.restlet.ext.jaxrs.internal.exceptions.InstantiateException; + +/** + *

      + * Implement this interface to instantiate JAX-RS root resource classes and + * providers yourself and register it by + * {@link JaxRsApplication#setObjectFactory(ObjectFactory)}. + *

      + * + *

      + * When using a ObjectFactory, no JAX-RS constructor dependency injection will + * be performed, but instance variable and bean setter injection will still be + * done. + *

      + * + * @author Bruno Dumon + * @see JaxRsApplication#setObjectFactory(ObjectFactory) + * @see JaxRsRouter#setObjectFactory(ObjectFactory) + */ +public interface ObjectFactory { + /** + * Creates an instance of the given class.
      + * If the concrete instance could not instantiate the given class, it could + * return null. Than the constructor specified by the JAX-RS specification + * (section 4.2) is used. + * + * @param + * @param jaxRsClass + * the root resource class or provider class. + * @return + * @throws InstantiateException + */ + public T getInstance(Class jaxRsClass) throws InstantiateException; +} \ No newline at end of file diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java index 2957fc6c68..08dd0ae0dc 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/RootResourceClass.java @@ -28,6 +28,7 @@ import javax.ws.rs.ext.ContextResolver; import org.restlet.ext.jaxrs.JaxRsRouter; +import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertRepresentationException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; @@ -122,22 +123,28 @@ private static void checkClassForPathAnnot(Class jaxRsClass, /** * Creates an instance of the root resource class. * + * @param objectFactory + * object responsible for instantiating the root resource + * class. Optional, thus can be null. * @return * @throws InvocationTargetException * @throws InstantiateException * @throws MissingAnnotationException * @throws WebApplicationException */ - public ResourceObject createInstance() throws InstantiateException, - InvocationTargetException { - Constructor constructor = this.constructor; - Object instance; - try { - instance = WrapperUtil.createInstance(constructor, - constructorParameters.get()); - } catch (ConvertRepresentationException e) { - // is not possible - throw new ImplementationException(""Must not be possible"", e); + public ResourceObject createInstance(ObjectFactory objectFactory) + throws InstantiateException, InvocationTargetException { + Object instance = null; + if (objectFactory != null) + instance = objectFactory.getInstance(jaxRsClass); + if (instance == null) { + try { + Object[] args = constructorParameters.get(); + instance = WrapperUtil.createInstance(constructor, args); + } catch (ConvertRepresentationException e) { + // is not possible + throw new ImplementationException(""Must not be possible"", e); + } } ResourceObject rootResourceObject = new ResourceObject(instance, this); try { diff --git a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java index 1fa634f510..b42e36bc61 100644 --- a/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java +++ b/modules/org.restlet.ext.jaxrs_0.9/src/org/restlet/ext/jaxrs/internal/wrappers/provider/Provider.java @@ -40,6 +40,7 @@ import javax.ws.rs.ext.MessageBodyWorkers; import org.restlet.data.MediaType; +import org.restlet.ext.jaxrs.ObjectFactory; import org.restlet.ext.jaxrs.internal.core.CallContext; import org.restlet.ext.jaxrs.internal.core.ThreadLocalizedContext; import org.restlet.ext.jaxrs.internal.exceptions.ConvertCookieParamException; @@ -101,6 +102,9 @@ public class Provider implements MessageBodyReader, MessageBodyWriter, * * @param jaxRsProviderClass * the JAX-RS provider class. + * @param objectFactory + * The object factory is responsible for the provider + * instantiation, if given. * @param tlContext * The tread local wrapped call context * @param mbWorkers @@ -124,7 +128,7 @@ public class Provider implements MessageBodyReader, MessageBodyWriter, * @see javax.ws.rs.ext.ContextResolver */ @SuppressWarnings(""unchecked"") - public Provider(Class jaxRsProviderClass, + public Provider(Class jaxRsProviderClass, ObjectFactory objectFactory, ThreadLocalizedContext tlContext, EntityProviders mbWorkers, Collection> allResolvers, Logger logger) throws IllegalArgumentException, InvocationTargetException, @@ -134,10 +138,15 @@ public Provider(Class jaxRsProviderClass, throw new IllegalArgumentException( ""The JAX-RS provider class must not be null""); Util.checkClassConcrete(jaxRsProviderClass, ""provider""); - Constructor providerConstructor = WrapperUtil.findJaxRsConstructor( - jaxRsProviderClass, ""provider""); - this.jaxRsProvider = createInstance(providerConstructor, - jaxRsProviderClass, tlContext, mbWorkers, allResolvers, logger); + if (objectFactory != null) + this.jaxRsProvider = objectFactory.getInstance(jaxRsProviderClass); + if (this.jaxRsProvider == null) { + Constructor providerConstructor = WrapperUtil + .findJaxRsConstructor(jaxRsProviderClass, ""provider""); + this.jaxRsProvider = createInstance(providerConstructor, + jaxRsProviderClass, tlContext, mbWorkers, allResolvers, + logger); + } boolean isProvider = false; if (jaxRsProvider instanceof javax.ws.rs.ext.MessageBodyWriter) { this.writer = (javax.ws.rs.ext.MessageBodyWriter) jaxRsProvider;" 62c8bfade88dc4b72a07c4a0d6f6633e5d0fcdad,orientdb,Fixed issue 1198: NullPointerException in- OCommandExecutorSQLResultsetAbstract.assignTarget--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java index feb3d9fac59..5be0dcec737 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java @@ -145,7 +145,7 @@ else if (parsedTarget.getTargetVariable() != null) { return true; } else if (var instanceof OIdentifiable) { final ArrayList list = new ArrayList(); - ((List) target).add((OIdentifiable) var); + list.add((OIdentifiable) var); target = list.iterator(); } else if (var instanceof Iterable) target = ((Iterable) var).iterator(); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java index 9498b38513e..c8f2826d5b1 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java @@ -16,6 +16,7 @@ package com.orientechnologies.orient.test.database.auto; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; @@ -230,6 +231,33 @@ public void insertWithNoSpaces() { database.close(); } + @Test + public void insertAvoidingSubQuery() { + database.open(""admin"", ""admin""); + + ODocument doc = (ODocument) database.command(new OCommandSQL(""INSERT INTO test(text) VALUES ('(Hello World)')"")).execute(); + + Assert.assertTrue(doc != null); + Assert.assertEquals(doc.field(""text""), ""(Hello World)""); + + database.close(); + } + + @Test + public void insertSubQuery() { + database.open(""admin"", ""admin""); + + ODocument doc = (ODocument) database.command(new OCommandSQL(""INSERT INTO test SET names = (select name from OUser)"")) + .execute(); + + Assert.assertTrue(doc != null); + Assert.assertNotNull(doc.field(""names"")); + Assert.assertTrue(doc.field(""names"") instanceof Collection); + Assert.assertEquals(((Collection) doc.field(""names"")).size(), 3); + + database.close(); + } + @Test public void insertCluster() { database.open(""admin"", ""admin""); @@ -274,7 +302,7 @@ private List getValidPositions(int clusterId) { for (int i = 0; i < 100; i++) { if (!iteratorCluster.hasNext()) break; - ORecord doc = iteratorCluster.next(); + ORecord doc = iteratorCluster.next(); positions.add(doc.getIdentity().getClusterPosition()); } return positions;" a7e7e662aec3201493c48b78be0ec0a7ef3cfbbe,restlet-framework-java,Added parsing of RDF XML.--,a,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlParsingContentHandler.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlParsingContentHandler.java index 27c975a8e3..e56a6f7921 100644 --- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlParsingContentHandler.java +++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlParsingContentHandler.java @@ -157,16 +157,13 @@ public void endElement(String uri, String localName, String name) if (state == State.SUBJECT) { popSubject(); } else if (state == State.PREDICATE) { - if (this.builder.length() > 0) { - this.graphHandler.link(getCurrentSubject(), - this.currentPredicate, getLiteral(builder - .toString(), null, this.currentLanguage)); - } + this.graphHandler.link(getCurrentSubject(), + this.currentPredicate, getLiteral(builder.toString(), + null, this.currentLanguage)); + } else if (state == State.OBJECT) { - if (this.builder.length() > 0) { - this.currentObject = getLiteral(builder.toString(), null, - this.currentLanguage); - } + this.currentObject = getLiteral(builder.toString(), null, + this.currentLanguage); } else if (state == State.LITERAL) { if (nodeDepth == 0) { // End of the XML literal" 1d90b2e1fe600816ace2acbdda25431f62d0f1c2,kotlin,Get rid of obsolete syntax in quickfixes changing- lambda's signature--- Do not wrap parameters with '()'-- Do not set return type for them-- Fix existing testData-,p,https://github.com/JetBrains/kotlin,"diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeInfo.kt index 4166799ea3381..90dd5199d5bee 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeInfo.kt @@ -228,6 +228,12 @@ public open class JetChangeInfo( } public fun getNewParametersSignature(inheritedCallable: JetCallableDefinitionUsage): String { + return ""("" + getNewParametersSignatureWithoutParentheses(inheritedCallable) + "")"" + } + + public fun getNewParametersSignatureWithoutParentheses( + inheritedCallable: JetCallableDefinitionUsage + ): String { val signatureParameters = getNonReceiverParameters() val isLambda = inheritedCallable.getDeclaration() is JetFunctionLiteral @@ -237,7 +243,7 @@ public open class JetChangeInfo( return signatureParameters.indices .map { i -> signatureParameters[i].getDeclarationSignature(i, inheritedCallable) } - .joinToString(prefix = ""("", separator = "", "", postfix = "")"") + .joinToString(separator = "", "") } public fun renderReceiverType(inheritedCallable: JetCallableDefinitionUsage): String? { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JetCallableDefinitionUsage.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JetCallableDefinitionUsage.java index a1a7274745d18..aac8745be4111 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JetCallableDefinitionUsage.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JetCallableDefinitionUsage.java @@ -227,9 +227,8 @@ protected void changeReturnTypeIfNeeded(JetChangeInfo changeInfo, PsiElement ele boolean returnTypeIsNeeded; if (element instanceof JetFunction) { - returnTypeIsNeeded = (changeInfo.isRefactoringTarget(originalCallableDescriptor) || - !(callable instanceof JetFunctionLiteral) || - callable.getTypeReference() != null); + returnTypeIsNeeded = !(callable instanceof JetFunctionLiteral) + && (changeInfo.isRefactoringTarget(originalCallableDescriptor) || callable.getTypeReference() != null); } else { returnTypeIsNeeded = element instanceof JetProperty || element instanceof JetParameter; @@ -261,7 +260,7 @@ private void processParameterListWithStructuralChanges( JetParameterList newParameterList = null; if (isLambda) { - if (parametersCount == 0 && ((JetFunctionLiteral) element).getTypeReference() == null) { + if (parametersCount == 0) { if (parameterList != null) { parameterList.delete(); PsiElement arrow = ((JetFunctionLiteral)element).getArrow(); @@ -272,7 +271,7 @@ private void processParameterListWithStructuralChanges( } } else { - newParameterList = psiFactory.createFunctionLiteralParameterList(changeInfo.getNewParametersSignature( + newParameterList = psiFactory.createFunctionLiteralParameterList(changeInfo.getNewParametersSignatureWithoutParentheses( (JetCallableDefinitionUsage) this) ); canReplaceEntireList = true; diff --git a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters1.kt b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters1.kt index c21d427282d34..ca3712073d97d 100644 --- a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters1.kt +++ b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters1.kt @@ -2,5 +2,5 @@ // DISABLE-ERRORS fun f(x: Int, y: Int, z : () -> Int) { - f(1, 2, {(x: Int, y: Int) -> x}); + f(1, 2, {x: Int, y: Int -> x}); } diff --git a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt index 38b814edd96eb..2a49b3dbefc16 100644 --- a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt +++ b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt @@ -2,5 +2,5 @@ // DISABLE-ERRORS fun f(x: Int, y: Int, z : (Int, Int?, Any) -> Int) { - f(1, 2, {(x: Int) -> x}); + f(1, 2, {x: Int -> x}); } diff --git a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt.after b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt.after index cf06b743b433c..8c0569b05529e 100644 --- a/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt.after +++ b/idea/testData/quickfix/changeSignature/changeFunctionLiteralParameters2.kt.after @@ -2,5 +2,5 @@ // DISABLE-ERRORS fun f(x: Int, y: Int, z : (Int, Int?, Any) -> Int) { - f(1, 2, {(i: Int, i1: Int?, any: Any) -> x}); + f(1, 2, { i: Int, i1: Int?, any: Any -> x}); } diff --git a/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt b/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt index 320ac11b5557b..6914871dee302 100644 --- a/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt +++ b/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt @@ -5,5 +5,5 @@ fun foo(f: Int.(Int, Int) -> Int) { } fun test() { - foo { (a: Int) -> 0 } + foo { a: Int -> 0 } } \ No newline at end of file diff --git a/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt.after b/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt.after index 9ac2b9ba304bc..a3a82db4be1cf 100644 --- a/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt.after +++ b/idea/testData/quickfix/changeSignature/fixExtensionLambdaSignature.kt.after @@ -5,5 +5,5 @@ fun foo(f: Int.(Int, Int) -> Int) { } fun test() { - foo {(i: Int, i1: Int) -> 0 } + foo { i: Int, i1: Int -> 0 } } \ No newline at end of file diff --git a/idea/testData/quickfix/changeSignature/matchFunctionLiteralWithSAMType.after.kt b/idea/testData/quickfix/changeSignature/matchFunctionLiteralWithSAMType.after.kt index c896bcf85705b..4b6fb3e637802 100644 --- a/idea/testData/quickfix/changeSignature/matchFunctionLiteralWithSAMType.after.kt +++ b/idea/testData/quickfix/changeSignature/matchFunctionLiteralWithSAMType.after.kt @@ -2,5 +2,5 @@ // DISABLE-ERRORS fun main(args: Array) { - Test().perform("""") {(s: String?, s1: String?) -> } + Test().perform("""") { s: String?, s1: String? -> } } diff --git a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt index c8897d3a65e40..a0a8ef6803967 100644 --- a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt +++ b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt @@ -1,6 +1,6 @@ // ""Change type from 'String' to '(Int) -> String'"" ""true"" fun foo(f: ((Int) -> String) -> String) { foo { - (f: String) -> f(42) + f: String -> f(42) } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt.after b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt.after index 89a07f91281e2..753225d3c44f5 100644 --- a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt.after +++ b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionType.kt.after @@ -1,6 +1,6 @@ // ""Change type from 'String' to '(Int) -> String'"" ""true"" fun foo(f: ((Int) -> String) -> String) { foo { - (f: (Int) -> String) -> f(42) + f: (Int) -> String -> f(42) } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt index 7e9e824e73a4e..3c51ba3125541 100644 --- a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt +++ b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt @@ -2,6 +2,6 @@ fun foo(f: ((java.util.LinkedHashSet) -> java.util.HashSet) -> String) { foo { - (f: String) -> ""42"" + f: String -> ""42"" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt.after b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt.after index 9c54b5f1bda3d..89ac14af56638 100644 --- a/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt.after +++ b/idea/testData/quickfix/typeMismatch/changeFunctionLiteralParameterTypeToFunctionTypeLongNameRuntime.kt.after @@ -5,6 +5,6 @@ import java.util.LinkedHashSet fun foo(f: ((java.util.LinkedHashSet) -> java.util.HashSet) -> String) { foo { - (f: (LinkedHashSet) -> HashSet) -> ""42"" + f: (LinkedHashSet) -> HashSet -> ""42"" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt index df3397685ceb3..e3089b5b26e4e 100644 --- a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt +++ b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt @@ -1,6 +1,6 @@ // ""Change type from 'String' to 'Int'"" ""true"" fun foo(f: (Int) -> String) { foo { - (x: String) -> """" + x: String -> """" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt.after b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt.after index 339488f1d5335..31e6d905c15b0 100644 --- a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt.after +++ b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatch.kt.after @@ -1,6 +1,6 @@ // ""Change type from 'String' to 'Int'"" ""true"" fun foo(f: (Int) -> String) { foo { - (x: Int) -> """" + x: Int -> """" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt index b362d569f6a51..c1bfcec90a2f6 100644 --- a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt +++ b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt @@ -2,6 +2,6 @@ fun foo(f: (java.util.HashSet) -> String) { foo { - (x: String) -> """" + x: String -> """" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt.after b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt.after index 9d101bd8c0ff6..85917b2ba68e3 100644 --- a/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt.after +++ b/idea/testData/quickfix/typeMismatch/expectedParameterTypeMismatchLongNameRuntime.kt.after @@ -4,6 +4,6 @@ import java.util.HashSet fun foo(f: (java.util.HashSet) -> String) { foo { - (x: HashSet) -> """" + x: HashSet -> """" } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt b/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt index a1ffc07759c6d..57484fa75c1fd 100644 --- a/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt +++ b/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt @@ -1,4 +1,4 @@ // ""Change 'f' type to '(Long) -> Unit'"" ""true"" fun foo() { - var f: Int = if (true) { (x: Long) -> } else { (x: Long) -> } + var f: Int = if (true) { x: Long -> } else { x: Long -> } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt.after b/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt.after index 4302b75770c17..032a1cceff1c1 100644 --- a/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt.after +++ b/idea/testData/quickfix/typeMismatch/propertyTypeMismatch.kt.after @@ -1,4 +1,4 @@ // ""Change 'f' type to '(Long) -> Unit'"" ""true"" fun foo() { - var f: (Long) -> Unit = if (true) { (x: Long) -> } else { (x: Long) -> } + var f: (Long) -> Unit = if (true) { x: Long -> } else { x: Long -> } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt b/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt index cc3c789f2fb21..b6ccd0b3bfc62 100644 --- a/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt +++ b/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt @@ -1,5 +1,5 @@ // ""Change 'f' type to '(Delegates) -> Unit'"" ""true"" fun foo() { - var f: Int = { (x: kotlin.properties.Delegates) -> } + var f: Int = { x: kotlin.properties.Delegates -> } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt.after b/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt.after index f2f5d044e8bb6..c1ef6ac5481f8 100644 --- a/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt.after +++ b/idea/testData/quickfix/typeMismatch/propertyTypeMismatchLongNameRuntime.kt.after @@ -3,5 +3,5 @@ import kotlin.properties.Delegates // ""Change 'f' type to '(Delegates) -> Unit'"" ""true"" fun foo() { - var f: (Delegates) -> Unit = { (x: kotlin.properties.Delegates) -> } + var f: (Delegates) -> Unit = { x: kotlin.properties.Delegates -> } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt index 2f90f8ee5e57c..3e830bc517ab6 100644 --- a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt +++ b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt @@ -1,4 +1,4 @@ // ""Change 'foo' function return type to '(Long) -> Int'"" ""true"" fun foo(x: Any): Int { - return {(x: Long) -> 42} + return {x: Long -> 42} } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt.after b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt.after index 4d6e718b94650..16b3d57bdc764 100644 --- a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt.after +++ b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/changeFunctionReturnTypeToFunctionType.kt.after @@ -1,4 +1,4 @@ // ""Change 'foo' function return type to '(Long) -> Int'"" ""true"" fun foo(x: Any): (Long) -> Int { - return {(x: Long) -> 42} + return {x: Long -> 42} } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/dontChangeFunctionReturnTypeToErrorType.kt b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/dontChangeFunctionReturnTypeToErrorType.kt index 2bdfc0c4b4164..f2876c47d15cc 100644 --- a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/dontChangeFunctionReturnTypeToErrorType.kt +++ b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/dontChangeFunctionReturnTypeToErrorType.kt @@ -8,5 +8,5 @@ // ERROR: Unresolved reference: NoSuchType fun foo(): Int { - return { (x: NoSuchType) -> 42 } + return { x: NoSuchType -> 42 } } \ No newline at end of file diff --git a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt index ae1c5c6a142eb..86fcfee1ac3b5 100644 --- a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt +++ b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt @@ -1,8 +1,8 @@ // ""Change 'f' type to '(Int, Int) -> (String) -> Int'"" ""true"" fun foo() { val f: () -> Long = { - (a: Int, b: Int): Long -> - val x = {(s: String) -> 42} + a: Int, b: Int -> + val x = {s: String -> 42} if (true) x else if (true) x else { var y = 42 diff --git a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt.after b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt.after index 19f21d70c714c..2628565175739 100644 --- a/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt.after +++ b/idea/testData/quickfix/typeMismatch/typeMismatchOnReturnedExpression/typeMismatchInIfStatementReturnedByLiteral.kt.after @@ -1,8 +1,8 @@ // ""Change 'f' type to '(Int, Int) -> (String) -> Int'"" ""true"" fun foo() { val f: (Int, Int) -> (String) -> Int = { - (a: Int, b: Int): (String) -> Int -> - val x = {(s: String) -> 42} + a: Int, b: Int -> + val x = {s: String -> 42} if (true) x else if (true) x else { var y = 42 diff --git a/idea/testData/refactoring/changeSignature/FunctionLiteralAfter.kt b/idea/testData/refactoring/changeSignature/FunctionLiteralAfter.kt index c8fac6d929269..db354080816f3 100644 --- a/idea/testData/refactoring/changeSignature/FunctionLiteralAfter.kt +++ b/idea/testData/refactoring/changeSignature/FunctionLiteralAfter.kt @@ -1,3 +1,3 @@ fun foo() { - val v1 = {(z: Int, y1: String, x: Any): Int -> println(z); println(y1) } + val v1 = { z: Int, y1: String, x: Any -> println(z); println(y1) } } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/FunctionLiteralBefore.kt b/idea/testData/refactoring/changeSignature/FunctionLiteralBefore.kt index f027cbe8f3c32..5fa5962b78e98 100644 --- a/idea/testData/refactoring/changeSignature/FunctionLiteralBefore.kt +++ b/idea/testData/refactoring/changeSignature/FunctionLiteralBefore.kt @@ -1,3 +1,3 @@ fun foo() { - val v1 = {(z: Int, y: String) -> println(z); println(y) } + val v1 = {z: Int, y: String -> println(z); println(y) } } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsAfter.1.kt b/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsAfter.1.kt index 55af593fa401b..1d5bfe2abda0b 100644 --- a/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsAfter.1.kt @@ -1,5 +1,5 @@ fun test() { - SamTest.test(Foo { (s, n) -> """" }) - SamTest.test(Foo { (s: MutableList>, n: X>) -> """" }) - SamTest.test(Foo { (s: MutableList>, n: X>): X>? -> """" }) + SamTest.test(Foo { s, n -> """" }) + SamTest.test(Foo { s: MutableList>, n: X> -> """" }) + SamTest.test(Foo { s: MutableList>, n: X> -> """" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsBefore.1.kt b/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsBefore.1.kt index 49329c7ae6c7f..b0ccee6a6433c 100644 --- a/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/GenericsWithSAMConstructorsBefore.1.kt @@ -1,5 +1,5 @@ fun test() { - SamTest.test(Foo { (s, n) -> """" }) - SamTest.test(Foo { (s: String, n: Int) -> """" }) - SamTest.test(Foo { (s: String, n: Int): String -> """" }) + SamTest.test(Foo { s, n -> """" }) + SamTest.test(Foo { s: String, n: Int -> """" }) + SamTest.test(Foo { s: String, n: Int -> """" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMAddToEmptyParamListBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMAddToEmptyParamListBefore.1.kt index a2b3563f7f39a..0e10cdc69f08c 100644 --- a/idea/testData/refactoring/changeSignature/SAMAddToEmptyParamListBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMAddToEmptyParamListBefore.1.kt @@ -1,5 +1,5 @@ fun test() { JTest.samTest(SAM { "" "" }) - JTest.samTest(SAM { () -> "" "" }) + JTest.samTest(SAM { -> "" "" }) JTest.samTest(SAM { -> "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListAfter.1.kt b/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListAfter.1.kt index aa4ca782cc2d1..b1f02320d2124 100644 --- a/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListAfter.1.kt @@ -1,3 +1,3 @@ fun test() { - JTest.samTest(SAM {(s, n, o) -> s + "" "" + n }) + JTest.samTest(SAM { s, n, o -> s + "" "" + n }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListBefore.1.kt index 95a93c212dc77..7906af65a0814 100644 --- a/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMAddToNonEmptyParamListBefore.1.kt @@ -1,3 +1,3 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" + n }) + JTest.samTest(SAM { s, n -> s + "" "" + n }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListAfter.1.kt b/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListAfter.1.kt index b369af61c4f9e..a434049bda7ef 100644 --- a/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListAfter.1.kt @@ -1,5 +1,5 @@ fun test() { - JTest.samTest(SAM {(n, s) -> s + "" "" }) - JTest.samTest(SAM {(n, s) -> s + "" "" }) - JTest.samTest(SAM {(n, it) -> it + "" "" }) + JTest.samTest(SAM { n, s -> s + "" "" }) + JTest.samTest(SAM { n, s -> s + "" "" }) + JTest.samTest(SAM { n, it -> it + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListBefore.1.kt index 6f7a69ac4f6a3..42110a56c4b08 100644 --- a/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMAddToSingletonParamListBefore.1.kt @@ -1,5 +1,5 @@ fun test() { JTest.samTest(SAM { s -> s + "" "" }) - JTest.samTest(SAM { (s) -> s + "" "" }) + JTest.samTest(SAM { s -> s + "" "" }) JTest.samTest(SAM { it + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeAfter.1.kt b/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeAfter.1.kt index 8d622ae21b4d6..2aac73f88b0b3 100644 --- a/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeAfter.1.kt @@ -1,4 +1,4 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" }) - JTest.samTest(SAM { (s, n): Any? -> s + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeBefore.1.kt index 09de97025b58b..2aac73f88b0b3 100644 --- a/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMChangeMethodReturnTypeBefore.1.kt @@ -1,4 +1,4 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" }) - JTest.samTest(SAM { (s, n): String -> s + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMChangeParamTypeAfter.1.kt b/idea/testData/refactoring/changeSignature/SAMChangeParamTypeAfter.1.kt index d3c2641ff1526..2a08ca341d9ac 100644 --- a/idea/testData/refactoring/changeSignature/SAMChangeParamTypeAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMChangeParamTypeAfter.1.kt @@ -1,4 +1,4 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" }) - JTest.samTest(SAM { (s: Any, n: Int) -> x + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) + JTest.samTest(SAM { s: Any, n: Int -> x + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMChangeParamTypeBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMChangeParamTypeBefore.1.kt index ed09e73f976ed..fe646a80b6da5 100644 --- a/idea/testData/refactoring/changeSignature/SAMChangeParamTypeBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMChangeParamTypeBefore.1.kt @@ -1,4 +1,4 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" }) - JTest.samTest(SAM { (s: String, n: Int) -> x + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) + JTest.samTest(SAM { s: String, n: Int -> x + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMRemoveParamBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMRemoveParamBefore.1.kt index 7b9695cb6f524..f0f5574b2999a 100644 --- a/idea/testData/refactoring/changeSignature/SAMRemoveParamBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMRemoveParamBefore.1.kt @@ -1,4 +1,4 @@ fun test() { - JTest.samTest(SAM { (s, n) -> s + "" "" }) - JTest.samTest(SAM { (x, y) -> x + "" "" }) + JTest.samTest(SAM { s, n -> s + "" "" }) + JTest.samTest(SAM { x, y -> x + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListAfter.1.kt b/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListAfter.1.kt index d108ed3fd8187..7e36ba365e32a 100644 --- a/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListAfter.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListAfter.1.kt @@ -1,5 +1,4 @@ fun test() { - JTest.samTest(SAM { s + "" "" }) JTest.samTest(SAM { s + "" "" }) JTest.samTest(SAM { it + "" "" }) } \ No newline at end of file diff --git a/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListBefore.1.kt b/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListBefore.1.kt index 6f7a69ac4f6a3..4b79a82b71972 100644 --- a/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListBefore.1.kt +++ b/idea/testData/refactoring/changeSignature/SAMRemoveSingletonParamListBefore.1.kt @@ -1,5 +1,4 @@ fun test() { JTest.samTest(SAM { s -> s + "" "" }) - JTest.samTest(SAM { (s) -> s + "" "" }) JTest.samTest(SAM { it + "" "" }) } \ No newline at end of file" 0744b7f381289147be4eb9e43a0f03e449c1768c,intellij-community,fix navbar rebuild on popup invocation--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java index a660037d7346f..6ba150185b141 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPanel.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -436,8 +436,9 @@ void navigateInsideBar(final Object object) { myContextObject = null; myUpdateQueue.cancelAllUpdates(); - - myUpdateQueue.queueModelUpdateForObject(obj); + if (myNodePopup != null && myNodePopup.isVisible()) { + myUpdateQueue.queueModelUpdateForObject(obj); + } myUpdateQueue.queueRebuildUi(); myUpdateQueue.queueAfterAll(new Runnable() {" 80ef201514764e948d2ed8b91143c205560382b1,elasticsearch,Remove dead code and add missing @Override- annotations--,p,https://github.com/elastic/elasticsearch,"diff --git a/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java b/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java index 9996d705b331a..ce8c8140ce072 100644 --- a/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java +++ b/core/src/main/java/org/elasticsearch/index/shard/InternalIndexingStats.java @@ -64,13 +64,14 @@ IndexingStats stats(boolean isThrottled, long currentThrottleInMillis, String... return new IndexingStats(total, typesSt); } - + @Override public Engine.Index preIndex(Engine.Index operation) { totalStats.indexCurrent.inc(); typeStats(operation.type()).indexCurrent.inc(); return operation; } + @Override public void postIndex(Engine.Index index) { long took = index.endTime() - index.startTime(); totalStats.indexMetric.inc(took); @@ -80,6 +81,7 @@ public void postIndex(Engine.Index index) { typeStats.indexCurrent.dec(); } + @Override public void postIndex(Engine.Index index, Throwable ex) { totalStats.indexCurrent.dec(); typeStats(index.type()).indexCurrent.dec(); @@ -87,13 +89,14 @@ public void postIndex(Engine.Index index, Throwable ex) { typeStats(index.type()).indexFailed.inc(); } + @Override public Engine.Delete preDelete(Engine.Delete delete) { totalStats.deleteCurrent.inc(); typeStats(delete.type()).deleteCurrent.inc(); return delete; } - + @Override public void postDelete(Engine.Delete delete) { long took = delete.endTime() - delete.startTime(); totalStats.deleteMetric.inc(took); @@ -103,6 +106,7 @@ public void postDelete(Engine.Delete delete) { typeStats.deleteCurrent.dec(); } + @Override public void postDelete(Engine.Delete delete, Throwable ex) { totalStats.deleteCurrent.dec(); typeStats(delete.type()).deleteCurrent.dec(); @@ -113,22 +117,6 @@ public void noopUpdate(String type) { typeStats(type).noopUpdates.inc(); } - public void clear() { // NOCOMMIT - this is unused? - totalStats.clear(); - synchronized (this) { - if (!typesStats.isEmpty()) { - MapBuilder typesStatsBuilder = MapBuilder.newMapBuilder(); - for (Map.Entry typeStats : typesStats.entrySet()) { - if (typeStats.getValue().totalCurrent() > 0) { - typeStats.getValue().clear(); - typesStatsBuilder.put(typeStats.getKey(), typeStats.getValue()); - } - } - typesStats = typesStatsBuilder.immutableMap(); - } - } - } - private StatsHolder typeStats(String type) { StatsHolder stats = typesStats.get(type); if (stats == null) { @@ -144,29 +132,23 @@ private StatsHolder typeStats(String type) { } static class StatsHolder { - public final MeanMetric indexMetric = new MeanMetric(); - public final MeanMetric deleteMetric = new MeanMetric(); - public final CounterMetric indexCurrent = new CounterMetric(); - public final CounterMetric indexFailed = new CounterMetric(); - public final CounterMetric deleteCurrent = new CounterMetric(); - public final CounterMetric noopUpdates = new CounterMetric(); - - public IndexingStats.Stats stats(boolean isThrottled, long currentThrottleMillis) { + private final MeanMetric indexMetric = new MeanMetric(); + private final MeanMetric deleteMetric = new MeanMetric(); + private final CounterMetric indexCurrent = new CounterMetric(); + private final CounterMetric indexFailed = new CounterMetric(); + private final CounterMetric deleteCurrent = new CounterMetric(); + private final CounterMetric noopUpdates = new CounterMetric(); + + IndexingStats.Stats stats(boolean isThrottled, long currentThrottleMillis) { return new IndexingStats.Stats( indexMetric.count(), TimeUnit.NANOSECONDS.toMillis(indexMetric.sum()), indexCurrent.count(), indexFailed.count(), deleteMetric.count(), TimeUnit.NANOSECONDS.toMillis(deleteMetric.sum()), deleteCurrent.count(), noopUpdates.count(), isThrottled, TimeUnit.MILLISECONDS.toMillis(currentThrottleMillis)); } - public long totalCurrent() { - return indexCurrent.count() + deleteMetric.count(); - } - - public void clear() { + void clear() { indexMetric.clear(); deleteMetric.clear(); } - - } }" 615adaba0cdfa8685039f4eb0765df053deead9c,restlet-framework-java,Fixed range issue -607.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java index 2e97420ce8..b34582859c 100644 --- a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java @@ -266,6 +266,15 @@ public void testGet() throws Exception { assertEquals(2, response.getEntity().getRange().getIndex()); assertEquals(8, response.getEntity().getRange().getSize()); + request.setRanges(Arrays.asList(new Range(2, 1000))); + response = client.handle(request); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); + assertEquals(""34567890"", response.getEntity().getText()); + assertEquals(10, response.getEntity().getSize()); + assertEquals(8, response.getEntity().getAvailableSize()); + assertEquals(2, response.getEntity().getRange().getIndex()); + assertEquals(8, response.getEntity().getRange().getSize()); + client.stop(); } diff --git a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java index eea7b61abb..ecbef8ecd0 100644 --- a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java +++ b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java @@ -106,6 +106,12 @@ protected void afterHandle(Request request, Response response) { .info(""The range of the response entity is not equal to the requested one.""); } + if (response.getEntity().hasKnownSize() + && requestedRange.getSize() > response + .getEntity().getAvailableSize()) { + requestedRange.setSize(Range.SIZE_MAX); + } + response.setEntity(new RangeRepresentation( response.getEntity(), requestedRange)); response.setStatus(Status.SUCCESS_PARTIAL_CONTENT);" bd92322d22be4a00f1a6fbd4fe45660a920eca6d,hadoop,HADOOP-6367. Removes Access Token implementation- from common. Contributed by Kan Zhang.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@881509 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index 89901793723e3..2c19f62abc95d 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -653,6 +653,9 @@ Release 0.21.0 - Unreleased HADOOP-6343. Log unexpected throwable object caught in RPC. (Jitendra Nath Pandey via szetszwo) + HADOOP-6367. Removes Access Token implementation from common. + (Kan Zhang via ddas) + OPTIMIZATIONS HADOOP-5595. NameNode does not need to run a replicator to choose a diff --git a/src/java/core-default.xml b/src/java/core-default.xml index dc77fd5c90417..9389ffb6e047b 100644 --- a/src/java/core-default.xml +++ b/src/java/core-default.xml @@ -269,29 +269,6 @@ Disk usage statistics refresh interval in msec. - - fs.access.token.enable - false - - If ""true"", access tokens are used as capabilities for accessing datanodes. - If ""false"", no access tokens are checked on accessing datanodes. - - - - - fs.access.key.update.interval - 600 - - Interval in minutes at which namenode updates its access keys. - - - - - fs.access.token.lifetime - 600 - The lifetime of access tokens in minutes. - - fs.s3.block.size 67108864 diff --git a/src/java/org/apache/hadoop/conf/Configuration.java b/src/java/org/apache/hadoop/conf/Configuration.java index e1b3be4f7b1ff..e12817b42f5b2 100644 --- a/src/java/org/apache/hadoop/conf/Configuration.java +++ b/src/java/org/apache/hadoop/conf/Configuration.java @@ -1757,12 +1757,6 @@ private static void addDeprecatedKeys() { new String[]{CommonConfigurationKeys.FS_CLIENT_BUFFER_DIR_KEY}); Configuration.addDeprecation(""hadoop.native.lib"", new String[]{CommonConfigurationKeys.IO_NATIVE_LIB_AVAILABLE_KEY}); - Configuration.addDeprecation(""dfs.access.token.enable"", - new String[]{CommonConfigurationKeys.FS_ACCESS_TOKEN_ENABLE_KEY}); - Configuration.addDeprecation(""dfs.access.key.update.interval"", - new String[]{CommonConfigurationKeys.FS_ACCESS_KEY_UPDATE_INTERVAL_KEY}); - Configuration.addDeprecation(""dfs.access.token.lifetime"", - new String[]{CommonConfigurationKeys.FS_ACCESS_TOKEN_LIFETIME_KEY}); Configuration.addDeprecation(""fs.default.name"", new String[]{CommonConfigurationKeys.FS_DEFAULT_NAME_KEY}); } diff --git a/src/java/org/apache/hadoop/fs/CommonConfigurationKeys.java b/src/java/org/apache/hadoop/fs/CommonConfigurationKeys.java index d721f5ed04a0c..5dcc2cb5ab133 100644 --- a/src/java/org/apache/hadoop/fs/CommonConfigurationKeys.java +++ b/src/java/org/apache/hadoop/fs/CommonConfigurationKeys.java @@ -43,15 +43,6 @@ public class CommonConfigurationKeys { public static final int FS_PERMISSIONS_UMASK_DEFAULT = 0022; public static final String FS_DF_INTERVAL_KEY = ""fs.df.interval""; public static final long FS_DF_INTERVAL_DEFAULT = 60000; - public static final String FS_ACCESS_TOKEN_ENABLE_KEY = - ""fs.access.token.enable""; - public static final boolean FS_ACCESS_TOKEN_ENABLE_DEFAULT = false; - public static final String FS_ACCESS_KEY_UPDATE_INTERVAL_KEY = - ""fs.access.key.update.interval""; - public static final long FS_ACCESS_KEY_UPDATE_INTERVAL_DEFAULT = 600; - public static final String FS_ACCESS_TOKEN_LIFETIME_KEY = - ""fs.access.token.lifetime""; - public static final long FS_ACCESS_TOKEN_LIFETIME_DEFAULT = 600; //Defaults are not specified for following keys diff --git a/src/java/org/apache/hadoop/security/AccessKey.java b/src/java/org/apache/hadoop/security/AccessKey.java deleted file mode 100644 index 81b6383381e22..0000000000000 --- a/src/java/org/apache/hadoop/security/AccessKey.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import javax.crypto.Mac; - -import org.apache.hadoop.io.Text; -import org.apache.hadoop.io.Writable; -import org.apache.hadoop.io.WritableUtils; - -/** - * Key used for generating and verifying access tokens - */ -public class AccessKey implements Writable { - private long keyID; - private Text key; - private long expiryDate; - private Mac mac; - - public AccessKey() { - this(0L, new Text(), 0L); - } - - public AccessKey(long keyID, Text key, long expiryDate) { - this.keyID = keyID; - this.key = key; - this.expiryDate = expiryDate; - } - - public long getKeyID() { - return keyID; - } - - public Text getKey() { - return key; - } - - public long getExpiryDate() { - return expiryDate; - } - - public Mac getMac() { - return mac; - } - - public void setMac(Mac mac) { - this.mac = mac; - } - - static boolean isEqual(Object a, Object b) { - return a == null ? b == null : a.equals(b); - } - - /** {@inheritDoc} */ - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof AccessKey) { - AccessKey that = (AccessKey) obj; - return this.keyID == that.keyID && isEqual(this.key, that.key) - && this.expiryDate == that.expiryDate; - } - return false; - } - - /** {@inheritDoc} */ - public int hashCode() { - return key == null ? 0 : key.hashCode(); - } - - // /////////////////////////////////////////////// - // Writable - // /////////////////////////////////////////////// - /** - */ - public void write(DataOutput out) throws IOException { - WritableUtils.writeVLong(out, keyID); - key.write(out); - WritableUtils.writeVLong(out, expiryDate); - } - - /** - */ - public void readFields(DataInput in) throws IOException { - keyID = WritableUtils.readVLong(in); - key.readFields(in); - expiryDate = WritableUtils.readVLong(in); - } -} \ No newline at end of file diff --git a/src/java/org/apache/hadoop/security/AccessToken.java b/src/java/org/apache/hadoop/security/AccessToken.java deleted file mode 100644 index 5a5d9a72f46cb..0000000000000 --- a/src/java/org/apache/hadoop/security/AccessToken.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import org.apache.hadoop.io.Text; -import org.apache.hadoop.io.Writable; - -public class AccessToken implements Writable { - public static final AccessToken DUMMY_TOKEN = new AccessToken(); - private Text tokenID; - private Text tokenAuthenticator; - - public AccessToken() { - this(new Text(), new Text()); - } - - public AccessToken(Text tokenID, Text tokenAuthenticator) { - this.tokenID = tokenID; - this.tokenAuthenticator = tokenAuthenticator; - } - - public Text getTokenID() { - return tokenID; - } - - public Text getTokenAuthenticator() { - return tokenAuthenticator; - } - - static boolean isEqual(Object a, Object b) { - return a == null ? b == null : a.equals(b); - } - - /** {@inheritDoc} */ - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof AccessToken) { - AccessToken that = (AccessToken) obj; - return isEqual(this.tokenID, that.tokenID) - && isEqual(this.tokenAuthenticator, that.tokenAuthenticator); - } - return false; - } - - /** {@inheritDoc} */ - public int hashCode() { - return tokenAuthenticator == null ? 0 : tokenAuthenticator.hashCode(); - } - - // /////////////////////////////////////////////// - // Writable - // /////////////////////////////////////////////// - /** - */ - public void write(DataOutput out) throws IOException { - tokenID.write(out); - tokenAuthenticator.write(out); - } - - /** - */ - public void readFields(DataInput in) throws IOException { - tokenID.readFields(in); - tokenAuthenticator.readFields(in); - } - -} \ No newline at end of file diff --git a/src/java/org/apache/hadoop/security/AccessTokenHandler.java b/src/java/org/apache/hadoop/security/AccessTokenHandler.java deleted file mode 100644 index 97166dcb9665f..0000000000000 --- a/src/java/org/apache/hadoop/security/AccessTokenHandler.java +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.security.GeneralSecurityException; -import java.security.SecureRandom; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.crypto.KeyGenerator; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.io.WritableUtils; -import org.apache.hadoop.fs.CommonConfigurationKeys; - -/** - * AccessTokenHandler can be instantiated in 2 modes, master mode and slave - * mode. Master can generate new access keys and export access keys to slaves, - * while slaves can only import and use access keys received from master. Both - * master and slave can generate and verify access tokens. Typically, master - * mode is used by NN and slave mode is used by DN. - */ -public class AccessTokenHandler { - private static final Log LOG = LogFactory.getLog(AccessTokenHandler.class); - public static final String STRING_ENABLE_ACCESS_TOKEN = - CommonConfigurationKeys.FS_ACCESS_TOKEN_ENABLE_KEY; - public static final String STRING_ACCESS_KEY_UPDATE_INTERVAL = - CommonConfigurationKeys.FS_ACCESS_KEY_UPDATE_INTERVAL_KEY; - public static final String STRING_ACCESS_TOKEN_LIFETIME = - CommonConfigurationKeys.FS_ACCESS_TOKEN_LIFETIME_KEY; - - - private final boolean isMaster; - /* - * keyUpdateInterval is the interval that NN updates its access keys. It - * should be set long enough so that all live DN's and Balancer should have - * sync'ed their access keys with NN at least once during each interval. - */ - private final long keyUpdateInterval; - private long tokenLifetime; - private long serialNo = new SecureRandom().nextLong(); - private KeyGenerator keyGen; - private AccessKey currentKey; - private AccessKey nextKey; - private Map allKeys; - - public static enum AccessMode { - READ, WRITE, COPY, REPLACE - }; - - /** - * Constructor - * - * @param isMaster - * @param keyUpdateInterval - * @param tokenLifetime - * @throws IOException - */ - public AccessTokenHandler(boolean isMaster, long keyUpdateInterval, - long tokenLifetime) throws IOException { - this.isMaster = isMaster; - this.keyUpdateInterval = keyUpdateInterval; - this.tokenLifetime = tokenLifetime; - this.allKeys = new HashMap(); - if (isMaster) { - try { - generateKeys(); - initMac(currentKey); - } catch (GeneralSecurityException e) { - throw (IOException) new IOException( - ""Failed to create AccessTokenHandler"").initCause(e); - } - } - } - - /** Initialize access keys */ - private synchronized void generateKeys() throws NoSuchAlgorithmException { - keyGen = KeyGenerator.getInstance(""HmacSHA1""); - /* - * Need to set estimated expiry dates for currentKey and nextKey so that if - * NN crashes, DN can still expire those keys. NN will stop using the newly - * generated currentKey after the first keyUpdateInterval, however it may - * still be used by DN and Balancer to generate new tokens before they get a - * chance to sync their keys with NN. Since we require keyUpdInterval to be - * long enough so that all live DN's and Balancer will sync their keys with - * NN at least once during the period, the estimated expiry date for - * currentKey is set to now() + 2 * keyUpdateInterval + tokenLifetime. - * Similarly, the estimated expiry date for nextKey is one keyUpdateInterval - * more. - */ - serialNo++; - currentKey = new AccessKey(serialNo, new Text(keyGen.generateKey() - .getEncoded()), System.currentTimeMillis() + 2 * keyUpdateInterval - + tokenLifetime); - serialNo++; - nextKey = new AccessKey(serialNo, new Text(keyGen.generateKey() - .getEncoded()), System.currentTimeMillis() + 3 * keyUpdateInterval - + tokenLifetime); - allKeys.put(currentKey.getKeyID(), currentKey); - allKeys.put(nextKey.getKeyID(), nextKey); - } - - /** Initialize Mac function */ - private synchronized void initMac(AccessKey key) throws IOException { - try { - Mac mac = Mac.getInstance(""HmacSHA1""); - mac.init(new SecretKeySpec(key.getKey().getBytes(), ""HmacSHA1"")); - key.setMac(mac); - } catch (GeneralSecurityException e) { - throw (IOException) new IOException( - ""Failed to initialize Mac for access key, keyID="" + key.getKeyID()) - .initCause(e); - } - } - - /** Export access keys, only to be used in master mode */ - public synchronized ExportedAccessKeys exportKeys() { - if (!isMaster) - return null; - if (LOG.isDebugEnabled()) - LOG.debug(""Exporting access keys""); - return new ExportedAccessKeys(true, keyUpdateInterval, tokenLifetime, - currentKey, allKeys.values().toArray(new AccessKey[0])); - } - - private synchronized void removeExpiredKeys() { - long now = System.currentTimeMillis(); - for (Iterator> it = allKeys.entrySet() - .iterator(); it.hasNext();) { - Map.Entry e = it.next(); - if (e.getValue().getExpiryDate() < now) { - it.remove(); - } - } - } - - /** - * Set access keys, only to be used in slave mode - */ - public synchronized void setKeys(ExportedAccessKeys exportedKeys) - throws IOException { - if (isMaster || exportedKeys == null) - return; - LOG.info(""Setting access keys""); - removeExpiredKeys(); - this.currentKey = exportedKeys.getCurrentKey(); - initMac(currentKey); - AccessKey[] receivedKeys = exportedKeys.getAllKeys(); - for (int i = 0; i < receivedKeys.length; i++) { - if (receivedKeys[i] == null) - continue; - this.allKeys.put(receivedKeys[i].getKeyID(), receivedKeys[i]); - } - } - - /** - * Update access keys, only to be used in master mode - */ - public synchronized void updateKeys() throws IOException { - if (!isMaster) - return; - LOG.info(""Updating access keys""); - removeExpiredKeys(); - // set final expiry date of retiring currentKey - allKeys.put(currentKey.getKeyID(), new AccessKey(currentKey.getKeyID(), - currentKey.getKey(), System.currentTimeMillis() + keyUpdateInterval - + tokenLifetime)); - // update the estimated expiry date of new currentKey - currentKey = new AccessKey(nextKey.getKeyID(), nextKey.getKey(), System - .currentTimeMillis() - + 2 * keyUpdateInterval + tokenLifetime); - initMac(currentKey); - allKeys.put(currentKey.getKeyID(), currentKey); - // generate a new nextKey - serialNo++; - nextKey = new AccessKey(serialNo, new Text(keyGen.generateKey() - .getEncoded()), System.currentTimeMillis() + 3 * keyUpdateInterval - + tokenLifetime); - allKeys.put(nextKey.getKeyID(), nextKey); - } - - /** Check if token is well formed */ - private synchronized boolean verifyToken(long keyID, AccessToken token) - throws IOException { - AccessKey key = allKeys.get(keyID); - if (key == null) { - LOG.warn(""Access key for keyID="" + keyID + "" doesn't exist.""); - return false; - } - if (key.getMac() == null) { - initMac(key); - } - Text tokenID = token.getTokenID(); - Text authenticator = new Text(key.getMac().doFinal(tokenID.getBytes())); - return authenticator.equals(token.getTokenAuthenticator()); - } - - /** Generate an access token for current user */ - public AccessToken generateToken(long blockID, EnumSet modes) - throws IOException { - UserGroupInformation ugi = UserGroupInformation.getCurrentUGI(); - String userID = (ugi == null ? null : ugi.getUserName()); - return generateToken(userID, blockID, modes); - } - - /** Generate an access token for a specified user */ - public synchronized AccessToken generateToken(String userID, long blockID, - EnumSet modes) throws IOException { - if (LOG.isDebugEnabled()) { - LOG.debug(""Generating access token for user="" + userID + "", blockID="" - + blockID + "", access modes="" + modes + "", keyID="" - + currentKey.getKeyID()); - } - if (modes == null || modes.isEmpty()) - throw new IOException(""access modes can't be null or empty""); - ByteArrayOutputStream buf = new ByteArrayOutputStream(4096); - DataOutputStream out = new DataOutputStream(buf); - WritableUtils.writeVLong(out, System.currentTimeMillis() + tokenLifetime); - WritableUtils.writeVLong(out, currentKey.getKeyID()); - WritableUtils.writeString(out, userID); - WritableUtils.writeVLong(out, blockID); - WritableUtils.writeVInt(out, modes.size()); - for (AccessMode aMode : modes) { - WritableUtils.writeEnum(out, aMode); - } - Text tokenID = new Text(buf.toByteArray()); - return new AccessToken(tokenID, new Text(currentKey.getMac().doFinal( - tokenID.getBytes()))); - } - - /** Check if access should be allowed. userID is not checked if null */ - public boolean checkAccess(AccessToken token, String userID, long blockID, - AccessMode mode) throws IOException { - long oExpiry = 0; - long oKeyID = 0; - String oUserID = null; - long oBlockID = 0; - EnumSet oModes = EnumSet.noneOf(AccessMode.class); - - try { - ByteArrayInputStream buf = new ByteArrayInputStream(token.getTokenID() - .getBytes()); - DataInputStream in = new DataInputStream(buf); - oExpiry = WritableUtils.readVLong(in); - oKeyID = WritableUtils.readVLong(in); - oUserID = WritableUtils.readString(in); - oBlockID = WritableUtils.readVLong(in); - int length = WritableUtils.readVInt(in); - for (int i = 0; i < length; ++i) { - oModes.add(WritableUtils.readEnum(in, AccessMode.class)); - } - } catch (IOException e) { - throw (IOException) new IOException( - ""Unable to parse access token for user="" + userID + "", blockID="" - + blockID + "", access mode="" + mode).initCause(e); - } - if (LOG.isDebugEnabled()) { - LOG.debug(""Verifying access token for user="" + userID + "", blockID="" - + blockID + "", access mode="" + mode + "", keyID="" + oKeyID); - } - return (userID == null || userID.equals(oUserID)) && oBlockID == blockID - && !isExpired(oExpiry) && oModes.contains(mode) - && verifyToken(oKeyID, token); - } - - private static boolean isExpired(long expiryDate) { - return System.currentTimeMillis() > expiryDate; - } - - /** check if a token is expired. for unit test only. - * return true when token is expired, false otherwise */ - static boolean isTokenExpired(AccessToken token) throws IOException { - ByteArrayInputStream buf = new ByteArrayInputStream(token.getTokenID() - .getBytes()); - DataInputStream in = new DataInputStream(buf); - long expiryDate = WritableUtils.readVLong(in); - return isExpired(expiryDate); - } - - /** set token lifetime. for unit test only */ - synchronized void setTokenLifetime(long tokenLifetime) { - this.tokenLifetime = tokenLifetime; - } -} diff --git a/src/java/org/apache/hadoop/security/ExportedAccessKeys.java b/src/java/org/apache/hadoop/security/ExportedAccessKeys.java deleted file mode 100644 index e5ab2934b4bc8..0000000000000 --- a/src/java/org/apache/hadoop/security/ExportedAccessKeys.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -import org.apache.hadoop.io.Writable; -import org.apache.hadoop.io.WritableFactories; -import org.apache.hadoop.io.WritableFactory; - -/** - * Object for passing access keys - */ -public class ExportedAccessKeys implements Writable { - public static final ExportedAccessKeys DUMMY_KEYS = new ExportedAccessKeys(); - private boolean isAccessTokenEnabled; - private long keyUpdateInterval; - private long tokenLifetime; - private AccessKey currentKey; - private AccessKey[] allKeys; - - public ExportedAccessKeys() { - this(false, 0, 0, new AccessKey(), new AccessKey[0]); - } - - ExportedAccessKeys(boolean isAccessTokenEnabled, long keyUpdateInterval, - long tokenLifetime, AccessKey currentKey, AccessKey[] allKeys) { - this.isAccessTokenEnabled = isAccessTokenEnabled; - this.keyUpdateInterval = keyUpdateInterval; - this.tokenLifetime = tokenLifetime; - this.currentKey = currentKey; - this.allKeys = allKeys; - } - - public boolean isAccessTokenEnabled() { - return isAccessTokenEnabled; - } - - public long getKeyUpdateInterval() { - return keyUpdateInterval; - } - - public long getTokenLifetime() { - return tokenLifetime; - } - - public AccessKey getCurrentKey() { - return currentKey; - } - - public AccessKey[] getAllKeys() { - return allKeys; - } - - static boolean isEqual(Object a, Object b) { - return a == null ? b == null : a.equals(b); - } - - /** {@inheritDoc} */ - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof ExportedAccessKeys) { - ExportedAccessKeys that = (ExportedAccessKeys) obj; - return this.isAccessTokenEnabled == that.isAccessTokenEnabled - && this.keyUpdateInterval == that.keyUpdateInterval - && this.tokenLifetime == that.tokenLifetime - && isEqual(this.currentKey, that.currentKey) - && Arrays.equals(this.allKeys, that.allKeys); - } - return false; - } - - /** {@inheritDoc} */ - public int hashCode() { - return currentKey == null ? 0 : currentKey.hashCode(); - } - - // /////////////////////////////////////////////// - // Writable - // /////////////////////////////////////////////// - static { // register a ctor - WritableFactories.setFactory(ExportedAccessKeys.class, - new WritableFactory() { - public Writable newInstance() { - return new ExportedAccessKeys(); - } - }); - } - - /** - */ - public void write(DataOutput out) throws IOException { - out.writeBoolean(isAccessTokenEnabled); - out.writeLong(keyUpdateInterval); - out.writeLong(tokenLifetime); - currentKey.write(out); - out.writeInt(allKeys.length); - for (int i = 0; i < allKeys.length; i++) { - allKeys[i].write(out); - } - } - - /** - */ - public void readFields(DataInput in) throws IOException { - isAccessTokenEnabled = in.readBoolean(); - keyUpdateInterval = in.readLong(); - tokenLifetime = in.readLong(); - currentKey.readFields(in); - this.allKeys = new AccessKey[in.readInt()]; - for (int i = 0; i < allKeys.length; i++) { - allKeys[i] = new AccessKey(); - allKeys[i].readFields(in); - } - } - -} \ No newline at end of file diff --git a/src/java/org/apache/hadoop/security/InvalidAccessTokenException.java b/src/java/org/apache/hadoop/security/InvalidAccessTokenException.java deleted file mode 100644 index eabce15ea3b13..0000000000000 --- a/src/java/org/apache/hadoop/security/InvalidAccessTokenException.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.IOException; - -/** - * Access token verification failed. - */ -public class InvalidAccessTokenException extends IOException { - private static final long serialVersionUID = 168L; - - public InvalidAccessTokenException() { - super(); - } - - public InvalidAccessTokenException(String msg) { - super(msg); - } -} diff --git a/src/test/core/org/apache/hadoop/security/SecurityTestUtil.java b/src/test/core/org/apache/hadoop/security/SecurityTestUtil.java deleted file mode 100644 index d6a30fcad10da..0000000000000 --- a/src/test/core/org/apache/hadoop/security/SecurityTestUtil.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.io.IOException; - -/** Utilities for security tests */ -public class SecurityTestUtil { - - /** - * check if an access token is expired. return true when token is expired, - * false otherwise - */ - public static boolean isAccessTokenExpired(AccessToken token) - throws IOException { - return AccessTokenHandler.isTokenExpired(token); - } - - /** - * set access token lifetime. - */ - public static void setAccessTokenLifetime(AccessTokenHandler handler, - long tokenLifetime) { - handler.setTokenLifetime(tokenLifetime); - } - -} diff --git a/src/test/core/org/apache/hadoop/security/TestAccessToken.java b/src/test/core/org/apache/hadoop/security/TestAccessToken.java deleted file mode 100644 index cd3cc4c482a9c..0000000000000 --- a/src/test/core/org/apache/hadoop/security/TestAccessToken.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.hadoop.security; - -import java.util.EnumSet; - -import org.apache.hadoop.io.TestWritable; - -import junit.framework.TestCase; - -/** Unit tests for access tokens */ -public class TestAccessToken extends TestCase { - long accessKeyUpdateInterval = 10 * 60 * 1000; // 10 mins - long accessTokenLifetime = 2 * 60 * 1000; // 2 mins - long blockID1 = 0L; - long blockID2 = 10L; - long blockID3 = -108L; - - /** test Writable */ - public void testWritable() throws Exception { - TestWritable.testWritable(ExportedAccessKeys.DUMMY_KEYS); - AccessTokenHandler handler = new AccessTokenHandler(true, - accessKeyUpdateInterval, accessTokenLifetime); - ExportedAccessKeys keys = handler.exportKeys(); - TestWritable.testWritable(keys); - TestWritable.testWritable(AccessToken.DUMMY_TOKEN); - AccessToken token = handler.generateToken(blockID3, EnumSet - .allOf(AccessTokenHandler.AccessMode.class)); - TestWritable.testWritable(token); - } - - private void tokenGenerationAndVerification(AccessTokenHandler master, - AccessTokenHandler slave) throws Exception { - // single-mode tokens - for (AccessTokenHandler.AccessMode mode : AccessTokenHandler.AccessMode - .values()) { - // generated by master - AccessToken token1 = master.generateToken(blockID1, EnumSet.of(mode)); - assertTrue(master.checkAccess(token1, null, blockID1, mode)); - assertTrue(slave.checkAccess(token1, null, blockID1, mode)); - // generated by slave - AccessToken token2 = slave.generateToken(blockID2, EnumSet.of(mode)); - assertTrue(master.checkAccess(token2, null, blockID2, mode)); - assertTrue(slave.checkAccess(token2, null, blockID2, mode)); - } - // multi-mode tokens - AccessToken mtoken = master.generateToken(blockID3, EnumSet - .allOf(AccessTokenHandler.AccessMode.class)); - for (AccessTokenHandler.AccessMode mode : AccessTokenHandler.AccessMode - .values()) { - assertTrue(master.checkAccess(mtoken, null, blockID3, mode)); - assertTrue(slave.checkAccess(mtoken, null, blockID3, mode)); - } - } - - /** test access key and token handling */ - public void testAccessTokenHandler() throws Exception { - AccessTokenHandler masterHandler = new AccessTokenHandler(true, - accessKeyUpdateInterval, accessTokenLifetime); - AccessTokenHandler slaveHandler = new AccessTokenHandler(false, - accessKeyUpdateInterval, accessTokenLifetime); - ExportedAccessKeys keys = masterHandler.exportKeys(); - slaveHandler.setKeys(keys); - tokenGenerationAndVerification(masterHandler, slaveHandler); - // key updating - masterHandler.updateKeys(); - tokenGenerationAndVerification(masterHandler, slaveHandler); - keys = masterHandler.exportKeys(); - slaveHandler.setKeys(keys); - tokenGenerationAndVerification(masterHandler, slaveHandler); - } - -}" 5787e2af06a377732f81cccb57b29a324875bb71,orientdb,"Support for not-logget Transactions by setting- OTransaction.setUsingLog(false). Default is true, so full compatibility is- guaranteed--",a,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java index 82285da83b5..3be98a9318d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordAbstract.java @@ -118,7 +118,7 @@ public byte[] toStream() { public ORecordAbstract fromStream(final byte[] iRecordBuffer) { _dirty = false; _source = iRecordBuffer; - _size = iRecordBuffer.length; + _size = iRecordBuffer != null ? iRecordBuffer.length : 0; _status = STATUS.LOADED; invokeListenerEvent(ORecordListener.EVENT.UNMARSHALL); diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java index 10146e58d4b..7997b3acecf 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalTxExecuter.java @@ -174,7 +174,7 @@ protected void commitAllPendingRecords(final int iRequesterId, final OTransactio if (tmpEntries.size() > 0) { for (OTransactionEntry txEntry : tmpEntries) // COMMIT ALL THE SINGLE ENTRIES ONE BY ONE - commitEntry(iRequesterId, iTx, txEntry); + commitEntry(iRequesterId, iTx, txEntry, iTx.isUsingLog()); allEntries.addAll(tmpEntries); tmpEntries.clear(); @@ -194,7 +194,8 @@ protected void rollback() { // TODO } - private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry) throws IOException { + private void commitEntry(final int iRequesterId, final OTransaction iTx, final OTransactionEntry txEntry, final boolean iUseLog) + throws IOException { if (txEntry.status != OTransactionEntry.DELETED && !txEntry.getRecord().isDirty()) return; @@ -215,46 +216,53 @@ private void commitEntry(final int iRequesterId, final OTransaction iTx, final O case OTransactionEntry.LOADED: break; - case OTransactionEntry.CREATED: + case OTransactionEntry.CREATED: { // CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD byte[] stream = txEntry.getRecord().toStream(); - if (rid.isNew()) { - if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord())) - // RECORD CHANGED: RE-STREAM IT - stream = txEntry.getRecord().toStream(); - - rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType()); - rid.clusterId = cluster.getId(); - - iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord()); + if (iUseLog) { + if (rid.isNew()) { + if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord())) + // RECORD CHANGED: RE-STREAM IT + stream = txEntry.getRecord().toStream(); + + rid.clusterPosition = createRecord(iRequesterId, iTx.getId(), cluster, stream, txEntry.getRecord().getRecordType()); + rid.clusterId = cluster.getId(); + + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord()); + } else { + txEntry.getRecord().setVersion( + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), + txEntry.getRecord().getRecordType())); + } } else { - txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry - .getRecord().getRecordType())); + iTx.getDatabase().getStorage().createRecord(cluster.getId(), stream, txEntry.getRecord().getRecordType()); } break; + } + + case OTransactionEntry.UPDATED: { + byte[] stream = txEntry.getRecord().toStream(); - case OTransactionEntry.UPDATED: if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord())) // RECORD CHANGED: RE-STREAM IT stream = txEntry.getRecord().toStream(); txEntry.getRecord().setVersion( - updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().toStream(), txEntry.getRecord() - .getVersion(), txEntry.getRecord().getRecordType())); + updateRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, stream, txEntry.getRecord().getVersion(), txEntry + .getRecord().getRecordType())); iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_UPDATE, txEntry.getRecord()); break; + } - case OTransactionEntry.DELETED: - if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord())) - // RECORD CHANGED: RE-STREAM IT - stream = txEntry.getRecord().toStream(); + case OTransactionEntry.DELETED: { + iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord()); deleteRecord(iRequesterId, iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().getVersion()); iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_DELETE, txEntry.getRecord()); + } break; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java index 25f498c6fe4..0aa11089fe0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransaction.java @@ -46,6 +46,10 @@ public enum TXSTATUS { public int getId(); + public boolean isUsingLog(); + + public void setUsingLog(boolean useLog); + public Iterable getEntries(); public List getEntriesByClass(String iClassName); diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java index 42203006e44..6a71398719e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionNoTx.java @@ -80,4 +80,11 @@ public int size() { public ORecordInternal getEntry(ORecordId rid) { return null; } + + public boolean isUsingLog() { + return false; + } + + public void setUsingLog(final boolean useLog) { + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java index baeba5b507b..90fbe801888 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java @@ -21,6 +21,8 @@ import com.orientechnologies.orient.core.storage.OStorageEmbedded; public class OTransactionOptimistic extends OTransactionRealAbstract { + private boolean usingLog = true; + public OTransactionOptimistic(final ODatabaseRecordTx iDatabase, final int iId) { super(iDatabase, iId); } @@ -101,12 +103,12 @@ private void addRecord(final ORecordInternal iRecord, final byte iStatus, fin final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (!rid.isValid()) { - // TODO: NEED IT FOR REAL? - // NEW RECORD: CHECK IF IT'S ALREADY IN - for (OTransactionEntry entry : entries.values()) { - if (entry.getRecord() == iRecord) - return; - } +// // TODO: NEED IT FOR REAL? +// // NEW RECORD: CHECK IF IT'S ALREADY IN +// for (OTransactionEntry entry : entries.values()) { +// if (entry.getRecord() == iRecord) +// return; +// } iRecord.onBeforeIdentityChanged(rid); @@ -165,4 +167,12 @@ private void addRecord(final ORecordInternal iRecord, final byte iStatus, fin public String toString() { return ""OTransactionOptimistic [id="" + id + "", status="" + status + "", entries="" + entries.size() + ""]""; } + + public boolean isUsingLog() { + return usingLog; + } + + public void setUsingLog(final boolean useLog) { + this.usingLog = useLog; + } }" cb1f286c45ca4c6599580551557a101d0836fe4f,intellij-community,"added ""Overloaded varargs method"" inspection--",a,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties index 0e84c3412a3f4..bdfce88dcf823 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties +++ b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties @@ -285,6 +285,7 @@ increment.decrement.display.name=Value of ++ or -- used nested.assignment.display.name=Nested assignment nested.assignment.problem.descriptor=Nested assignment #ref #loc overloaded.methods.with.same.number.parameters.display.name=Overloaded methods with same number of parameters +overloaded.vararg.method.display.name=Overloaded varargs method refused.bequest.display.name=Refused bequest reuse.of.local.variable.display.name=Reuse of local variable reuse.of.local.variable.split.quickfix=Split local variable @@ -1435,6 +1436,8 @@ indexof.replaceable.by.contains.display.name='.indexOf()' expression is replacea indexof.replaceable.by.contains.problem.descriptor=#ref can be replaced by ''{0}'' #loc replace.indexof.with.contains.quickfix=Replace '.indexOf()' with '.contains()' overloaded.methods.with.same.number.parameters.problem.descriptor=Multiple methods named #ref with the same number of parameters +overloaded.vararg.method.problem.descriptor=Overloaded varargs method #ref +overloaded.vararg.constructor.problem.descriptor=Overloaded varargs constructor #ref cached.number.constructor.call.display.name=Number constructor call with primitive argument cached.number.constructor.call.problem.descriptor=Number constructor call with primitive argument #ref #loc cached.number.constructor.call.quickfix=Replace with {0}.valueOf() call diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java b/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java index f1b2ff6dc13b5..e5c92109ae256 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java @@ -369,6 +369,7 @@ private void registerNamingInspections(){ m_inspectionClasses.add(ConfusingMainMethodInspection.class); m_inspectionClasses.add(UpperCaseFieldNameNotConstantInspection.class); m_inspectionClasses.add(DollarSignInNameInspection.class); + m_inspectionClasses.add(OverloadedVarargsMethodInspection.class); } private void registerControlFlowInspections() { diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java index 0bf2e4381b38c..b622560fe5eaf 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java @@ -26,7 +26,8 @@ public class OverloadedMethodsWithSameNumberOfParametersInspection extends MethodInspection { public String getDisplayName() { - return InspectionGadgetsBundle.message(""overloaded.methods.with.same.number.parameters.display.name""); + return InspectionGadgetsBundle.message( + ""overloaded.methods.with.same.number.parameters.display.name""); } public String getGroupDisplayName() { @@ -34,7 +35,8 @@ public String getGroupDisplayName() { } public String buildErrorString(PsiElement location) { - return InspectionGadgetsBundle.message(""overloaded.methods.with.same.number.parameters.problem.descriptor""); + return InspectionGadgetsBundle.message( + ""overloaded.methods.with.same.number.parameters.problem.descriptor""); } public BaseInspectionVisitor buildVisitor() { @@ -48,25 +50,19 @@ public void visitMethod(@NotNull PsiMethod method) { if (method.isConstructor()) { return; } - - final String methodName = method.getName(); - if (methodName == null) { - return; - } final int parameterCount = calculateParamCount(method); - final PsiClass aClass = method.getContainingClass(); if (aClass == null) { return; } - final PsiMethod[] methods = aClass.getMethods(); - for (PsiMethod method1 : methods) { - if(!method1.equals(method)) { - final String testMethName = method1.getName(); - - final int testParameterCount = calculateParamCount(method1); - if(testMethName != null && methodName.equals(testMethName) - && parameterCount == testParameterCount) { + final String methodName = method.getName(); + final PsiMethod[] sameNameMethods = + aClass.findMethodsByName(methodName, false); + for (PsiMethod sameNameMethod : sameNameMethods) { + if(!sameNameMethod.equals(method)) { + final int testParameterCount = + calculateParamCount(sameNameMethod); + if(parameterCount == testParameterCount) { registerMethodError(method); } } diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java new file mode 100644 index 0000000000000..a64ce1e2149b2 --- /dev/null +++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java @@ -0,0 +1,77 @@ +/** + * (c) 2004 Carp Technologies BV + * Hengelosestraat 705, 7521PA Enschede + * Created: Feb 22, 2006, 12:39:10 AM + */ +package com.siyeh.ig.naming; + +import com.siyeh.ig.MethodInspection; +import com.siyeh.ig.BaseInspectionVisitor; +import com.siyeh.InspectionGadgetsBundle; +import com.intellij.codeInsight.daemon.GroupNames; +import com.intellij.psi.*; +import org.jetbrains.annotations.NotNull; + +public class OverloadedVarargsMethodInspection extends MethodInspection { + + public String getDisplayName() { + return InspectionGadgetsBundle.message( + ""overloaded.vararg.method.display.name""); + } + + public String getGroupDisplayName() { + return GroupNames.NAMING_CONVENTIONS_GROUP_NAME; + } + + public String buildErrorString(PsiElement location) { + final PsiMethod element = (PsiMethod)location.getParent(); + if (element.isConstructor()) { + return InspectionGadgetsBundle.message( + ""overloaded.vararg.constructor.problem.descriptor""); + } else { + return InspectionGadgetsBundle.message( + ""overloaded.vararg.method.problem.descriptor""); + } + } + + public BaseInspectionVisitor buildVisitor() { + return new OverloadedVarargMethodVisitor(); + } + + private static class OverloadedVarargMethodVisitor + extends BaseInspectionVisitor { + + public void visitMethod(@NotNull PsiMethod method) { + if (!hasVarargParameter(method)) { + return; + } + final PsiClass aClass = method.getContainingClass(); + if (aClass == null) { + return; + } + final String methodName = method.getName(); + final PsiMethod[] sameNameMethods; + if (method.isConstructor()) { + sameNameMethods = aClass.findMethodsByName(methodName, false); + } else { + sameNameMethods = aClass.findMethodsByName(methodName, false); + } + for (PsiMethod sameNameMethod : sameNameMethods) { + if(!sameNameMethod.equals(method)) { + registerMethodError(method); + } + } + } + + private static boolean hasVarargParameter(PsiMethod method) { + final PsiParameterList parameterList = method.getParameterList(); + final PsiParameter[] parameters = parameterList.getParameters(); + if (parameters.length == 0) { + return false; + } + final PsiParameter lastParameter = + parameters[parameters.length - 1]; + return lastParameter.isVarArgs(); + } + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html b/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html new file mode 100644 index 0000000000000..d6a2e326922af --- /dev/null +++ b/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html @@ -0,0 +1,8 @@ + +
      + +This inspection reports vararg methods, when there are one or more other methods with the +same name present in a class. Overloaded varargs methods can be very confusing, +as it is often not clear which overloading gets called. +
      Powered by InspectionGadgets
      + \ No newline at end of file" acfbc75640d5eaeea7a2ba9329e32f9d1efaa649,ReactiveX-RxJava,Prevent direct instantiation of BlockingObservable- via no-arg constructor--- also questioning why to allow extending this and would like to make it a private constructor-,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java index 05e4c60ae4..3f572e7844 100644 --- a/rxjava-core/src/main/java/rx/observables/BlockingObservable.java +++ b/rxjava-core/src/main/java/rx/observables/BlockingObservable.java @@ -44,6 +44,18 @@ */ public class BlockingObservable extends Observable { + protected BlockingObservable(Func1, Subscription> onSubscribe) { + super(onSubscribe); + } + + /** + * Used to prevent public instantiation + */ + @SuppressWarnings(""unused"") + private BlockingObservable() { + // prevent public instantiation + } + public static BlockingObservable from(final Observable o) { return new BlockingObservable(new Func1, Subscription>() { @@ -330,10 +342,6 @@ public static Iterable toIterable(final Observable source) { return from(source).toIterable(); } - protected BlockingObservable(Func1, Subscription> onSubscribe) { - super(onSubscribe); - } - /** * Used for protecting against errors being thrown from Observer implementations and ensuring onNext/onError/onCompleted contract compliance. *

      " daab3db062b9b8cddbb653fedca91288cf5a0684,kotlin,Add WITH_RUNTIME and WITH_REFLECT directives to- box tests--Currently all tests in boxWithStdlib/ run with both runtime and reflection-included; eventually they'll be merged into box/ using these directives-,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt b/compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt similarity index 99% rename from compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt rename to compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt index b8e2bbdcfe356..45aae6043855e 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt +++ b/compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt @@ -41,4 +41,4 @@ fun box(): String { val test2: X> = J.test2() as X> return test2.p1 + test2.p2.value -} \ No newline at end of file +} diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt similarity index 97% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt index f120be87f6224..5ef83125dcb5a 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt similarity index 96% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt index 87a17ca3bd09c..b620b9318936a 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.KCallable import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt index cb99eb8129d0c..7046257bca3e8 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.KClass import kotlin.test.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt index a21e54b428757..22d1afefa3ac3 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertEquals diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt similarity index 94% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt index 2f989b02118d8..f485e0554fe10 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.* diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt similarity index 98% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt index c9133e2ec241f..bbd34af42b9a5 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.reflect.* import kotlin.test.assertTrue diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt similarity index 95% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt index 3f5912a3ab310..806258b30482f 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertEquals diff --git a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt b/compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt similarity index 91% rename from compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt rename to compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt index 48a845d11bd7e..a082834ed029d 100644 --- a/compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt +++ b/compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt @@ -1,4 +1,4 @@ -// NO_KOTLIN_REFLECT +// WITH_RUNTIME import kotlin.test.assertNotNull diff --git a/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt b/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt index 14960a71ce7fc..f68dda4d4b18e 100644 --- a/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt +++ b/compiler/testData/codegen/boxMultiFile/accessorForProtectedInvokeVirtual.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import test.A diff --git a/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt index 07b1bd2799a87..2915070b4c557 100644 --- a/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/callMultifileClassMemberFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt index f89f5ec7516d0..7f782c4f080cd 100644 --- a/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/callsToMultifileClassFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import a.* diff --git a/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt b/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt index adaa0963a20d1..369756176b40d 100644 --- a/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt +++ b/compiler/testData/codegen/boxMultiFile/constPropertyReferenceFromMultifileClass.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt import a.OK diff --git a/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt b/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt index 8bc0417184e4a..efdebe900ac5e 100644 --- a/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt +++ b/compiler/testData/codegen/boxMultiFile/inlineMultifileClassMemberFromOtherPackage.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/kt1515.kt b/compiler/testData/codegen/boxMultiFile/kt1515.kt index 7cd77d0374c90..90dfc5624f775 100644 --- a/compiler/testData/codegen/boxMultiFile/kt1515.kt +++ b/compiler/testData/codegen/boxMultiFile/kt1515.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package thispackage diff --git a/compiler/testData/codegen/boxMultiFile/kt5445.kt b/compiler/testData/codegen/boxMultiFile/kt5445.kt index 7b342adab2eaf..b8eb1bd4a7813 100644 --- a/compiler/testData/codegen/boxMultiFile/kt5445.kt +++ b/compiler/testData/codegen/boxMultiFile/kt5445.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test2 diff --git a/compiler/testData/codegen/boxMultiFile/kt5445_2.kt b/compiler/testData/codegen/boxMultiFile/kt5445_2.kt index 62def12b07f13..6d0bf0391a746 100644 --- a/compiler/testData/codegen/boxMultiFile/kt5445_2.kt +++ b/compiler/testData/codegen/boxMultiFile/kt5445_2.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test2 diff --git a/compiler/testData/codegen/boxMultiFile/mainInFiles.kt b/compiler/testData/codegen/boxMultiFile/mainInFiles.kt index c488f31116fec..229de1362cfa1 100644 --- a/compiler/testData/codegen/boxMultiFile/mainInFiles.kt +++ b/compiler/testData/codegen/boxMultiFile/mainInFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1.kt package test diff --git a/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt b/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt index 9030317f1a5d7..33b98e5aaf5e8 100644 --- a/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt +++ b/compiler/testData/codegen/boxMultiFile/multifileClassPartsInitialization.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: box.kt import a.* diff --git a/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt b/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt index 74bca491a4c8b..461b35bccb485 100644 --- a/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt +++ b/compiler/testData/codegen/boxMultiFile/samWrappersDifferentFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1/wrapped.kt fun getWrapped1(): Runnable { diff --git a/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt b/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt index f149e6819887b..0ce5c61c0b59e 100644 --- a/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt +++ b/compiler/testData/codegen/boxMultiFile/samePartNameDifferentFacades.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: 1/part.kt @file:JvmName(""Foo"") diff --git a/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt b/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt index 93f3efb978844..2d0bc40ed34c8 100644 --- a/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt +++ b/compiler/testData/codegen/boxWithJava/allWildcardsOnClass.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java public class JavaClass { diff --git a/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt b/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt index 032a68a65a157..21514c2a694a8 100644 --- a/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt +++ b/compiler/testData/codegen/boxWithJava/annotatedSamFunExpression.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt b/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt index 8dbebfd91bad3..9566ff0d9ec15 100644 --- a/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt +++ b/compiler/testData/codegen/boxWithJava/annotatedSamLambda.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt index 38ceb8c790201..ada2a274c2fd7 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/array.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class O {} @@ -16,7 +17,7 @@ annotation class Ann(val args: Array>) fun box(): String { val args = Test::class.java.getAnnotation(Ann::class.java).args - val argName1 = args[0].simpleName ?: ""fail 1"" - val argName2 = args[1].simpleName ?: ""fail 2"" + val argName1 = args[0].java.simpleName ?: ""fail 1"" + val argName2 = args[1].java.simpleName ?: ""fail 2"" return argName1 + argName2 } diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt index ba5d272def412..e8bbfe3c99a0a 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/basic.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class OK {} @@ -14,6 +15,6 @@ import kotlin.reflect.KClass annotation class Ann(val arg: KClass<*>) fun box(): String { - val argName = Test::class.java.getAnnotation(Ann::class.java).arg.simpleName ?: ""fail 1"" + val argName = Test::class.java.getAnnotation(Ann::class.java).arg.java.simpleName ?: ""fail 1"" return argName } diff --git a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt index e12a7817fcf81..15d218db5c0f6 100644 --- a/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt +++ b/compiler/testData/codegen/boxWithJava/annotationsWithKClass/vararg.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class O {} @@ -16,7 +17,7 @@ annotation class Ann(vararg val args: KClass<*>) fun box(): String { val args = Test::class.java.getAnnotation(Ann::class.java).args - val argName1 = args[0].simpleName ?: ""fail 1"" - val argName2 = args[1].simpleName ?: ""fail 2"" + val argName1 = args[0].java.simpleName ?: ""fail 1"" + val argName2 = args[1].java.simpleName ?: ""fail 2"" return argName1 + argName2 } diff --git a/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt b/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt index f7ccb51249c63..a05f02ea645ed 100644 --- a/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt +++ b/compiler/testData/codegen/boxWithJava/collections/irrelevantImplMutableListKotlin.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: A.java public class A extends AImpl implements java.util.List { diff --git a/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt b/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt index fac871fb05d5a..69f8ff0a32fb4 100644 --- a/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt +++ b/compiler/testData/codegen/boxWithJava/covariantOverrideWithDeclarationSiteProjection.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java public class JavaClass { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt b/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt index 887a1af5cc5ac..e1bd46360aa44 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/differentFiles.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt b/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt index d4db0df8d6039..f13f8a93d6b90 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/javaAnnotationOnFileFacade.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: StringHolder.java import java.lang.annotation.ElementType; diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt index fc240cd9899ee..240fccccd5656 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWith2Files.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt index 0a2e8bd496dd8..4186b62d558c3 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithCrossCall.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt index 3227619a9cc10..bc2c3db2f558a 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/multifileClassWithPrivate.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Baz.java public class Baz { diff --git a/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt b/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt index fd2feb7393abc..66b6bd3328602 100644 --- a/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt +++ b/compiler/testData/codegen/boxWithJava/fileClasses/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Bar.java public class Bar { diff --git a/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt b/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt index b2b9353b3df41..58bdad5fe98be 100644 --- a/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/interfaceCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: CompanionInitialization.java public class CompanionInitialization { diff --git a/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt b/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt index ea0ed56d7268f..250f764b41fe7 100644 --- a/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt +++ b/compiler/testData/codegen/boxWithJava/jvmField/constructorProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmField/simple.kt b/compiler/testData/codegen/boxWithJava/jvmField/simple.kt index 4112b0f189b81..f89b81c2fc20e 100644 --- a/compiler/testData/codegen/boxWithJava/jvmField/simple.kt +++ b/compiler/testData/codegen/boxWithJava/jvmField/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt b/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt index b63fe927dcd82..498a8b306de43 100644 --- a/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt +++ b/compiler/testData/codegen/boxWithJava/jvmOverloads/generics.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt b/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt index a03031975129a..9fff7ca10bb1a 100644 --- a/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt +++ b/compiler/testData/codegen/boxWithJava/jvmOverloads/simple.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java public class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt index dfbfe6702310c..dd1d45bb97d48 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/annotations.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java import java.lang.annotation.Annotation; diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt index 13d937d9b4bbd..e6aa00a607e8f 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/companionObject.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt index b25091ee2ed2a..b11acbd3d0f24 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/enumCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt b/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt index b4b84c3e15cc3..97d071d557de5 100644 --- a/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt +++ b/compiler/testData/codegen/boxWithJava/jvmStatic/object.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt b/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt index 12e90aca638ce..b1f09f9ea9547 100644 --- a/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt +++ b/compiler/testData/codegen/boxWithJava/properties/annotationWithKotlinProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaClass.java import java.lang.annotation.Retention; diff --git a/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt b/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt index 385f8a0896f51..035da13ca8032 100644 --- a/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt +++ b/compiler/testData/codegen/boxWithJava/properties/companionObjectProperties.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: Test.java class Test { diff --git a/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt b/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt index c6c0a16780a8a..a8cc18a55ff74 100644 --- a/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt +++ b/compiler/testData/codegen/boxWithJava/properties/protectedJavaProperty.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaBaseClass.java public class JavaBaseClass { diff --git a/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt b/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt index 99d6f8e15f3aa..6aff71b3d79e4 100644 --- a/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt +++ b/compiler/testData/codegen/boxWithJava/properties/protectedJavaPropertyInCompanion.kt @@ -1,3 +1,4 @@ +// WITH_RUNTIME // FILE: JavaBaseClass.java public class JavaBaseClass { diff --git a/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt b/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt index 4947956755a46..1ea9f687be462 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/annotationsOnJavaMembers.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java @Anno(""J"") diff --git a/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt index b02cf4892eb27..35f527ffa0255 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callInstanceJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt index 5ce51bff71a9d..4a28a0f9aa9dc 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callPrivateJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt b/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt index 9121ae15c5057..13de918f62822 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/callStaticJavaMethod.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt index 2260351e564f2..f1c2d8bdf424e 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedFunctions.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt index 1a21b4b0cd9af..c1880a4c91843 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/declaredVsInheritedProperties.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt b/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt index d7096212f8616..2843bacbab651 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java import kotlin.jvm.functions.Function2; diff --git a/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt b/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt index 8b06ce6459e7f..7dffd907ee142 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/javaClassGetFunctions.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt b/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt index 1f40ab18c87e4..d1ef881b8782d 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/javaStaticField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt b/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt index 8a08b664ab5e2..f71764acfc390 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/kotlinPropertyInheritedInJava.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J extends K { diff --git a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt index 16030d194a530..8cbbf6c6cf6c2 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaInstanceField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt index 3d853c18d6a92..9887e442c792a 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/mutatePrivateJavaStaticField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt b/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt index 4ccd0f612ec39..21a31878f02a2 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/nestedClasses.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt b/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt index ffd0b270986bd..7bde34e271db1 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/noConflictOnKotlinGetterAndJavaField.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt b/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt index 930dde99cb30c..6defc2359f771 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/parametersHaveNoNames.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt b/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt index 8980cd4d7abfd..2699bf83e0f6a 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/platformTypeNotEqualToKotlinType.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java public class J { diff --git a/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt b/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt index 89a5ab0403cea..f43a98c50f442 100644 --- a/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt +++ b/compiler/testData/codegen/boxWithJava/reflection/platformTypeToString.kt @@ -1,3 +1,4 @@ +// WITH_REFLECT // FILE: J.java import java.util.List; diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java b/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java index b3c7b2f0cef61..1857c048e69d8 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/AbstractBlackBoxCodegenTest.java @@ -51,6 +51,9 @@ import static org.jetbrains.kotlin.test.KotlinTestUtils.getAnnotationsJar; public abstract class AbstractBlackBoxCodegenTest extends CodegenTestCase { + private boolean addRuntime = false; + private boolean addReflect = false; + @Override protected void doMultiFileTest(@NotNull File wholeFile, @NotNull List files, @Nullable File javaFilesDir) throws Exception { TestJdkKind jdkKind = TestJdkKind.MOCK_JDK; @@ -59,18 +62,26 @@ protected void doMultiFileTest(@NotNull File wholeFile, @NotNull List if (InTextDirectivesUtils.isDirectiveDefined(file.content, ""FULL_JDK"")) { jdkKind = TestJdkKind.FULL_JDK; } - if (InTextDirectivesUtils.isDirectiveDefined(file.content, ""NO_KOTLIN_REFLECT"")) { - configurationKind = ConfigurationKind.NO_KOTLIN_REFLECT; + if (InTextDirectivesUtils.isDirectiveDefined(file.content, ""WITH_RUNTIME"")) { + addRuntime = true; + } + if (InTextDirectivesUtils.isDirectiveDefined(file.content, ""WITH_REFLECT"")) { + addReflect = true; } javacOptions.addAll(InTextDirectivesUtils.findListWithPrefixes(file.content, ""// JAVAC_OPTIONS:"")); } + configurationKind = + addReflect ? ConfigurationKind.ALL : + addRuntime ? ConfigurationKind.NO_KOTLIN_REFLECT : + ConfigurationKind.JDK_ONLY; + compileAndRun(files, javaFilesDir, jdkKind, javacOptions); } protected void doTestWithStdlib(@NotNull String filename) throws Exception { - configurationKind = ConfigurationKind.ALL; + addReflect = true; doTest(filename); } diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java index 076092aadccb6..4d1fc5d639290 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxCodegenTestGenerated.java @@ -7030,11 +7030,83 @@ public void testAllFilesPresentInReflection() throws Exception { KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""compiler/testData/codegen/box/reflection""), Pattern.compile(""^(.+)\\.kt$""), true); } + @TestMetadata(""defaultImplsGenericSignature.kt"") + public void testDefaultImplsGenericSignature() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/defaultImplsGenericSignature.kt""); + doTest(fileName); + } + @TestMetadata(""functionLiteralGenericSignature.kt"") public void testFunctionLiteralGenericSignature() throws Exception { String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/functionLiteralGenericSignature.kt""); doTest(fileName); } + + @TestMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect"") + @TestDataPath(""$PROJECT_ROOT"") + @RunWith(JUnit3RunnerWithInners.class) + public static class NoKotlinReflect extends AbstractBlackBoxCodegenTest { + public void testAllFilesPresentInNoKotlinReflect() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""compiler/testData/codegen/box/reflection/noKotlinReflect""), Pattern.compile(""^(.+)\\.kt$""), true); + } + + @TestMetadata(""javaClass.kt"") + public void testJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/javaClass.kt""); + doTest(fileName); + } + + @TestMetadata(""primitiveJavaClass.kt"") + public void testPrimitiveJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/primitiveJavaClass.kt""); + doTest(fileName); + } + + @TestMetadata(""propertyGetSetName.kt"") + public void testPropertyGetSetName() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/propertyGetSetName.kt""); + doTest(fileName); + } + + @TestMetadata(""propertyInstanceof.kt"") + public void testPropertyInstanceof() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/propertyInstanceof.kt""); + doTest(fileName); + } + + @TestMetadata(""reifiedTypeJavaClass.kt"") + public void testReifiedTypeJavaClass() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/reifiedTypeJavaClass.kt""); + doTest(fileName); + } + + @TestMetadata(""simpleClassLiterals.kt"") + public void testSimpleClassLiterals() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/simpleClassLiterals.kt""); + doTest(fileName); + } + + @TestMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny"") + @TestDataPath(""$PROJECT_ROOT"") + @RunWith(JUnit3RunnerWithInners.class) + public static class MethodsFromAny extends AbstractBlackBoxCodegenTest { + public void testAllFilesPresentInMethodsFromAny() throws Exception { + KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny""), Pattern.compile(""^(.+)\\.kt$""), true); + } + + @TestMetadata(""callableReferences.kt"") + public void testCallableReferences() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt""); + doTest(fileName); + } + + @TestMetadata(""classReference.kt"") + public void testClassReference() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/box/reflection/noKotlinReflect/methodsFromAny/classReference.kt""); + doTest(fileName); + } + } + } } @TestMetadata(""compiler/testData/codegen/box/regressions"") diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java index caf303962cc31..e9d7fa1f6a1d5 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithJavaCodegenTestGenerated.java @@ -601,12 +601,6 @@ public void testDeclaredVsInheritedProperties() throws Exception { doTest(fileName); } - @TestMetadata(""defaultImplsGenericSignature.kt"") - public void testDefaultImplsGenericSignature() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithJava/reflection/defaultImplsGenericSignature.kt""); - doTest(fileName); - } - @TestMetadata(""functionReferenceErasedToKFunction.kt"") public void testFunctionReferenceErasedToKFunction() throws Exception { String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithJava/reflection/functionReferenceErasedToKFunction.kt""); diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java index 27b99123016ef..9aaca3605e245 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/BlackBoxWithStdlibCodegenTestGenerated.java @@ -3786,12 +3786,6 @@ public void testCovariantOverride() throws Exception { doTestWithStdlib(fileName); } - @TestMetadata(""kt11121.kt"") - public void testKt11121() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt11121.kt""); - doTestWithStdlib(fileName); - } - @TestMetadata(""genericBackingFieldSignature.kt"") public void testGenericBackingFieldSignature() throws Exception { String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/genericBackingFieldSignature.kt""); @@ -3804,6 +3798,12 @@ public void testGenericMethodSignature() throws Exception { doTestWithStdlib(fileName); } + @TestMetadata(""kt11121.kt"") + public void testKt11121() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt11121.kt""); + doTestWithStdlib(fileName); + } + @TestMetadata(""kt5112.kt"") public void testKt5112() throws Exception { String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/genericSignature/kt5112.kt""); @@ -4153,72 +4153,6 @@ public void testTypeToString() throws Exception { } } - @TestMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect"") - @TestDataPath(""$PROJECT_ROOT"") - @RunWith(JUnit3RunnerWithInners.class) - public static class NoKotlinReflect extends AbstractBlackBoxCodegenTest { - public void testAllFilesPresentInNoKotlinReflect() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect""), Pattern.compile(""^(.+)\\.kt$""), true); - } - - @TestMetadata(""javaClass.kt"") - public void testJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/javaClass.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""primitiveJavaClass.kt"") - public void testPrimitiveJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/primitiveJavaClass.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""propertyGetSetName.kt"") - public void testPropertyGetSetName() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyGetSetName.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""propertyInstanceof.kt"") - public void testPropertyInstanceof() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/propertyInstanceof.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""reifiedTypeJavaClass.kt"") - public void testReifiedTypeJavaClass() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/reifiedTypeJavaClass.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""simpleClassLiterals.kt"") - public void testSimpleClassLiterals() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/simpleClassLiterals.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny"") - @TestDataPath(""$PROJECT_ROOT"") - @RunWith(JUnit3RunnerWithInners.class) - public static class MethodsFromAny extends AbstractBlackBoxCodegenTest { - public void testAllFilesPresentInMethodsFromAny() throws Exception { - KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny""), Pattern.compile(""^(.+)\\.kt$""), true); - } - - @TestMetadata(""callableReferences.kt"") - public void testCallableReferences() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/callableReferences.kt""); - doTestWithStdlib(fileName); - } - - @TestMetadata(""classReference.kt"") - public void testClassReference() throws Exception { - String fileName = KotlinTestUtils.navigationMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/noKotlinReflect/methodsFromAny/classReference.kt""); - doTestWithStdlib(fileName); - } - } - } - @TestMetadata(""compiler/testData/codegen/boxWithStdlib/reflection/parameters"") @TestDataPath(""$PROJECT_ROOT"") @RunWith(JUnit3RunnerWithInners.class)" 3a5efd71396f7febeee17b268071b5a07cba27c3,camel,CAMEL-4071 clean up the camel OSGi integration- test and load the karaf spring feature first--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1133394 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/tests/camel-itest-osgi/pom.xml b/tests/camel-itest-osgi/pom.xml index a1352a1716b4f..f6b8abc19f577 100644 --- a/tests/camel-itest-osgi/pom.xml +++ b/tests/camel-itest-osgi/pom.xml @@ -345,6 +345,7 @@ ${spring-version} + ${karaf-version} diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java index 8c9c2a2932c97..692426aa17002 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java @@ -72,39 +72,46 @@ protected void setThreadContextClassLoader() { } public static UrlReference getCamelKarafFeatureUrl() { - String springVersion = System.getProperty(""springVersion""); - System.out.println(""*** The spring version is "" + springVersion + "" ***""); - + String type = ""xml/features""; return mavenBundle().groupId(""org.apache.camel.karaf""). artifactId(""apache-camel"").versionAsInProject().type(type); } public static UrlReference getKarafFeatureUrl() { - String karafVersion = ""2.2.1""; + String karafVersion = System.getProperty(""karafVersion""); System.out.println(""*** The karaf version is "" + karafVersion + "" ***""); String type = ""xml/features""; return mavenBundle().groupId(""org.apache.karaf.assemblies.features""). artifactId(""standard"").version(karafVersion).type(type); } - - @Configuration - public static Option[] configure() throws Exception { + + public static Option[] getDefaultCamelKarafOptions() { Option[] options = combine( // Default karaf environment Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), + Helper.setLogLevel(""WARN"")), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test""), - + ""camel-core"", ""camel-spring"", ""camel-test""), + workingDirectory(""target/paxrunner/""), equinox(), felix()); + return options; + } + + @Configuration + public static Option[] configure() throws Exception { + Option[] options = combine( + getDefaultCamelKarafOptions()); // for remote debugging // vmOption(""-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5008""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java index 9cc421830c948..d6b6da8a274ba 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java @@ -18,7 +18,6 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,11 +25,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * @@ -70,17 +66,11 @@ public void configure() { @Configuration public static Option[] configure() throws Exception { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components + getDefaultCamelKarafOptions(), + + // using the features to install other camel components scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-ahc""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + ""camel-jetty"", ""camel-ahc"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java index 48a5708219c28..6be307e76766e 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java @@ -25,25 +25,15 @@ import org.apache.camel.Processor; import org.apache.camel.component.aws.s3.S3Constants; import org.apache.camel.component.mock.MockEndpoint; -import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.OptionUtils.combine; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; - @RunWith(JUnit4TestRunner.class) @Ignore(""Test fails"") -public class AwsS3IntegrationTest extends OSGiIntegrationSpringTestSupport { +public class AwsS3IntegrationTest extends AwsTestSupport { @EndpointInject(uri = ""mock:result"") private MockEndpoint result; @@ -109,22 +99,4 @@ private void assertResponseMessage(Message message) { assertEquals(""3a5c8b1ad448bca04584ecb55b836264"", message.getHeader(S3Constants.E_TAG)); assertNull(message.getHeader(S3Constants.VERSION_ID)); } - - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java index 7a5ec944a0cfc..c6adb7c93c858 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java @@ -41,7 +41,7 @@ import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) -public class AwsS3Test extends OSGiIntegrationSpringTestSupport { +public class AwsS3Test extends AwsTestSupport { @EndpointInject(uri = ""mock:result-s3"") private MockEndpoint result; @@ -108,21 +108,4 @@ private void assertResponseMessage(Message message) { assertNull(message.getHeader(S3Constants.VERSION_ID)); } - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java index 3be6631b863e8..68c9439be01ae 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java @@ -20,25 +20,15 @@ import org.apache.camel.ExchangePattern; import org.apache.camel.Processor; import org.apache.camel.component.aws.sns.SnsConstants; -import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.OptionUtils.combine; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; - @RunWith(JUnit4TestRunner.class) @Ignore(""Must be manually tested. Provide your own accessKey and secretKey in CamelIntegrationContext.xml!"") -public class AwsSnsIntegrationTest extends OSGiIntegrationSpringTestSupport { +public class AwsSnsIntegrationTest extends AwsTestSupport { @Override protected OsgiBundleXmlApplicationContext createApplicationContext() { @@ -69,21 +59,5 @@ public void process(Exchange exchange) throws Exception { assertNotNull(exchange.getOut().getHeader(SnsConstants.MESSAGE_ID)); } - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java index a9f08d891612d..1c601d647842e 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java @@ -36,7 +36,7 @@ import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) -public class AwsSnsTest extends OSGiIntegrationSpringTestSupport { +public class AwsSnsTest extends AwsTestSupport { @Override protected OsgiBundleXmlApplicationContext createApplicationContext() { @@ -66,22 +66,5 @@ public void process(Exchange exchange) throws Exception { assertEquals(""dcc8ce7a-7f18-4385-bedd-b97984b4363c"", exchange.getOut().getHeader(SnsConstants.MESSAGE_ID)); } - - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java index a6938b3829655..3b9288a88da0d 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java @@ -22,25 +22,15 @@ import org.apache.camel.Processor; import org.apache.camel.component.aws.sqs.SqsConstants; import org.apache.camel.component.mock.MockEndpoint; -import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.OptionUtils.combine; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; - @RunWith(JUnit4TestRunner.class) @Ignore(""Must be manually tested. Provide your own accessKey and secretKey in CamelIntegrationContext.xml!"") -public class AwsSqsIntegrationTest extends OSGiIntegrationSpringTestSupport { +public class AwsSqsIntegrationTest extends AwsTestSupport { @EndpointInject(uri = ""mock:result"") private MockEndpoint result; @@ -95,22 +85,4 @@ public void process(Exchange exchange) throws Exception { assertNotNull(exchange.getOut().getHeader(SqsConstants.MESSAGE_ID)); assertEquals(""6a1559560f67c5e7a7d5d838bf0272ee"", exchange.getOut().getHeader(SqsConstants.MD5_OF_BODY)); } - - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java index 1247a68cd05c6..9a8c5086f6f49 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java @@ -22,23 +22,14 @@ import org.apache.camel.Processor; import org.apache.camel.component.aws.sqs.SqsConstants; import org.apache.camel.component.mock.MockEndpoint; -import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.OptionUtils.combine; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) -public class AwsSqsTest extends OSGiIntegrationSpringTestSupport { +public class AwsSqsTest extends AwsTestSupport { @EndpointInject(uri = ""mock:result"") private MockEndpoint result; @@ -94,21 +85,5 @@ public void process(Exchange exchange) throws Exception { assertEquals(""6a1559560f67c5e7a7d5d838bf0272ee"", exchange.getOut().getHeader(SqsConstants.MD5_OF_BODY)); } - @Configuration - public static Option[] configure() { - Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), - workingDirectory(""target/paxrunner/""), - equinox(), - felix()); - - return options; - } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java new file mode 100644 index 0000000000000..629f41db6d05f --- /dev/null +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java @@ -0,0 +1,42 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.camel.itest.osgi.aws; + +import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.Configuration; +import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +import static org.ops4j.pax.exam.OptionUtils.combine; +import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; + + +public abstract class AwsTestSupport extends OSGiIntegrationSpringTestSupport { + + + @Configuration + public static Option[] configure() { + Option[] options = combine( + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-aws"")); + + return options; + } + +} diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java index bb50885b4eafd..4f90ea4175f3a 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java @@ -20,21 +20,16 @@ import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import org.ops4j.pax.swissbox.tinybundles.dp.Constants; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; -import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle; -import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.withBnd; + @RunWith(JUnit4TestRunner.class) public class BeanValidatorTest extends OSGiIntegrationTestSupport { @@ -64,23 +59,13 @@ public void process(Exchange exchange) throws Exception { Car createCar(String manufacturer, String licencePlate) { return new CarWithAnnotations(manufacturer, licencePlate); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-bean-validator""), - - workingDirectory(""target/paxrunner/""), - - equinox(), - felix()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-bean-validator"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java index 9b4e4d4e74242..75a20aa3bb782 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java @@ -91,6 +91,9 @@ public static Option[] configure() throws Exception { .set(Constants.BUNDLE_SYMBOLICNAME, BlueprintExplicitPropertiesRouteTest.class.getName()) .build()).noStart(), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-blueprint"", ""camel-test""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java index f2f7dfc9722ca..378875caa6467 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java @@ -90,6 +90,8 @@ public static Option[] configure() throws Exception { // install blueprint requirements mavenBundle(""org.apache.felix"", ""org.apache.felix.configadmin""), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-blueprint"", ""camel-test""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java index 6287094266775..b557b1f666b04 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java @@ -188,6 +188,8 @@ public static Option[] configure() throws Exception { .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") .build()).noStart(), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-blueprint"", ""camel-test"", ""camel-mail"", ""camel-jaxb"", ""camel-jms""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java index 0e6799657cfcf..1f6a27908d399 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java @@ -112,6 +112,9 @@ public static Option[] configure() throws Exception { .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle9"") .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") .build()).noStart(), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java index dacff6254d5d7..ba5d36c80c1c6 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java @@ -91,6 +91,9 @@ public static Option[] configure() throws Exception { .add(""org/apache/camel/itest/osgi/blueprint/example.vm"", OSGiBlueprintTestSupport.class.getResource(""example.vm"")) .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle20"") .build()).noStart(), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java index a2e39070aa0f3..1600985f58966 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java @@ -146,6 +146,9 @@ public static Option[] configure() throws Exception { .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle5"") .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") .build()).noStart(), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java index d1def0e19acf9..c1961004d98ee 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java @@ -86,6 +86,9 @@ public static Option[] configure() throws Exception { .add(""OSGI-INF/blueprint/test.xml"", OSGiBlueprintTestSupport.class.getResource(""blueprint-13.xml"")) .set(Constants.BUNDLE_SYMBOLICNAME, OSGiBlueprintHelloWorldTest.class.getName()) .build()).noStart(), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java index ddcd5c1a6d2f3..47b6e9539b32e 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java @@ -26,18 +26,14 @@ import org.apache.camel.component.cache.CacheEndpoint; import org.apache.camel.component.cache.CacheManagerFactory; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class CacheManagerFactoryRefTest extends OSGiIntegrationTestSupport { @@ -78,25 +74,16 @@ public void configure() { } }; } - + + + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax - // logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures( - getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); + return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java index 12a06c702fe40..4a82d52ffa909 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java @@ -26,18 +26,15 @@ import org.apache.camel.component.cache.CacheConstants; import org.apache.camel.component.cache.CacheManagerFactory; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + @RunWith(JUnit4TestRunner.class) public class CacheRoutesManagementTest extends OSGiIntegrationTestSupport { @@ -100,24 +97,14 @@ public void configure() { }; } + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax - // logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures( - getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); + return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java index 240ea6204226a..aef41d4f7bbdf 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java @@ -19,18 +19,14 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.cache.CacheConstants; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class CacheTest extends OSGiIntegrationTestSupport { @@ -66,19 +62,11 @@ public void configure() { @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java index 8fac6b558cee8..ef3df9dfef17a 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java @@ -20,6 +20,7 @@ import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; @@ -70,6 +71,9 @@ public static Option[] configure() throws Exception { // this is how you set the default log level when using pax // logging (logProfile) Helper.setLogLevel(""WARN"")), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install AMQ scanFeatures(""mvn:org.apache.activemq/activemq-karaf/5.5.0/xml/features"", diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java index 98a749a79f76d..69f41bca0b920 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java @@ -88,6 +88,9 @@ public static Option[] configure() throws Exception { Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java index 5f2c37a493f26..14e805cf3f88d 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java @@ -27,11 +27,10 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + /** * @version @@ -66,23 +65,14 @@ public void testDozer() throws Exception { assertMockEndpointsSatisfied(); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-dozer""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-dozer"")); + return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java index 7f22127e58a67..bd6bcbbb8bac1 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java @@ -18,7 +18,6 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,11 +25,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) @Ignore(""We need a test which runs on all platforms"") @@ -52,23 +48,15 @@ public void configure() { }; } - @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-exec""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-exec"")); return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java index d14d06ed1b218..bde59afb9f502 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java @@ -22,18 +22,14 @@ import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class FreemarkerTest extends OSGiIntegrationTestSupport { @@ -64,20 +60,14 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-freemarker""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-freemarker"")); return options; } + + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java index b4f48c1400b36..7a5a1b460e19f 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java @@ -62,6 +62,9 @@ public static Option[] configure() throws Exception { mavenBundle().groupId(""org.apache.ftpserver"").artifactId(""ftpserver-core"").version(""1.0.5""), mavenBundle().groupId(""org.apache.ftpserver"").artifactId(""ftplet-api"").version(""1.0.5""), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-ftp""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java index d575d3771b278..39e9346b42a16 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java @@ -19,18 +19,15 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + @RunWith(JUnit4TestRunner.class) public class GroovyTest extends OSGiIntegrationTestSupport { @@ -52,19 +49,11 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-groovy""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-groovy"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java index 8d25c4e8825c6..ff151bc9c603c 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java @@ -24,18 +24,14 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; import org.apache.camel.processor.aggregate.AggregationStrategy; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class HawtDBAggregateRouteTest extends OSGiIntegrationTestSupport { @@ -91,21 +87,13 @@ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { return oldExchange; } } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-hawtdb""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-hawtdb"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java index afe4473efd4bd..2c110c8a0a09d 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java @@ -29,11 +29,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class HL7DataFormatTest extends OSGiIntegrationTestSupport { @@ -105,22 +102,15 @@ private static String createHL7AsString() { body.append(line8); return body.toString(); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-hl7""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-hl7"")); + return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java index 61ba7e7c9dc94..a799df9982bdd 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java @@ -19,7 +19,6 @@ import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; @@ -27,12 +26,8 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class HL7MLLPCodecTest extends OSGiIntegrationSpringTestSupport implements Processor { @@ -63,25 +58,15 @@ public void process(Exchange exchange) throws Exception { String out = ""MSH|^~\\&|MYSENDER||||200701011539||ADR^A19||||123\rMSA|AA|123\n""; exchange.getOut().setBody(out); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-mina"", ""camel-hl7""), - - // add hl7 osgi bundle - mavenBundle().groupId(""http://hl7api.sourceforge.net/m2/!ca.uhn.hapi"").artifactId(""hapi-osgi-base"").version(""1.0.1""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-hl7"", ""camel-mina"")); + return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java index 988592314a132..49fa76f9a6daf 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java @@ -18,7 +18,6 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,11 +25,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * @@ -66,22 +62,14 @@ public void configure() { } }; } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-http""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jetty"", ""camel-http"")); + return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java index 9cb2dd9fb2d02..42c9835650bb1 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java @@ -18,7 +18,6 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,11 +25,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * @@ -66,23 +62,16 @@ public void configure() { } }; } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-http4""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-http4"", ""camel-jetty"")); + return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java index 9eec49769c45c..e6b5e38cd6fea 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java @@ -20,18 +20,14 @@ import org.apache.camel.component.jasypt.JasyptPropertiesParser; import org.apache.camel.component.properties.PropertiesComponent; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class JasyptTest extends OSGiIntegrationTestSupport { @@ -68,20 +64,13 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-jasypt""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jasypt"")); return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java index 75285698d0c89..2fc3cf5adfa1c 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java @@ -20,18 +20,14 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.converter.jaxb.JaxbDataFormat; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class JaxbDataFormatTest extends OSGiIntegrationTestSupport { @@ -58,24 +54,16 @@ public void testSendMessage() throws Exception { template.sendBodyAndHeader(""direct:start"", ""FOOBAR"", ""foo"", ""bar""); assertMockEndpointsSatisfied(); - } + } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java index be157a54c4ddf..d5d2f6bed1551 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java @@ -18,7 +18,6 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; @@ -26,11 +25,8 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class JaxbFallbackConverterSpringTest extends OSGiIntegrationSpringTestSupport { @@ -56,19 +52,11 @@ public void testSendMessage() throws Exception { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java index e6157f1946603..60886b780cc7e 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java @@ -19,18 +19,14 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class JaxbFallbackConverterTest extends OSGiIntegrationTestSupport { @@ -59,19 +55,11 @@ public void testSendMessage() throws Exception { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java index 5bfca0fb5b968..9a34c5aae2197 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java @@ -27,17 +27,13 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.ops4j.pax.swissbox.tinybundles.dp.Constants; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; - import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle; @RunWith(JUnit4TestRunner.class) -@Ignore(""TODO: fix me"") +//@Ignore(""TODO: fix me"") public class OSGiMulitJettyCamelContextsTest extends OSGiIntegrationTestSupport { @Test @@ -66,16 +62,13 @@ public void testStoppingJettyContext() throws Exception { response = template.requestBody(endpointURI, ""Hello World"", String.class); assertEquals(""response is "" , ""camelContext2"", response); } + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jetty""), + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jetty""), //set up the camel context bundle1 provision(newBundle().add(""META-INF/spring/CamelContext1.xml"", OSGiMulitJettyCamelContextsTest.class.getResource(""CamelContext1.xml"")) .add(JettyProcessor.class) @@ -89,15 +82,11 @@ public static Option[] configure() throws Exception { .add(JettyProcessor.class) .set(Constants.BUNDLE_SYMBOLICNAME, ""org.apache.camel.itest.osgi.CamelContextBundle2"") .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") - .set(Constants.BUNDLE_NAME, ""CamelContext2"").build()), - - - workingDirectory(""target/paxrunner/""), - - equinox(), - felix()); + .set(Constants.BUNDLE_NAME, ""CamelContext2"").build()) + ); return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java index c36dc687a6401..b3070effcfdc9 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java @@ -17,7 +17,6 @@ package org.apache.camel.itest.osgi.jms; import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; @@ -25,11 +24,8 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * @version @@ -54,21 +50,13 @@ public void testJms() throws Exception { @Configuration public static Option[] configure() throws Exception { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), + getDefaultCamelKarafOptions(), // using the features to install AMQ scanFeatures(""mvn:org.apache.activemq/activemq-karaf/5.4.0/xml/features"", ""activemq""), // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jms""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + scanFeatures(getCamelKarafFeatureUrl(), ""camel-jms"")); return options; } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java index 52ba5be5d7497..a5028c5f24538 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java @@ -132,7 +132,10 @@ public static Option[] configure() throws Exception { // Default karaf environment Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), + Helper.setLogLevel(""WARN"")), + + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jpa""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java index 5827694cc4d3d..e8d8e68cd7e9a 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java @@ -125,6 +125,9 @@ public static Option[] configure() throws Exception { Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-spring"", ""camel-test""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java index f6cb5d14ddd2d..4d1464b1db44d 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java @@ -18,18 +18,14 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class MinaTest extends OSGiIntegrationTestSupport { @@ -55,20 +51,13 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-mina""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-mina"")); return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java index 12f93145e98fc..25c3a510f2426 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java @@ -112,6 +112,9 @@ public static Option[] configure() throws Exception { // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + mavenBundle().groupId(""org.apache.derby"").artifactId(""derby"").version(""10.4.2.0""), // using the features to install the camel components diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java index 4eb4133756299..c4ef7e8d7216f 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java @@ -18,18 +18,14 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class NettyTest extends OSGiIntegrationTestSupport { @@ -55,20 +51,13 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-netty""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-netty"")); return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java index 865657568af06..fb4ca25bd4fd6 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java @@ -23,18 +23,14 @@ import org.apache.camel.dataformat.protobuf.ProtobufDataFormat; import org.apache.camel.dataformat.protobuf.generated.AddressBookProtos; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class ProtobufRouteTest extends OSGiIntegrationTestSupport { @@ -109,21 +105,13 @@ public void configure() throws Exception { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-protobuf""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-protobuf"")); return options; } - + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java index 365f09f602046..bb6ac7568670b 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java @@ -60,6 +60,9 @@ public static Option[] configure() throws Exception { Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), + // install the spring, http features first + scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-quartz""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java index 463deb5d5e4ce..1988b7174b60c 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java @@ -23,18 +23,14 @@ import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class RestletTest extends OSGiIntegrationTestSupport { @@ -63,22 +59,15 @@ public void process(Exchange exchange) throws Exception { } }; } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-restlet""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-restlet"")); + return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java index ebb5f917f0211..0812124f2576c 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java @@ -18,7 +18,6 @@ import org.apache.camel.Exchange; import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,11 +26,8 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * @version @@ -65,23 +61,16 @@ public void testGetDomain() throws Exception { assertEquals(""{www.google.com}"", response); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cxf"", ""camel-restlet""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-cxf"", ""camel-restlet"")); + return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java index 264c3fcb86604..2dec9d10e880e 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java @@ -26,18 +26,14 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.component.rss.RssConstants; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class RssPollingConsumerTest extends OSGiIntegrationTestSupport { @@ -76,21 +72,13 @@ public void configure() throws Exception { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-rss""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-rss"")); return options; } - + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java index 4349a469e4053..1a32b6c6b38e1 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java @@ -19,19 +19,16 @@ import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; + import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; + import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; /** * Test camel-script for groovy expressions in OSGi @@ -54,25 +51,14 @@ public void testLanguage() throws Exception { assertMockEndpointsSatisfied(); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-script""), - - mavenBundle().groupId(""org.apache.servicemix.bundles"").artifactId(""org.apache.servicemix.bundles.ant"").version(""1.7.0_3""), - mavenBundle().groupId(""org.codehaus.groovy"").artifactId(""groovy-all"").version(""1.7.9""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + scanFeatures(getCamelKarafFeatureUrl(), ""camel-script"", ""camel-groovy"")); return options; } + + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java index 052c8164f91cc..0e856e31b84d3 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java @@ -55,22 +55,15 @@ public void testSendMessage() throws Exception { template.sendBody(""direct:start"", ""Hello""); assertMockEndpointsSatisfied(); } - + @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-script"", ""camel-ruby""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-script"", ""camel-ruby"")); + return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java index 0c0a49ecb7b63..73767cb58d478 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java @@ -50,7 +50,7 @@ public static Option[] configure() throws Exception { Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), - Helper.loadKarafStandardFeatures(""http"", ""war""), + Helper.loadKarafStandardFeatures(""spring"", ""jetty"", ""http"", ""war""), // set the system property for pax web org.ops4j.pax.exam.CoreOptions.systemProperty(""org.osgi.service.http.port"").value(""9080""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java index 715323449bb3e..2013ffb86662b 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java @@ -49,7 +49,7 @@ public static Option[] configure() throws Exception { Helper.getDefaultOptions( // this is how you set the default log level when using pax logging (logProfile) Helper.setLogLevel(""WARN"")), - Helper.loadKarafStandardFeatures(""http"", ""war""), + Helper.loadKarafStandardFeatures(""spring"", ""http"", ""war""), // set the system property for pax web org.ops4j.pax.exam.CoreOptions.systemProperty(""org.osgi.service.http.port"").value(""9080""), diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java index 020c74a637375..e4ecf73b5e514 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java @@ -26,7 +26,6 @@ import org.apache.camel.component.shiro.security.ShiroSecurityToken; import org.apache.camel.component.shiro.security.ShiroSecurityTokenInjector; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; @@ -36,11 +35,8 @@ import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class ShiroAuthenticationTest extends OSGiIntegrationTestSupport { @@ -88,24 +84,15 @@ public void testSuccessfulShiroAuthenticationWithNoAuthorization() throws Except } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-shiro""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-shiro"")); return options; } - - + protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java index 526a968165717..d3e312eea7295 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java @@ -52,22 +52,14 @@ public void configure() { } }; } - @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-test"", ""camel-stream""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-stream"")); return options; } + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java index 03e12ab9f1998..e1f3cf4f5cfd4 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java @@ -30,7 +30,6 @@ import org.apache.camel.component.syslog.SyslogMessage; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; import org.apache.camel.spi.DataFormat; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; @@ -38,11 +37,9 @@ import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + @RunWith(JUnit4TestRunner.class) public class SyslogTest extends OSGiIntegrationTestSupport { @@ -100,19 +97,13 @@ public void process(Exchange ex) { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-test"", ""camel-mina"", ""camel-syslog""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); - + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-mina"", ""camel-syslog"")); + return options; } + } diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java index 2300a3d7c3fb2..7ba634af94c9b 100644 --- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java +++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java @@ -22,18 +22,14 @@ import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; -import org.apache.karaf.testing.Helper; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; -import static org.ops4j.pax.exam.CoreOptions.equinox; -import static org.ops4j.pax.exam.CoreOptions.felix; import static org.ops4j.pax.exam.OptionUtils.combine; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; -import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; @RunWith(JUnit4TestRunner.class) public class VelocityTest extends OSGiIntegrationTestSupport { @@ -65,20 +61,14 @@ public void configure() { } @Configuration - public static Option[] configure() throws Exception { + public static Option[] configure() { Option[] options = combine( - // Default karaf environment - Helper.getDefaultOptions( - // this is how you set the default log level when using pax logging (logProfile) - Helper.setLogLevel(""WARN"")), - // using the features to install the camel components - scanFeatures(getCamelKarafFeatureUrl(), - ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-velocity""), - - workingDirectory(""target/paxrunner/""), - - felix(), equinox()); + getDefaultCamelKarafOptions(), + // using the features to install the other camel components + scanFeatures(getCamelKarafFeatureUrl(), ""camel-velocity"")); return options; } + + } \ No newline at end of file diff --git a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml index f47d175222b5e..49e4097ef3525 100644 --- a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml +++ b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml @@ -29,7 +29,7 @@ - + diff --git a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml index de47fc04df34c..f8c0387eb636f 100644 --- a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml +++ b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml @@ -29,7 +29,7 @@ - + " d54477c34b1643fb68539bf6c235dc001582ec9c,intellij-community,Maven: test fixed by removing unnecessary and- obsolete assertion--,c,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java index 5c1fdbead33a3..7117306ba4430 100644 --- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java +++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/compiler/ResourceFilteringTest.java @@ -15,7 +15,6 @@ */ package org.jetbrains.idea.maven.compiler; -import com.intellij.compiler.CompilerConfiguration; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.fileTypes.FileTypeManager; @@ -911,7 +910,6 @@ public void testCustomEscapingFiltering() throws Exception { } public void testDoNotFilterButCopyBigFiles() throws Exception { - assertFalse(CompilerConfiguration.getInstance(myProject).isResourceFile(""file.xyz"")); assertEquals(FileTypeManager.getInstance().getFileTypeByFileName(""file.xyz""), FileTypes.UNKNOWN); createProjectSubFile(""resources/file.xyz"").setBinaryContent(new byte[1024 * 1024 * 20]);" b3bab12e6135d7c792c297d6f46b032ce496c18d,intellij-community,IDEA-80573 GitCheckoutOperation: sleep a bit to- let file watcher report all changes for small repositories where refresh is- too fast.--,c,https://github.com/JetBrains/intellij-community,"diff --git a/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java b/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java index e3530b19e040f..7eda20eda6871 100644 --- a/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java +++ b/plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java @@ -231,8 +231,22 @@ private boolean checkoutOrNotify(@NotNull List repositories, private static void refresh(GitRepository... repositories) { for (GitRepository repository : repositories) { + // If repository is small, everything can happen so fast, that FileWatcher wouldn't report the change before refresh() handles it. + // Performing a fair total refresh would be an overhead, so just waiting a bit to let file watcher report the change. + // This is a hack, but other solutions would be either performance or programming overhead. + // See http://youtrack.jetbrains.com/issue/IDEA-80573 + sleepABit(); refreshRoot(repository); // repository state will be auto-updated with this VFS refresh => no need to call GitRepository#update(). } } + + private static void sleepABit() { + try { + Thread.sleep(50); + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + } }" bcd1a596f2a4fa0e244c2f31c9256b078c1bfdf6,restlet-framework-java, - Fixed connection closing regression--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java index 0dfbd1fb0e..e2335b6619 100644 --- a/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java +++ b/modules/org.restlet/src/org/restlet/engine/connector/ConnectionController.java @@ -83,9 +83,6 @@ protected void controlConnections() throws IOException { // Close connections or register interest in NIO operations for (Connection conn : getHelper().getConnections()) { if (conn.getState() == ConnectionState.CLOSED) { - // Make sure that the registration is removed from the selector - getUpdatedRegistrations().add(conn.getRegistration()); - // Detach the connection and collect it getHelper().getConnections().remove(conn); getHelper().checkin(conn);" a3ecc3b910aa3bbc3ede2b8ba1bd040d02a26ca8,hadoop,HDFS-4733. Make HttpFS username pattern- configurable. Contributed by Alejandro Abdelnur.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1477241 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java index d217322b6ae89..1410b8b8cdfce 100644 --- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java @@ -193,7 +193,7 @@ public static class DoAsParam extends StringParam { * Constructor. */ public DoAsParam() { - super(NAME, null, UserProvider.USER_PATTERN); + super(NAME, null, UserProvider.getUserPattern()); } /** @@ -248,7 +248,7 @@ public static class GroupParam extends StringParam { * Constructor. */ public GroupParam() { - super(NAME, null, UserProvider.USER_PATTERN); + super(NAME, null, UserProvider.getUserPattern()); } } @@ -344,7 +344,7 @@ public static class OwnerParam extends StringParam { * Constructor. */ public OwnerParam() { - super(NAME, null, UserProvider.USER_PATTERN); + super(NAME, null, UserProvider.getUserPattern()); } } diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java index 440d7c9702b0c..f8e53d4bb3adf 100644 --- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java @@ -24,6 +24,7 @@ import org.apache.hadoop.lib.server.ServerException; import org.apache.hadoop.lib.service.FileSystemAccess; import org.apache.hadoop.lib.servlet.ServerWebApp; +import org.apache.hadoop.lib.wsrs.UserProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -102,6 +103,9 @@ public void init() throws ServerException { LOG.info(""Connects to Namenode [{}]"", get().get(FileSystemAccess.class).getFileSystemConfiguration(). get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY)); + String userPattern = getConfig().get(UserProvider.USER_PATTERN_KEY, + UserProvider.USER_PATTERN_DEFAULT); + UserProvider.setUserPattern(userPattern); } /** diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java index fd59b19dc3443..cd1cfc7f4ef27 100644 --- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java @@ -41,12 +41,27 @@ public class UserProvider extends AbstractHttpContextInjectable imple public static final String USER_NAME_PARAM = ""user.name""; - public static final Pattern USER_PATTERN = Pattern.compile(""^[A-Za-z_][A-Za-z0-9._-]*[$]?$""); + + public static final String USER_PATTERN_KEY + = ""httpfs.user.provider.user.pattern""; + + public static final String USER_PATTERN_DEFAULT + = ""^[A-Za-z_][A-Za-z0-9._-]*[$]?$""; + + private static Pattern userPattern = Pattern.compile(USER_PATTERN_DEFAULT); + + public static void setUserPattern(String pattern) { + userPattern = Pattern.compile(pattern); + } + + public static Pattern getUserPattern() { + return userPattern; + } static class UserParam extends StringParam { public UserParam(String user) { - super(USER_NAME_PARAM, user, USER_PATTERN); + super(USER_NAME_PARAM, user, getUserPattern()); } @Override diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml index 7171d388fe9ee..87cd73020d151 100644 --- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml @@ -226,4 +226,12 @@ + + httpfs.user.provider.user.pattern + ^[A-Za-z_][A-Za-z0-9._-]*[$]?$ + + Valid pattern for user and group names, it must be a valid java regex. + + + diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java new file mode 100644 index 0000000000000..e8407fc30cd80 --- /dev/null +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java @@ -0,0 +1,94 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.fs.http.server; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.CommonConfigurationKeysPublic; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.fs.http.client.HttpFSKerberosAuthenticator; +import org.apache.hadoop.lib.server.Service; +import org.apache.hadoop.lib.server.ServiceException; +import org.apache.hadoop.lib.service.Groups; +import org.apache.hadoop.lib.wsrs.UserProvider; +import org.apache.hadoop.security.authentication.client.AuthenticatedURL; +import org.apache.hadoop.security.authentication.server.AuthenticationToken; +import org.apache.hadoop.security.authentication.util.Signer; +import org.apache.hadoop.test.HFSTestCase; +import org.apache.hadoop.test.HadoopUsersConfTestHelper; +import org.apache.hadoop.test.TestDir; +import org.apache.hadoop.test.TestDirHelper; +import org.apache.hadoop.test.TestHdfs; +import org.apache.hadoop.test.TestHdfsHelper; +import org.apache.hadoop.test.TestJetty; +import org.apache.hadoop.test.TestJettyHelper; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.junit.Assert; +import org.junit.Test; +import org.mortbay.jetty.Server; +import org.mortbay.jetty.webapp.WebAppContext; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Writer; +import java.net.HttpURLConnection; +import java.net.URL; +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.List; + +public class TestHttpFSCustomUserName extends HFSTestCase { + + @Test + @TestDir + @TestJetty + public void defaultUserName() throws Exception { + String dir = TestDirHelper.getTestDir().getAbsolutePath(); + + Configuration httpfsConf = new Configuration(false); + HttpFSServerWebApp server = + new HttpFSServerWebApp(dir, dir, dir, dir, httpfsConf); + server.init(); + Assert.assertEquals(UserProvider.USER_PATTERN_DEFAULT, + UserProvider.getUserPattern().pattern()); + server.destroy(); + } + + @Test + @TestDir + @TestJetty + public void customUserName() throws Exception { + String dir = TestDirHelper.getTestDir().getAbsolutePath(); + + Configuration httpfsConf = new Configuration(false); + httpfsConf.set(UserProvider.USER_PATTERN_KEY, ""1""); + HttpFSServerWebApp server = + new HttpFSServerWebApp(dir, dir, dir, dir, httpfsConf); + server.init(); + Assert.assertEquals(""1"", UserProvider.getUserPattern().pattern()); + server.destroy(); + } + +} diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java index 694e8dc3185bd..e8942fbe4ef75 100644 --- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java +++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java @@ -104,34 +104,39 @@ public void getters() { @Test @TestException(exception = IllegalArgumentException.class) public void userNameEmpty() { - UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); - userParam.parseParam(""""); + new UserProvider.UserParam(""""); } @Test @TestException(exception = IllegalArgumentException.class) public void userNameInvalidStart() { - UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); - userParam.parseParam(""1x""); + new UserProvider.UserParam(""1x""); } @Test @TestException(exception = IllegalArgumentException.class) public void userNameInvalidDollarSign() { - UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); - userParam.parseParam(""1$x""); + new UserProvider.UserParam(""1$x""); } @Test public void userNameMinLength() { - UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); - assertNotNull(userParam.parseParam(""a"")); + new UserProvider.UserParam(""a""); } @Test public void userNameValidDollarSign() { - UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); - assertNotNull(userParam.parseParam(""a$"")); + new UserProvider.UserParam(""a$""); + } + + @Test + public void customUserPattern() { + try { + UserProvider.setUserPattern(""1""); + new UserProvider.UserParam(""1""); + } finally { + UserProvider.setUserPattern(UserProvider.USER_PATTERN_DEFAULT); + } } }" 8b9fdf23e2196dce9c956ba9088dd9b3146be60c,camel,CAMEL-4244 Add ThreadPoolProfileBuilder and- change ThreadPoolFactory to use the ThreadPoolProfile--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1159342 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java new file mode 100644 index 0000000000000..8f3af7e1d17d9 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java @@ -0,0 +1,86 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.builder; + +import java.util.concurrent.TimeUnit; + +import org.apache.camel.ThreadPoolRejectedPolicy; +import org.apache.camel.spi.ThreadPoolProfile; + +public class ThreadPoolProfileBuilder { + private final ThreadPoolProfile profile; + + public ThreadPoolProfileBuilder(String id) { + this.profile = new ThreadPoolProfile(id); + } + + public ThreadPoolProfileBuilder(String id, ThreadPoolProfile origProfile) { + this.profile = origProfile.clone(); + this.profile.setId(id); + } + + public ThreadPoolProfileBuilder defaultProfile(Boolean defaultProfile) { + this.profile.setDefaultProfile(defaultProfile); + return this; + } + + + public ThreadPoolProfileBuilder poolSize(Integer poolSize) { + profile.setPoolSize(poolSize); + return this; + } + + public ThreadPoolProfileBuilder maxPoolSize(Integer maxPoolSize) { + profile.setMaxPoolSize(maxPoolSize); + return this; + } + + public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime, TimeUnit timeUnit) { + profile.setKeepAliveTime(keepAliveTime); + profile.setTimeUnit(timeUnit); + return this; + } + + public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime) { + profile.setKeepAliveTime(keepAliveTime); + return this; + } + + public ThreadPoolProfileBuilder maxQueueSize(Integer maxQueueSize) { + if (maxQueueSize != null) { + profile.setMaxQueueSize(maxQueueSize); + } + return this; + } + + public ThreadPoolProfileBuilder rejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) { + profile.setRejectedPolicy(rejectedPolicy); + return this; + } + + /** + * Builds the new thread pool + * + * @return the created thread pool + * @throws Exception is thrown if error building the thread pool + */ + public ThreadPoolProfile build() { + return profile; + } + + +} diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java index fe2f4e0907ff4..f874a7b6360c4 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java @@ -22,7 +22,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -30,6 +29,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.ThreadPoolRejectedPolicy; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.model.OptionalIdentifiedDefinition; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ProcessorDefinitionHelper; @@ -56,21 +56,20 @@ public class DefaultExecutorServiceManager extends ServiceSupport implements Exe private String threadNamePattern; private String defaultThreadPoolProfileId = ""defaultThreadPoolProfile""; private final Map threadPoolProfiles = new HashMap(); + private ThreadPoolProfile builtIndefaultProfile; public DefaultExecutorServiceManager(CamelContext camelContext) { this.camelContext = camelContext; - // create and register the default profile - ThreadPoolProfile defaultProfile = new ThreadPoolProfile(defaultThreadPoolProfileId); - // the default profile has the following values - defaultProfile.setDefaultProfile(true); - defaultProfile.setPoolSize(10); - defaultProfile.setMaxPoolSize(20); - defaultProfile.setKeepAliveTime(60L); - defaultProfile.setTimeUnit(TimeUnit.SECONDS); - defaultProfile.setMaxQueueSize(1000); - defaultProfile.setRejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns); - registerThreadPoolProfile(defaultProfile); + builtIndefaultProfile = new ThreadPoolProfileBuilder(defaultThreadPoolProfileId) + .defaultProfile(true) + .poolSize(10) + .maxPoolSize(20) + .keepAliveTime(60L, TimeUnit.SECONDS) + .maxQueueSize(1000) + .rejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns) + .build(); + registerThreadPoolProfile(builtIndefaultProfile); } @Override @@ -102,46 +101,12 @@ public ThreadPoolProfile getDefaultThreadPoolProfile() { @Override public void setDefaultThreadPoolProfile(ThreadPoolProfile defaultThreadPoolProfile) { - ThreadPoolProfile oldProfile = threadPoolProfiles.remove(defaultThreadPoolProfileId); - if (oldProfile != null) { - // the old is no longer default - oldProfile.setDefaultProfile(false); - - // fallback and use old default values for new default profile if absent (convention over configuration) - if (defaultThreadPoolProfile.getKeepAliveTime() == null) { - defaultThreadPoolProfile.setKeepAliveTime(oldProfile.getKeepAliveTime()); - } - if (defaultThreadPoolProfile.getMaxPoolSize() == null) { - defaultThreadPoolProfile.setMaxPoolSize(oldProfile.getMaxPoolSize()); - } - if (defaultThreadPoolProfile.getRejectedPolicy() == null) { - defaultThreadPoolProfile.setRejectedPolicy(oldProfile.getRejectedPolicy()); - } - if (defaultThreadPoolProfile.getMaxQueueSize() == null) { - defaultThreadPoolProfile.setMaxQueueSize(oldProfile.getMaxQueueSize()); - } - if (defaultThreadPoolProfile.getPoolSize() == null) { - defaultThreadPoolProfile.setPoolSize(oldProfile.getPoolSize()); - } - if (defaultThreadPoolProfile.getTimeUnit() == null) { - defaultThreadPoolProfile.setTimeUnit(oldProfile.getTimeUnit()); - } - } - - // validate that all options has been given as its mandatory for a default thread pool profile - // as it is used as fallback for other profiles if they do not have that particular value - ObjectHelper.notEmpty(defaultThreadPoolProfile.getId(), ""id"", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getKeepAliveTime(), ""keepAliveTime"", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getMaxPoolSize(), ""maxPoolSize"", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getMaxQueueSize(), ""maxQueueSize"", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getPoolSize(), ""poolSize"", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getTimeUnit(), ""timeUnit"", defaultThreadPoolProfile); + threadPoolProfiles.remove(defaultThreadPoolProfileId); + defaultThreadPoolProfile.addDefaults(builtIndefaultProfile); LOG.info(""Using custom DefaultThreadPoolProfile: "" + defaultThreadPoolProfile); - // and replace with the new default profile this.defaultThreadPoolProfileId = defaultThreadPoolProfile.getId(); - // and mark the new profile as default defaultThreadPoolProfile.setDefaultProfile(true); registerThreadPoolProfile(defaultThreadPoolProfile); } @@ -170,12 +135,7 @@ public ExecutorService newDefaultThreadPool(Object source, String name) { @Override public ScheduledExecutorService newDefaultScheduledThreadPool(Object source, String name) { - ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - - ThreadFactory threadFactory = createThreadFactory(name, true); - ScheduledExecutorService executorService = threadPoolFactory.newScheduledThreadPool(defaultProfile.getPoolSize(), threadFactory); - onThreadPoolCreated(executorService, source, null); - return executorService; + return newScheduledThreadPool(source, name, getDefaultThreadPoolProfile()); } @Override @@ -194,35 +154,22 @@ public ExecutorService newThreadPool(Object source, String name, ThreadPoolProfi ObjectHelper.notNull(profile, ""ThreadPoolProfile""); ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - // fallback to use values from default profile if not specified - Integer poolSize = profile.getPoolSize() != null ? profile.getPoolSize() : defaultProfile.getPoolSize(); - Integer maxPoolSize = profile.getMaxPoolSize() != null ? profile.getMaxPoolSize() : defaultProfile.getMaxPoolSize(); - Long keepAliveTime = profile.getKeepAliveTime() != null ? profile.getKeepAliveTime() : defaultProfile.getKeepAliveTime(); - TimeUnit timeUnit = profile.getTimeUnit() != null ? profile.getTimeUnit() : defaultProfile.getTimeUnit(); - Integer maxQueueSize = profile.getMaxQueueSize() != null ? profile.getMaxQueueSize() : defaultProfile.getMaxQueueSize(); - RejectedExecutionHandler handler = profile.getRejectedExecutionHandler() != null ? profile.getRejectedExecutionHandler() : defaultProfile.getRejectedExecutionHandler(); + profile.addDefaults(defaultProfile); ThreadFactory threadFactory = createThreadFactory(name, true); - ExecutorService executorService = threadPoolFactory.newThreadPool(poolSize, maxPoolSize, - keepAliveTime, timeUnit, maxQueueSize, handler, threadFactory); + ExecutorService executorService = threadPoolFactory.newThreadPool(profile, threadFactory); onThreadPoolCreated(executorService, source, profile.getId()); + if (LOG.isDebugEnabled()) { + LOG.debug(""Created new ThreadPool for source: {} with name: {}. -> {}"", new Object[]{source, name, executorService}); + } + return executorService; } @Override public ExecutorService newThreadPool(Object source, String name, int poolSize, int maxPoolSize) { - ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - - // fallback to use values from default profile - ExecutorService answer = threadPoolFactory.newThreadPool(poolSize, maxPoolSize, - defaultProfile.getKeepAliveTime(), defaultProfile.getTimeUnit(), defaultProfile.getMaxQueueSize(), - defaultProfile.getRejectedExecutionHandler(), new CamelThreadFactory(threadNamePattern, name, true)); - onThreadPoolCreated(answer, source, null); - - if (LOG.isDebugEnabled()) { - LOG.debug(""Created new ThreadPool for source: {} with name: {}. -> {}"", new Object[]{source, name, answer}); - } - return answer; + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(maxPoolSize).build(); + return newThreadPool(source, name, profile); } @Override @@ -232,7 +179,7 @@ public ExecutorService newSingleThreadExecutor(Object source, String name) { @Override public ExecutorService newCachedThreadPool(Object source, String name) { - ExecutorService answer = threadPoolFactory.newCachedThreadPool(new CamelThreadFactory(threadNamePattern, name, true)); + ExecutorService answer = threadPoolFactory.newCachedThreadPool(createThreadFactory(name, true)); onThreadPoolCreated(answer, source, null); if (LOG.isDebugEnabled()) { @@ -243,29 +190,32 @@ public ExecutorService newCachedThreadPool(Object source, String name) { @Override public ExecutorService newFixedThreadPool(Object source, String name, int poolSize) { - ExecutorService answer = threadPoolFactory.newFixedThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true)); - onThreadPoolCreated(answer, source, null); - - if (LOG.isDebugEnabled()) { - LOG.debug(""Created new FixedThreadPool for source: {} with name: {}. -> {}"", new Object[]{source, name, answer}); - } - return answer; + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(poolSize).keepAliveTime(0L).build(); + return newThreadPool(source, name, profile); } @Override public ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name) { return newScheduledThreadPool(source, name, 1); } - + @Override - public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) { - ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true)); + public ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile) { + profile.addDefaults(getDefaultThreadPoolProfile()); + ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(profile, createThreadFactory(name, true)); onThreadPoolCreated(answer, source, null); if (LOG.isDebugEnabled()) { LOG.debug(""Created new ScheduledThreadPool for source: {} with name: {}. -> {}"", new Object[]{source, name, answer}); } return answer; + + } + + @Override + public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) { + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).build(); + return newScheduledThreadPool(source, name, profile); } @Override diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java index 3cbb0fa75bd59..318283fa01efb 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java @@ -28,6 +28,7 @@ import java.util.concurrent.TimeUnit; import org.apache.camel.spi.ThreadPoolFactory; +import org.apache.camel.spi.ThreadPoolProfile; /** * Factory for thread pools that uses the JDK {@link Executors} for creating the thread pools. @@ -37,13 +38,16 @@ public class DefaultThreadPoolFactory implements ThreadPoolFactory { public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return Executors.newCachedThreadPool(threadFactory); } - - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - return Executors.newFixedThreadPool(poolSize, threadFactory); - } - - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - return Executors.newScheduledThreadPool(corePoolSize, threadFactory); + + @Override + public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory factory) { + return newThreadPool(profile.getPoolSize(), + profile.getMaxPoolSize(), + profile.getKeepAliveTime(), + profile.getTimeUnit(), + profile.getMaxQueueSize(), + profile.getRejectedExecutionHandler(), + factory); } public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, @@ -84,5 +88,13 @@ public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long kee answer.setRejectedExecutionHandler(rejectedExecutionHandler); return answer; } + + /* (non-Javadoc) + * @see org.apache.camel.impl.ThreadPoolFactory#newScheduledThreadPool(java.lang.Integer, java.util.concurrent.ThreadFactory) + */ + @Override + public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) { + return Executors.newScheduledThreadPool(profile.getPoolSize(), threadFactory); + } } diff --git a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java index fcddf40314609..aa5ef9f585d87 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -29,10 +30,11 @@ import org.apache.camel.Processor; import org.apache.camel.ThreadPoolRejectedPolicy; -import org.apache.camel.builder.ThreadPoolBuilder; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.builder.xml.TimeUnitAdapter; import org.apache.camel.processor.Pipeline; import org.apache.camel.processor.ThreadsProcessor; +import org.apache.camel.spi.ExecutorServiceManager; import org.apache.camel.spi.RouteContext; import org.apache.camel.spi.ThreadPoolProfile; @@ -81,24 +83,16 @@ public Processor createProcessor(RouteContext routeContext) throws Exception { executorService = ProcessorDefinitionHelper.getConfiguredExecutorService(routeContext, name, this); // if no explicit then create from the options if (executorService == null) { - ThreadPoolProfile profile = routeContext.getCamelContext().getExecutorServiceManager().getDefaultThreadPoolProfile(); - // use the default thread pool profile as base and then override with values - // use a custom pool based on the settings - int core = getPoolSize() != null ? getPoolSize() : profile.getPoolSize(); - int max = getMaxPoolSize() != null ? getMaxPoolSize() : profile.getMaxPoolSize(); - long keepAlive = getKeepAliveTime() != null ? getKeepAliveTime() : profile.getKeepAliveTime(); - int maxQueue = getMaxQueueSize() != null ? getMaxQueueSize() : profile.getMaxQueueSize(); - TimeUnit tu = getTimeUnit() != null ? getTimeUnit() : profile.getTimeUnit(); - ThreadPoolRejectedPolicy rejected = getRejectedPolicy() != null ? getRejectedPolicy() : profile.getRejectedPolicy(); - + ExecutorServiceManager manager = routeContext.getCamelContext().getExecutorServiceManager(); // create the thread pool using a builder - executorService = new ThreadPoolBuilder(routeContext.getCamelContext()) - .poolSize(core) - .maxPoolSize(max) - .keepAliveTime(keepAlive, tu) - .maxQueueSize(maxQueue) - .rejectedPolicy(rejected) - .build(this, name); + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name) + .poolSize(getPoolSize()) + .maxPoolSize(getMaxPoolSize()) + .keepAliveTime(getKeepAliveTime(), getTimeUnit()) + .maxQueueSize(getMaxQueueSize()) + .rejectedPolicy(getRejectedPolicy()) + .build(); + executorService = manager.newThreadPool(this, name, profile); } ThreadsProcessor thread = new ThreadsProcessor(routeContext.getCamelContext(), executorService); diff --git a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java index 49efb0720c1b5..11070a96e0dcd 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java @@ -220,6 +220,8 @@ public interface ExecutorServiceManager extends ShutdownableService { * @return the created thread pool */ ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name); + + ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile); /** * Shutdown the given executor service. @@ -237,4 +239,5 @@ public interface ExecutorServiceManager extends ShutdownableService { * @see java.util.concurrent.ExecutorService#shutdownNow() */ List shutdownNow(ExecutorService executorService); + } diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java index c97f5ab68ea06..cc31ad23ad938 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java @@ -17,73 +17,41 @@ package org.apache.camel.spi; import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; /** - * Factory to crate {@link ExecutorService} and {@link ScheduledExecutorService} instances - *

      - * This interface allows to customize the creation of these objects to adapt Camel - * for application servers and other environments where thread pools should - * not be created with the JDK methods, as provided by the {@link org.apache.camel.impl.DefaultThreadPoolFactory}. - * - * @see ExecutorServiceManager + * Creates ExecutorService and ScheduledExecutorService objects that work with a thread pool for a given ThreadPoolProfile and ThreadFactory. + * + * This interface allows to customize the creation of these objects to adapt camel for application servers and other environments where thread pools + * should not be created with the jdk methods */ public interface ThreadPoolFactory { - /** * Creates a new cached thread pool *

      * The cached thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newCachedThreadPool()}. - * Implementators of this interface, may create a different kind of pool than the cached, or check the source code - * of the JDK to create a pool using the same settings. + * Typically it will have no size limit (this is why it is handled separately * * @param threadFactory factory for creating threads * @return the created thread pool */ ExecutorService newCachedThreadPool(ThreadFactory threadFactory); - + /** - * Creates a new fixed thread pool - *

      - * The fixed thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newFixedThreadPool(int)}. - * Implementators of this interface, may create a different kind of pool than the fixed, or check the source code - * of the JDK to create a pool using the same settings. - * - * @param poolSize the number of threads in the pool - * @param threadFactory factory for creating threads - * @return the created thread pool + * Create a thread pool using the given thread pool profile + * + * @param profile + * @param threadFactory + * @return */ - ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory); - + ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory); + /** - * Creates a new scheduled thread pool - * - * @param corePoolSize the core pool size - * @param threadFactory factory for creating threads - * @return the created thread pool - * @throws IllegalArgumentException if parameters is not valid - */ - ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException; - - /** - * Creates a new thread pool - * - * @param corePoolSize the core pool size - * @param maxPoolSize the maximum pool size - * @param keepAliveTime keep alive time - * @param timeUnit keep alive time unit - * @param maxQueueSize the maximum number of tasks in the queue, use Integer.MAX_VALUE or -1 to indicate unbounded - * @param rejectedExecutionHandler the handler for tasks which cannot be executed by the thread pool. - * If null is provided then {@link java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy CallerRunsPolicy} is used. - * @param threadFactory factory for creating threads - * @return the created thread pool - * @throws IllegalArgumentException if parameters is not valid + * Create a scheduled thread pool using the given thread pool profile + * @param profile + * @param threadFactory + * @return */ - ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, - int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, - ThreadFactory threadFactory) throws IllegalArgumentException; - -} + ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory); +} \ No newline at end of file diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java index c4f2e933477b0..87b9a01fd991b 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java @@ -219,6 +219,49 @@ public void setRejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) { this.rejectedPolicy = rejectedPolicy; } + /** + * Overwrites each attribute that is null with the attribute from defaultProfile + * + * @param defaultProfile2 + */ + public void addDefaults(ThreadPoolProfile defaultProfile2) { + if (defaultProfile2 == null) { + return; + } + if (poolSize == null) { + poolSize = defaultProfile2.getPoolSize(); + } + if (maxPoolSize == null) { + maxPoolSize = defaultProfile2.getMaxPoolSize(); + } + if (keepAliveTime == null) { + keepAliveTime = defaultProfile2.getKeepAliveTime(); + } + if (timeUnit == null) { + timeUnit = defaultProfile2.getTimeUnit(); + } + if (maxQueueSize == null) { + maxQueueSize = defaultProfile2.getMaxQueueSize(); + } + if (rejectedPolicy == null) { + rejectedPolicy = defaultProfile2.getRejectedPolicy(); + } + } + + @Override + public ThreadPoolProfile clone() { + ThreadPoolProfile cloned = new ThreadPoolProfile(); + cloned.setDefaultProfile(defaultProfile); + cloned.setId(id); + cloned.setKeepAliveTime(keepAliveTime); + cloned.setMaxPoolSize(maxPoolSize); + cloned.setMaxQueueSize(maxQueueSize); + cloned.setPoolSize(maxPoolSize); + cloned.setRejectedPolicy(rejectedPolicy); + cloned.setTimeUnit(timeUnit); + return cloned; + } + @Override public String toString() { return ""ThreadPoolProfile["" + id + "" ("" + defaultProfile + "") size:"" + poolSize + ""-"" + maxPoolSize diff --git a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java index 6d26693cc0b2c..f5467c0ef541e 100644 --- a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java +++ b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java @@ -18,7 +18,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @@ -54,18 +53,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return super.newCachedThreadPool(threadFactory); } - @Override - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - invoked = true; - return super.newFixedThreadPool(poolSize, threadFactory); - } - - @Override - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - invoked = true; - return super.newScheduledThreadPool(corePoolSize, threadFactory); - } - @Override public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException { diff --git a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java index af9c1963afd91..75204f0f93e76 100644 --- a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java +++ b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java @@ -357,8 +357,8 @@ public void testNewFixedThreadPool() throws Exception { ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool); // a fixed dont use keep alive - assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS)); - assertEquals(5, tp.getMaximumPoolSize()); + assertEquals(""keepAliveTime"", 0, tp.getKeepAliveTime(TimeUnit.SECONDS)); + assertEquals(""maximumPoolSize"", 5, tp.getMaximumPoolSize()); assertEquals(5, tp.getCorePoolSize()); assertFalse(tp.isShutdown()); @@ -373,8 +373,8 @@ public void testNewSingleThreadExecutor() throws Exception { ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool); // a single dont use keep alive - assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS)); - assertEquals(1, tp.getMaximumPoolSize()); + assertEquals(""keepAliveTime"", 0, tp.getKeepAliveTime(TimeUnit.SECONDS)); + assertEquals(""maximumPoolSize"", 1, tp.getMaximumPoolSize()); assertEquals(1, tp.getCorePoolSize()); assertFalse(tp.isShutdown()); diff --git a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java index 47338594284c3..624ab8087eb55 100644 --- a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java +++ b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java @@ -25,8 +25,9 @@ import org.apache.camel.CamelContext; import org.apache.camel.ThreadPoolRejectedPolicy; -import org.apache.camel.builder.ThreadPoolBuilder; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.builder.xml.TimeUnitAdapter; +import org.apache.camel.spi.ThreadPoolProfile; import org.apache.camel.util.CamelContextHelper; /** @@ -74,10 +75,14 @@ public ExecutorService getObject() throws Exception { queueSize = CamelContextHelper.parseInteger(getCamelContext(), maxQueueSize); } - ExecutorService answer = new ThreadPoolBuilder(getCamelContext()) - .poolSize(size).maxPoolSize(max).keepAliveTime(keepAlive, getTimeUnit()) - .maxQueueSize(queueSize).rejectedPolicy(getRejectedPolicy()) - .build(getId(), getThreadName()); + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(getId()) + .poolSize(size) + .maxPoolSize(max) + .keepAliveTime(keepAlive, timeUnit) + .maxQueueSize(queueSize) + .rejectedPolicy(rejectedPolicy) + .build(); + ExecutorService answer = getCamelContext().getExecutorServiceManager().newThreadPool(getId(), getThreadName(), profile); return answer; } diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java index a756b06391406..31729538c3ce3 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java @@ -18,7 +18,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @@ -56,18 +55,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return super.newCachedThreadPool(threadFactory); } - @Override - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - invoked = true; - return super.newFixedThreadPool(poolSize, threadFactory); - } - - @Override - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - invoked = true; - return super.newScheduledThreadPool(corePoolSize, threadFactory); - } - @Override public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException {" 1d24d71821f0163977a4d625263c9dcfaabe7bcb,hbase,HBASE-5549 HBASE-5572 Master can fail if- ZooKeeper session expires (N Keywal)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1301775 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java b/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java index 4f3fbc70d086..0ac1a334ca6d 100644 --- a/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java +++ b/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java @@ -124,97 +124,96 @@ private void handleMasterNodeChange() { * * This also makes sure that we are watching the master znode so will be * notified if another master dies. - * @param startupStatus + * @param startupStatus * @return True if no issue becoming active master else false if another * master was running or if some other problem (zookeeper, stop flag has been * set on this Master) */ boolean blockUntilBecomingActiveMaster(MonitoredTask startupStatus, - ClusterStatusTracker clusterStatusTracker) { - startupStatus.setStatus(""Trying to register in ZK as active master""); - boolean cleanSetOfActiveMaster = true; - // Try to become the active master, watch if there is another master. - // Write out our ServerName as versioned bytes. - try { - String backupZNode = ZKUtil.joinZNode( + ClusterStatusTracker clusterStatusTracker) { + while (true) { + startupStatus.setStatus(""Trying to register in ZK as active master""); + // Try to become the active master, watch if there is another master. + // Write out our ServerName as versioned bytes. + try { + String backupZNode = ZKUtil.joinZNode( this.watcher.backupMasterAddressesZNode, this.sn.toString()); - if (ZKUtil.createEphemeralNodeAndWatch(this.watcher, + if (ZKUtil.createEphemeralNodeAndWatch(this.watcher, this.watcher.masterAddressZNode, this.sn.getVersionedBytes())) { - // If we were a backup master before, delete our ZNode from the backup - // master directory since we are the active now - LOG.info(""Deleting ZNode for "" + backupZNode + - "" from backup master directory""); - ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode); - - // We are the master, return - startupStatus.setStatus(""Successfully registered as active master.""); + // If we were a backup master before, delete our ZNode from the backup + // master directory since we are the active now + LOG.info(""Deleting ZNode for "" + backupZNode + + "" from backup master directory""); + ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode); + + // We are the master, return + startupStatus.setStatus(""Successfully registered as active master.""); + this.clusterHasActiveMaster.set(true); + LOG.info(""Master="" + this.sn); + return true; + } + + // There is another active master running elsewhere or this is a restart + // and the master ephemeral node has not expired yet. this.clusterHasActiveMaster.set(true); - LOG.info(""Master="" + this.sn); - return cleanSetOfActiveMaster; - } - cleanSetOfActiveMaster = false; - - // There is another active master running elsewhere or this is a restart - // and the master ephemeral node has not expired yet. - this.clusterHasActiveMaster.set(true); - - /* - * Add a ZNode for ourselves in the backup master directory since we are - * not the active master. - * - * If we become the active master later, ActiveMasterManager will delete - * this node explicitly. If we crash before then, ZooKeeper will delete - * this node for us since it is ephemeral. - */ - LOG.info(""Adding ZNode for "" + backupZNode + - "" in backup master directory""); - ZKUtil.createEphemeralNodeAndWatch(this.watcher, backupZNode, + + /* + * Add a ZNode for ourselves in the backup master directory since we are + * not the active master. + * + * If we become the active master later, ActiveMasterManager will delete + * this node explicitly. If we crash before then, ZooKeeper will delete + * this node for us since it is ephemeral. + */ + LOG.info(""Adding ZNode for "" + backupZNode + + "" in backup master directory""); + ZKUtil.createEphemeralNodeAndWatch(this.watcher, backupZNode, HConstants.EMPTY_BYTE_ARRAY); - String msg; - byte [] bytes = - ZKUtil.getDataAndWatch(this.watcher, this.watcher.masterAddressZNode); - if (bytes == null) { - msg = (""A master was detected, but went down before its address "" + - ""could be read. Attempting to become the next active master""); - } else { - ServerName currentMaster = ServerName.parseVersionedServerName(bytes); - if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) { - msg = (""Current master has this master's address, "" + - currentMaster + ""; master was restarted? Waiting on znode "" + - ""to expire...""); - // Hurry along the expiration of the znode. - ZKUtil.deleteNode(this.watcher, this.watcher.masterAddressZNode); + String msg; + byte[] bytes = + ZKUtil.getDataAndWatch(this.watcher, this.watcher.masterAddressZNode); + if (bytes == null) { + msg = (""A master was detected, but went down before its address "" + + ""could be read. Attempting to become the next active master""); } else { - msg = ""Another master is the active master, "" + currentMaster + - ""; waiting to become the next active master""; + ServerName currentMaster = ServerName.parseVersionedServerName(bytes); + if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) { + msg = (""Current master has this master's address, "" + + currentMaster + ""; master was restarted? Deleting node.""); + // Hurry along the expiration of the znode. + ZKUtil.deleteNode(this.watcher, this.watcher.masterAddressZNode); + } else { + msg = ""Another master is the active master, "" + currentMaster + + ""; waiting to become the next active master""; + } } + LOG.info(msg); + startupStatus.setStatus(msg); + } catch (KeeperException ke) { + master.abort(""Received an unexpected KeeperException, aborting"", ke); + return false; } - LOG.info(msg); - startupStatus.setStatus(msg); - } catch (KeeperException ke) { - master.abort(""Received an unexpected KeeperException, aborting"", ke); - return false; - } - synchronized (this.clusterHasActiveMaster) { - while (this.clusterHasActiveMaster.get() && !this.master.isStopped()) { - try { - this.clusterHasActiveMaster.wait(); - } catch (InterruptedException e) { - // We expect to be interrupted when a master dies, will fall out if so - LOG.debug(""Interrupted waiting for master to die"", e); + synchronized (this.clusterHasActiveMaster) { + while (this.clusterHasActiveMaster.get() && !this.master.isStopped()) { + try { + this.clusterHasActiveMaster.wait(); + } catch (InterruptedException e) { + // We expect to be interrupted when a master dies, + // will fall out if so + LOG.debug(""Interrupted waiting for master to die"", e); + } } + if (!clusterStatusTracker.isClusterUp()) { + this.master.stop( + ""Cluster went down before this master became active""); + } + if (this.master.isStopped()) { + return false; + } + // there is no active master so we can try to become active master again } - if (!clusterStatusTracker.isClusterUp()) { - this.master.stop(""Cluster went down before this master became active""); - } - if (this.master.isStopped()) { - return cleanSetOfActiveMaster; - } - // Try to become active master again now that there is no active master - blockUntilBecomingActiveMaster(startupStatus,clusterStatusTracker); } - return cleanSetOfActiveMaster; } /** diff --git a/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/src/main/java/org/apache/hadoop/hbase/master/HMaster.java index cc56b620ef09..f814dcdaec2c 100644 --- a/src/main/java/org/apache/hadoop/hbase/master/HMaster.java +++ b/src/main/java/org/apache/hadoop/hbase/master/HMaster.java @@ -1527,8 +1527,7 @@ public void abort(final String msg, final Throwable t) { private boolean tryRecoveringExpiredZKSession() throws InterruptedException, IOException, KeeperException, ExecutionException { - this.zooKeeper = new ZooKeeperWatcher(conf, MASTER + "":"" - + this.serverName.getPort(), this, true); + this.zooKeeper.reconnectAfterExpiration(); Callable callable = new Callable () { public Boolean call() throws InterruptedException, diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java index 3e5ac0a839ff..a484d362c066 100644 --- a/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java +++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java @@ -73,25 +73,41 @@ public class RecoverableZooKeeper { // An identifier of this process in the cluster private final String identifier; private final byte[] id; - private int retryIntervalMillis; + private Watcher watcher; + private int sessionTimeout; + private String quorumServers; private static final int ID_OFFSET = Bytes.SIZEOF_INT; // the magic number is to be backward compatible private static final byte MAGIC =(byte) 0XFF; private static final int MAGIC_OFFSET = Bytes.SIZEOF_BYTE; - public RecoverableZooKeeper(String quorumServers, int seesionTimeout, + public RecoverableZooKeeper(String quorumServers, int sessionTimeout, Watcher watcher, int maxRetries, int retryIntervalMillis) throws IOException { - this.zk = new ZooKeeper(quorumServers, seesionTimeout, watcher); + this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher); this.retryCounterFactory = new RetryCounterFactory(maxRetries, retryIntervalMillis); - this.retryIntervalMillis = retryIntervalMillis; // the identifier = processID@hostName this.identifier = ManagementFactory.getRuntimeMXBean().getName(); LOG.info(""The identifier of this process is "" + identifier); this.id = Bytes.toBytes(identifier); + + this.watcher = watcher; + this.sessionTimeout = sessionTimeout; + this.quorumServers = quorumServers; + } + + public void reconnectAfterExpiration() + throws IOException, InterruptedException { + LOG.info(""Closing dead ZooKeeper connection, session"" + + "" was: 0x""+Long.toHexString(zk.getSessionId())); + zk.close(); + this.zk = new ZooKeeper(this.quorumServers, + this.sessionTimeout, this.watcher); + LOG.info(""Recreated a ZooKeeper, session"" + + "" is: 0x""+Long.toHexString(zk.getSessionId())); } /** @@ -123,6 +139,7 @@ public void delete(String path, int version) throw e; case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -159,6 +176,7 @@ public Stat exists(String path, Watcher watcher) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -194,6 +212,7 @@ public Stat exists(String path, boolean watch) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -229,6 +248,7 @@ public List getChildren(String path, Watcher watcher) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -264,6 +284,7 @@ public List getChildren(String path, boolean watch) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -301,6 +322,7 @@ public byte[] getData(String path, Watcher watcher, Stat stat) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -338,6 +360,7 @@ public byte[] getData(String path, boolean watch, Stat stat) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -377,6 +400,7 @@ public Stat setData(String path, byte[] data, int version) } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -484,6 +508,7 @@ private String createNonSequential(String path, byte[] data, List acl, throw e; case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { @@ -523,6 +548,7 @@ private String createSequential(String path, byte[] data, } catch (KeeperException e) { switch (e.code()) { case CONNECTIONLOSS: + case SESSIONEXPIRED: case OPERATIONTIMEOUT: LOG.warn(""Possibly transient ZooKeeper exception: "" + e); if (!retryCounter.shouldRetry()) { diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java index 5472cc878691..79b660476f83 100644 --- a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java +++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java @@ -253,6 +253,10 @@ public RecoverableZooKeeper getRecoverableZooKeeper() { return recoverableZooKeeper; } + public void reconnectAfterExpiration() throws IOException, InterruptedException { + recoverableZooKeeper.reconnectAfterExpiration(); + } + /** * Get the quorum address of this instance. * @return quorum string of this zookeeper connection instance diff --git a/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java b/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java index 4696e4dc4869..d9a2a0272f7c 100644 --- a/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java +++ b/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java @@ -39,6 +39,7 @@ import java.util.NavigableSet; import java.util.Random; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -73,6 +74,7 @@ import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; +import org.apache.hadoop.hbase.util.JVMClusterUtil; import org.apache.hadoop.hbase.util.RegionSplitter; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.util.Writables; @@ -86,6 +88,7 @@ import org.apache.hadoop.mapred.MiniMRCluster; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NodeExistsException; +import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.ZooKeeper; /** @@ -1308,7 +1311,7 @@ public void enableDebug(Class clazz) { */ public void expireMasterSession() throws Exception { HMaster master = hbaseCluster.getMaster(); - expireSession(master.getZooKeeper(), master); + expireSession(master.getZooKeeper(), false); } /** @@ -1318,7 +1321,7 @@ public void expireMasterSession() throws Exception { */ public void expireRegionServerSession(int index) throws Exception { HRegionServer rs = hbaseCluster.getRegionServer(index); - expireSession(rs.getZooKeeper(), rs); + expireSession(rs.getZooKeeper(), false); } @@ -1334,8 +1337,15 @@ public void expireSession(ZooKeeperWatcher nodeZK, Server server) } /** - * Expire a ZooKeeer session as recommended in ZooKeeper documentation + * Expire a ZooKeeper session as recommended in ZooKeeper documentation * http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4 + * There are issues when doing this: + * [1] http://www.mail-archive.com/dev@zookeeper.apache.org/msg01942.html + * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105 + * + * @param nodeZK - the ZK watcher to expire + * @param checkStatus - true to check if we can create an HTable with the + * current configuration. */ public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus) throws Exception { @@ -1345,14 +1355,29 @@ public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus) byte[] password = zk.getSessionPasswd(); long sessionID = zk.getSessionId(); + // Expiry seems to be asynchronous (see comment from P. Hunt in [1]), + // so we create a first watcher to be sure that the + // event was sent. We expect that if our watcher receives the event + // other watchers on the same machine will get is as well. + // When we ask to close the connection, ZK does not close it before + // we receive all the events, so don't have to capture the event, just + // closing the connection should be enough. + ZooKeeper monitor = new ZooKeeper(quorumServers, + 1000, new org.apache.zookeeper.Watcher(){ + @Override + public void process(WatchedEvent watchedEvent) { + LOG.info(""Monitor ZKW received event=""+watchedEvent); + } + } , sessionID, password); + + // Making it expire ZooKeeper newZK = new ZooKeeper(quorumServers, 1000, EmptyWatcher.instance, sessionID, password); newZK.close(); LOG.info(""ZK Closed Session 0x"" + Long.toHexString(sessionID)); - // There is actually no reason to sleep here. Session is expired. - // May be for old ZK versions? - // Thread.sleep(sleep); + // Now closing & waiting to be sure that the clients get it. + monitor.close(); if (checkStatus) { new HTable(new Configuration(conf), HConstants.META_TABLE_NAME).close(); @@ -1508,7 +1533,7 @@ public void waitTableAvailable(byte[] table, long timeoutMillis) * Make sure that at least the specified number of region servers * are running * @param num minimum number of region servers that should be running - * @return True if we started some servers + * @return true if we started some servers * @throws IOException */ public boolean ensureSomeRegionServersAvailable(final int num) @@ -1524,6 +1549,31 @@ public boolean ensureSomeRegionServersAvailable(final int num) } + /** + * Make sure that at least the specified number of region servers + * are running. We don't count the ones that are currently stopping or are + * stopped. + * @param num minimum number of region servers that should be running + * @return true if we started some servers + * @throws IOException + */ + public boolean ensureSomeNonStoppedRegionServersAvailable(final int num) + throws IOException { + boolean startedServer = ensureSomeRegionServersAvailable(num); + + for (JVMClusterUtil.RegionServerThread rst : + hbaseCluster.getRegionServerThreads()) { + + HRegionServer hrs = rst.getRegionServer(); + if (hrs.isStopping() || hrs.isStopped()) { + LOG.info(""A region server is stopped or stopping:""+hrs); + LOG.info(""Started new server="" + hbaseCluster.startRegionServer()); + startedServer = true; + } + } + + return startedServer; + } /** diff --git a/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java b/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java index a39de81d723a..fc3c46ec973d 100644 --- a/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java +++ b/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java @@ -36,6 +36,7 @@ import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.zookeeper.ZKConfig; import org.apache.hadoop.hbase.zookeeper.ZKUtil; @@ -93,40 +94,75 @@ public void setUp() throws Exception { */ @Test public void testClientSessionExpired() throws Exception { - LOG.info(""testClientSessionExpired""); Configuration c = new Configuration(TEST_UTIL.getConfiguration()); - new HTable(c, HConstants.META_TABLE_NAME).close(); + + // We don't want to share the connection as we will check + // its state + c.set(HConstants.HBASE_CLIENT_INSTANCE_ID, ""1111""); HConnection connection = HConnectionManager.getConnection(c); + ZooKeeperWatcher connectionZK = connection.getZooKeeperWatcher(); + LOG.info(""ZooKeeperWatcher= 0x""+ Integer.toHexString( + connectionZK.hashCode())); + LOG.info(""getRecoverableZooKeeper= 0x""+ Integer.toHexString( + connectionZK.getRecoverableZooKeeper().hashCode())); + LOG.info(""session=""+Long.toHexString( + connectionZK.getRecoverableZooKeeper().getSessionId())); TEST_UTIL.expireSession(connectionZK); - // Depending on how long you wait here, the state after dump will - // be 'closed' or 'Connecting'. - // There should be no reason to wait, the connection is closed on the server - // Thread.sleep(sessionTimeout * 3L); - - LOG.info(""Before dump state="" + + LOG.info(""Before using zkw state="" + connectionZK.getRecoverableZooKeeper().getState()); // provoke session expiration by doing something with ZK - ZKUtil.dump(connectionZK); + try { + connectionZK.getRecoverableZooKeeper().getZooKeeper().exists( + ""/1/1"", false); + } catch (KeeperException ignored) { + } // Check that the old ZK connection is closed, means we did expire - LOG.info(""ZooKeeper should have timed out""); States state = connectionZK.getRecoverableZooKeeper().getState(); - LOG.info(""After dump state="" + state); + LOG.info(""After using zkw state="" + state); + LOG.info(""session=""+Long.toHexString( + connectionZK.getRecoverableZooKeeper().getSessionId())); + + // It's asynchronous, so we may have to wait a little... + final long limit1 = System.currentTimeMillis() + 3000; + while (System.currentTimeMillis() < limit1 && state != States.CLOSED){ + state = connectionZK.getRecoverableZooKeeper().getState(); + } + LOG.info(""After using zkw loop="" + state); + LOG.info(""ZooKeeper should have timed out""); + LOG.info(""session=""+Long.toHexString( + connectionZK.getRecoverableZooKeeper().getSessionId())); + + // It's surprising but sometimes we can still be in connected state. + // As it's known (even if not understood) we don't make the the test fail + // for this reason. Assert.assertTrue(state == States.CLOSED); // Check that the client recovered ZooKeeperWatcher newConnectionZK = connection.getZooKeeperWatcher(); - //Here, if you wait, you will have a CONNECTED state. If you don't, - // you may have the CONNECTING one. - //Thread.sleep(sessionTimeout * 3L); + States state2 = newConnectionZK.getRecoverableZooKeeper().getState(); LOG.info(""After new get state="" +state2); + + // As it's an asynchronous event we may got the same ZKW, if it's not + // yet invalidated. Hence this loop. + final long limit2 = System.currentTimeMillis() + 3000; + while (System.currentTimeMillis() < limit2 && + state2 != States.CONNECTED && state2 != States.CONNECTING) { + + newConnectionZK = connection.getZooKeeperWatcher(); + state2 = newConnectionZK.getRecoverableZooKeeper().getState(); + } + LOG.info(""After new get state loop="" + state2); + Assert.assertTrue( state2 == States.CONNECTED || state2 == States.CONNECTING); + + connection.close(); } @Test @@ -141,7 +177,21 @@ public void testRegionServerSessionExpired() throws Exception { public void testMasterSessionExpired() throws Exception { LOG.info(""Starting testMasterSessionExpired""); TEST_UTIL.expireMasterSession(); - Thread.sleep(7000); // Helps the test to succeed!!! + testSanity(); + } + + /** + * Master recovery when the znode already exists. Internally, this + * test differs from {@link #testMasterSessionExpired} because here + * the master znode will exist in ZK. + */ + @Test(timeout=20000) + public void testMasterZKSessionRecoveryFailure() throws Exception { + MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); + HMaster m = cluster.getMaster(); + m.abort(""Test recovery from zk session expired"", + new KeeperException.SessionExpiredException()); + assertFalse(m.isStopped()); testSanity(); } diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java b/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java index 3a0c6b07e89b..afd9f0e68c96 100644 --- a/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java +++ b/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java @@ -87,6 +87,8 @@ private void startCluster(int num_rs) throws Exception{ LOG.info(""Starting cluster""); conf = HBaseConfiguration.create(); conf.getLong(""hbase.splitlog.max.resubmit"", 0); + // Make the failure test faster + conf.setInt(""zookeeper.recovery.retry"", 0); TEST_UTIL = new HBaseTestingUtility(conf); TEST_UTIL.startMiniCluster(NUM_MASTERS, num_rs); cluster = TEST_UTIL.getHBaseCluster(); @@ -245,7 +247,7 @@ public void run() { slm.enqueueSplitTask(logfiles[0].getPath().toString(), batch); //waitForCounter but for one of the 2 counters long curt = System.currentTimeMillis(); - long waitTime = 30000; + long waitTime = 80000; long endt = curt + waitTime; while (curt < endt) { if ((tot_wkr_task_resigned.get() + tot_wkr_task_err.get() + diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java b/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java deleted file mode 100644 index 1b9b24ec560b..000000000000 --- a/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright The Apache Software Foundation - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * ""License""); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.hadoop.hbase.master; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.hbase.HBaseTestingUtility; -import org.apache.hadoop.hbase.MediumTests; -import org.apache.hadoop.hbase.MiniHBaseCluster; -import org.apache.zookeeper.KeeperException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -/** - * Test cases for master to recover from ZK session expiry. - */ -@Category(MediumTests.class) -public class TestMasterZKSessionRecovery { - private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); - - /** - * The default timeout is 5 minutes. - * Shorten it so that the test won't wait for too long. - */ - static { - Configuration conf = TEST_UTIL.getConfiguration(); - conf.setLong(""hbase.master.zksession.recover.timeout"", 50000); - } - - @Before - public void setUp() throws Exception { - // Start a cluster of one regionserver. - TEST_UTIL.startMiniCluster(1); - } - - @After - public void tearDown() throws Exception { - TEST_UTIL.shutdownMiniCluster(); - } - - /** - * Negative test of master recovery from zk session expiry. - *

      - * Starts with one master. Fakes the master zk session expired. - * Ensures the master cannot recover the expired zk session since - * the master zk node is still there. - * @throws Exception - */ - @Test(timeout=10000) - public void testMasterZKSessionRecoveryFailure() throws Exception { - MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); - HMaster m = cluster.getMaster(); - m.abort(""Test recovery from zk session expired"", - new KeeperException.SessionExpiredException()); - assertTrue(m.isStopped()); - } - - /** - * Positive test of master recovery from zk session expiry. - *

      - * Starts with one master. Closes the master zk session. - * Ensures the master can recover the expired zk session. - * @throws Exception - */ - @Test(timeout=60000) - public void testMasterZKSessionRecoverySuccess() throws Exception { - MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); - HMaster m = cluster.getMaster(); - m.getZooKeeperWatcher().close(); - m.abort(""Test recovery from zk session expired"", - new KeeperException.SessionExpiredException()); - assertFalse(m.isStopped()); - } -} - diff --git a/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java index 1997abd531cb..7485832ee48f 100644 --- a/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java +++ b/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java @@ -20,6 +20,7 @@ package org.apache.hadoop.hbase.regionserver; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; @@ -78,7 +79,7 @@ public class TestSplitTransactionOnCluster { } @Before public void setup() throws IOException { - TESTING_UTIL.ensureSomeRegionServersAvailable(NB_SERVERS); + TESTING_UTIL.ensureSomeNonStoppedRegionServersAvailable(NB_SERVERS); this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); this.cluster = TESTING_UTIL.getMiniHBaseCluster(); } @@ -398,7 +399,10 @@ private int ensureTableRegionNotOnSameServerAsMeta(final HBaseAdmin admin, HRegionServer tableRegionServer = cluster.getRegionServer(tableRegionIndex); if (metaRegionServer.getServerName().equals(tableRegionServer.getServerName())) { HRegionServer hrs = getOtherRegionServer(cluster, metaRegionServer); - LOG.info(""Moving "" + hri.getRegionNameAsString() + "" to "" + + assertNotNull(hrs); + assertNotNull(hri); + LOG. + info(""Moving "" + hri.getRegionNameAsString() + "" to "" + hrs.getServerName() + ""; metaServerIndex="" + metaServerIndex); admin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hrs.getServerName().toString())); diff --git a/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java b/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java index a9ae7cac46e0..f6775bad836b 100644 --- a/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java +++ b/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java @@ -93,6 +93,8 @@ public static void setUpBeforeClass() throws Exception { conf1.setLong(""replication.source.sleepforretries"", 100); conf1.setInt(""hbase.regionserver.maxlogs"", 10); conf1.setLong(""hbase.master.logcleaner.ttl"", 10); + conf1.setInt(""zookeeper.recovery.retry"", 1); + conf1.setInt(""zookeeper.recovery.retry.intervalmill"", 10); conf1.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true); conf1.setBoolean(""dfs.support.append"", true); conf1.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100); @@ -651,9 +653,11 @@ public void queueFailover() throws Exception { int lastCount = 0; + final long start = System.currentTimeMillis(); for (int i = 0; i < NB_RETRIES; i++) { if (i==NB_RETRIES-1) { - fail(""Waited too much time for queueFailover replication""); + fail(""Waited too much time for queueFailover replication. "" + + ""Waited ""+(System.currentTimeMillis() - start)+""ms.""); } Scan scan2 = new Scan(); ResultScanner scanner2 = htable2.getScanner(scan2); diff --git a/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java b/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java index dd5460c3968c..1922d60a77fe 100644 --- a/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java +++ b/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java @@ -24,6 +24,7 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; +import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.SessionExpiredException; import org.junit.*; import org.junit.experimental.categories.Category; @@ -58,7 +59,9 @@ public void testResetZooKeeperSession() throws Exception { try { LOG.info(""Attempting to use expired ReplicationPeer ZooKeeper session.""); // Trying to use the expired session to assert that it is indeed closed - zkw.getRecoverableZooKeeper().exists(""/1/2"", false); + zkw.getRecoverableZooKeeper().getZooKeeper().exists(""/2/2"", false); + Assert.fail( + ""ReplicationPeer ZooKeeper session was not properly expired.""); } catch (SessionExpiredException k) { rp.reloadZkWatcher(); @@ -66,13 +69,12 @@ public void testResetZooKeeperSession() throws Exception { // Try to use the connection again LOG.info(""Attempting to use refreshed "" - + ""ReplicationPeer ZooKeeper session.""); - zkw.getRecoverableZooKeeper().exists(""/1/2"", false); + + ""ReplicationPeer ZooKeeper session.""); + zkw.getRecoverableZooKeeper().exists(""/3/2"", false); - return; + } catch (KeeperException.ConnectionLossException ignored) { + // We sometimes receive this exception. We just ignore it. } - - Assert.fail(""ReplicationPeer ZooKeeper session was not properly expired.""); }" bead0e770467e56136d115c64bf9ea2404813627,camel,CAMEL-1078. Fix potential NPE.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@788149 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java b/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java index 649a91589fe8a..f8943a0df76ae 100644 --- a/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java +++ b/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java @@ -103,8 +103,8 @@ public void setMessage(String message) { @Override protected Object createBody() { Exchange exchange = getExchange(); - IrcBinding binding = (IrcBinding)exchange.getProperty(Exchange.BINDING); - return binding.extractBodyFromIrc(exchange, this); + IrcBinding binding = exchange != null ? (IrcBinding)exchange.getProperty(Exchange.BINDING) : null; + return binding != null ? binding.extractBodyFromIrc(exchange, this) : null; } @Override" 643ae0c985d01e4b5deb9d28a1381de8179926af,hbase,HBASE-2781 ZKW.createUnassignedRegion doesn't- make sure existing znode is in the right state (Karthik- Ranganathan via JD)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@963910 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt index ec4341f65428..44e345bba702 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -432,6 +432,8 @@ Release 0.21.0 - Unreleased HBASE-2797 Another NPE in ReadWriteConsistencyControl HBASE-2831 Fix '$bin' path duplication in setup scripts (Nicolas Spiegelberg via Stack) + HBASE-2781 ZKW.createUnassignedRegion doesn't make sure existing znode is + in the right state (Karthik Ranganathan via JD) IMPROVEMENTS HBASE-1760 Cleanup TODOs in HTable diff --git a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java index b4ba5ab15c03..979739e3a076 100644 --- a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java +++ b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java @@ -993,8 +993,9 @@ public void setUnassigned(HRegionInfo info, boolean force) { // should never happen LOG.error(""Error creating event data for "" + HBaseEventType.M2ZK_REGION_OFFLINE, e); } - zkWrapper.createUnassignedRegion(info.getEncodedName(), data); - LOG.debug(""Created UNASSIGNED zNode "" + info.getRegionNameAsString() + "" in state "" + HBaseEventType.M2ZK_REGION_OFFLINE); + zkWrapper.createOrUpdateUnassignedRegion(info.getEncodedName(), data); + LOG.debug(""Created/updated UNASSIGNED zNode "" + info.getRegionNameAsString() + + "" in state "" + HBaseEventType.M2ZK_REGION_OFFLINE); s = new RegionState(info, RegionState.State.UNASSIGNED); regionsInTransition.put(info.getRegionNameAsString(), s); } diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java index 74b0446fa30f..f292b253c62e 100644 --- a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java +++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java @@ -1073,6 +1073,14 @@ public boolean writeZNode(String znodeName, byte[] data, int version, boolean wa } } + /** + * Given a region name and some data, this method creates a new the region + * znode data under the UNASSGINED znode with the data passed in. This method + * will not update data for existing znodes. + * + * @param regionName - encoded name of the region + * @param data - new serialized data to update the region znode + */ public void createUnassignedRegion(String regionName, byte[] data) { String znode = getZNode(getRegionInTransitionZNode(), regionName); if(LOG.isDebugEnabled()) { @@ -1109,6 +1117,66 @@ public void createUnassignedRegion(String regionName, byte[] data) { } } + /** + * Given a region name and some data, this method updates the region znode + * data under the UNASSGINED znode with the latest data. This method will + * update the znode data only if it already exists. + * + * @param regionName - encoded name of the region + * @param data - new serialized data to update the region znode + */ + public void updateUnassignedRegion(String regionName, byte[] data) { + String znode = getZNode(getRegionInTransitionZNode(), regionName); + // this is an update - make sure the node already exists + if(!exists(znode, true)) { + LOG.error(""Cannot update "" + znode + "" - node does not exist"" ); + return; + } + + if(LOG.isDebugEnabled()) { + // Check existing state for logging purposes. + Stat stat = new Stat(); + byte[] oldData = null; + try { + oldData = readZNode(znode, stat); + } catch (IOException e) { + LOG.error(""Error reading data for "" + znode); + } + if(oldData == null) { + LOG.debug(""While updating UNASSIGNED region "" + regionName + "" - node exists with no data"" ); + } + else { + LOG.debug(""While updating UNASSIGNED region "" + regionName + "" exists, state = "" + (HBaseEventType.fromByte(oldData[0]))); + } + } + synchronized(unassignedZNodesWatched) { + unassignedZNodesWatched.add(znode); + try { + writeZNode(znode, data, -1, true); + } catch (IOException e) { + LOG.error(""Error writing data for "" + znode + "", could not update state to "" + (HBaseEventType.fromByte(data[0]))); + } + } + } + + /** + * This method will create a new region in transition entry in ZK with the + * speficied data if none exists. If one already exists, it will update the + * data with whatever is passed in. + * + * @param regionName - encoded name of the region + * @param data - serialized data for the region znode + */ + public void createOrUpdateUnassignedRegion(String regionName, byte[] data) { + String znode = getZNode(getRegionInTransitionZNode(), regionName); + if(exists(znode, true)) { + updateUnassignedRegion(regionName, data); + } + else { + createUnassignedRegion(regionName, data); + } + } + public void deleteUnassignedRegion(String regionName) { String znode = getZNode(getRegionInTransitionZNode(), regionName); try {" 169e7e06ea223bd3fdca2460b74e9cd361439fff,ReactiveX-RxJava,Trying to fix non-deterministic test--- not sure of a way other than putting Thread.sleep in here to give time after each CountDownLatch triggers for the process scheduler to execute the next line of each thread--See https://github.com/Netflix/RxJava/pull/201 for more information.-,c,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/operators/OperationMerge.java b/rxjava-core/src/main/java/rx/operators/OperationMerge.java index eeb1e96407..d5aebe0ad5 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationMerge.java +++ b/rxjava-core/src/main/java/rx/operators/OperationMerge.java @@ -441,6 +441,15 @@ public void onNext(String v) { o1.onNextBeingSent.await(); o2.onNextBeingSent.await(); + // I can't think of a way to know for sure that both threads have or are trying to send onNext + // since I can't use a CountDownLatch for ""after"" onNext since I want to catch during it + // but I can't know for sure onNext is invoked + // so I'm unfortunately reverting to using a Thread.sleep to allow the process scheduler time + // to make sure after o1.onNextBeingSent and o2.onNextBeingSent are hit that the following + // onNext is invoked. + + Thread.sleep(300); + try { // in try/finally so threads are released via latch countDown even if assertion fails assertEquals(1, concurrentCounter.get()); } finally { @@ -541,6 +550,8 @@ public Subscription subscribe(final Observer observer) { public void run() { onNextBeingSent.countDown(); observer.onNext(""hello""); + // I can't use a countDownLatch to prove we are actually sending 'onNext' + // since it will block if synchronized and I'll deadlock observer.onCompleted(); }" a62eecc95a164415d8f924e1c88e2d144282395d,hbase,HBASE-7923 force unassign can confirm region- online on any RS to get rid of double assignments--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1464232 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java index 08358c3053a1..ea71218f3209 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/HMaster.java @@ -2267,11 +2267,14 @@ public UnassignRegionResponse unassignRegion(RpcController controller, UnassignR return urr; } } - if (force) { - this.assignmentManager.regionOffline(hri); + LOG.debug(""Close region "" + hri.getRegionNameAsString() + + "" on current location if it is online and reassign.force="" + force); + this.assignmentManager.unassign(hri, force); + if (!this.assignmentManager.getRegionStates().isRegionInTransition(hri) + && !this.assignmentManager.getRegionStates().isRegionAssigned(hri)) { + LOG.debug(""Region "" + hri.getRegionNameAsString() + + "" is not online on any region server, reassigning it.""); assignRegion(hri); - } else { - this.assignmentManager.unassign(hri, force); } if (cpHost != null) { cpHost.postUnassign(hri, force);" 0f92fdd8e6422d5b79c610a7fd8409d222315a49,ReactiveX-RxJava,RunAsync method for outputting multiple values--,a,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java index e091e78a9c..4f04f5fb47 100644 --- a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java +++ b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/Async.java @@ -20,10 +20,16 @@ import java.util.concurrent.FutureTask; import rx.Observable; +import rx.Observer; import rx.Scheduler; import rx.Scheduler.Inner; +import rx.Subscriber; +import rx.Subscription; import rx.schedulers.Schedulers; import rx.subjects.AsyncSubject; +import rx.subjects.PublishSubject; +import rx.subjects.Subject; +import rx.subscriptions.SerialSubscription; import rx.util.async.operators.Functionals; import rx.util.async.operators.OperationDeferFuture; import rx.util.async.operators.OperationForEachFuture; @@ -1711,4 +1717,54 @@ public static Observable fromCallable(Callable callable, Sch public static Observable fromRunnable(final Runnable run, final R result, Scheduler scheduler) { return Observable.create(OperationFromFunctionals.fromRunnable(run, result)).subscribeOn(scheduler); } + /** + * Runs the provided action on the given scheduler and allows propagation + * of multiple events to the observers of the returned StoppableObservable. + * The action is immediately executed and unobserved values will be lost. + * @param the output value type + * @param scheduler the scheduler where the action is executed + * @param action the action to execute, receives an Observer where the events can be pumped + * and a Subscription which lets check for cancellation condition. + * @return an Observable which provides a Subscription interface to cancel the action + */ + public static StoppableObservable runAsync(Scheduler scheduler, + final Action2, ? super Subscription> action) { + return runAsync(scheduler, PublishSubject.create(), action); + } + /** + * Runs the provided action on the given scheduler and allows propagation + * of multiple events to the observers of the returned StoppableObservable. + * The action is immediately executed and unobserved values might be lost, + * depending on the subject type used. + * @param the output value of the action + * @param the output type of the observable sequence + * @param scheduler the scheduler where the action is executed + * @param subject the subject to use to distribute values emitted by the action + * @param action the action to execute, receives an Observer where the events can be pumped + * and a Subscription which lets check for cancellation condition. + * @return an Observable which provides a Subscription interface to cancel the action + */ + public static StoppableObservable runAsync(Scheduler scheduler, + final Subject subject, + final Action2, ? super Subscription> action) { + final SerialSubscription csub = new SerialSubscription(); + + StoppableObservable co = new StoppableObservable(new Observable.OnSubscribe() { + @Override + public void call(Subscriber t1) { + subject.subscribe(t1); + } + }, csub); + + csub.set(scheduler.schedule(new Action1() { + @Override + public void call(Inner t1) { + if (!csub.isUnsubscribed()) { + action.call(subject, csub); + } + } + })); + + return co; + } } diff --git a/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java new file mode 100644 index 0000000000..ebd9538ed5 --- /dev/null +++ b/rxjava-contrib/rxjava-async-util/src/main/java/rx/util/async/StoppableObservable.java @@ -0,0 +1,41 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package rx.util.async; + +import rx.Observable; +import rx.Subscription; + +/** + * An Observable which provides a Subscription interface to signal a stop + * condition to an asynchronous task. + */ +public class StoppableObservable extends Observable implements Subscription { + private final Subscription token; + public StoppableObservable(Observable.OnSubscribe onSubscribe, Subscription token) { + super(onSubscribe); + this.token = token; + } + + @Override + public boolean isUnsubscribed() { + return token.isUnsubscribed(); + } + + @Override + public void unsubscribe() { + token.unsubscribe(); + } +} diff --git a/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java b/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java index d83d01b047..3146681c5f 100644 --- a/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java +++ b/rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java @@ -16,8 +16,8 @@ package rx.util.async; +import java.util.concurrent.CountDownLatch; import static org.junit.Assert.*; -import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import java.util.concurrent.TimeUnit; @@ -35,6 +35,7 @@ import rx.Observable; import rx.Observer; +import rx.Subscription; import rx.observers.TestObserver; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; @@ -818,4 +819,47 @@ public String answer(InvocationOnMock invocation) throws Throwable { verify(func, times(1)).call(); } + @Test + public void testRunAsync() throws InterruptedException { + final CountDownLatch cdl = new CountDownLatch(1); + final CountDownLatch cdl2 = new CountDownLatch(1); + Action2, Subscription> action = new Action2, Subscription>() { + @Override + public void call(Observer t1, Subscription t2) { + try { + cdl.await(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + return; + } + for (int i = 0; i < 10 && !t2.isUnsubscribed(); i++) { + t1.onNext(i); + } + t1.onCompleted(); + cdl2.countDown(); + } + }; + + @SuppressWarnings(""unchecked"") + Observer o = mock(Observer.class); + InOrder inOrder = inOrder(o); + + StoppableObservable so = Async.runAsync(Schedulers.io(), action); + + so.subscribe(o); + + cdl.countDown(); + + if (!cdl2.await(2, TimeUnit.SECONDS)) { + fail(""Didn't complete""); + } + + for (int i = 0; i < 10; i++) { + inOrder.verify(o).onNext(i); + } + inOrder.verify(o).onCompleted(); + inOrder.verifyNoMoreInteractions(); + verify(o, never()).onError(any(Throwable.class)); + + } }" 089b6d52e485ac587753db5343e9bb2104ed1c84,camel,Fixed unit test. Doh what a mistake--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@887104 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java index d8fe3adb3802d..f2c01618cef64 100644 --- a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java +++ b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpPollingConsumerTest.java @@ -44,12 +44,10 @@ public void setUp() throws Exception { @Test public void testPollingConsumer() throws Exception { MockEndpoint result = getMockEndpoint(""mock:result""); - result.expectedBodiesReceived(5); + result.expectedMessageCount(3); result.expectedFileExists(FTP_ROOT_DIR + ""polling/done/1.txt""); result.expectedFileExists(FTP_ROOT_DIR + ""polling/done/2.txt""); result.expectedFileExists(FTP_ROOT_DIR + ""polling/done/3.txt""); - result.expectedFileExists(FTP_ROOT_DIR + ""polling/done/4.txt""); - result.expectedFileExists(FTP_ROOT_DIR + ""polling/done/5.txt""); PollingConsumer consumer = context.getEndpoint(getFtpUrl()).createPollingConsumer(); consumer.start(); @@ -82,8 +80,6 @@ private void prepareFtpServer() throws Exception { sendFile(getFtpUrl(), ""Message 1"", ""1.txt""); sendFile(getFtpUrl(), ""Message 2"", ""2.txt""); sendFile(getFtpUrl(), ""Message 3"", ""3.txt""); - sendFile(getFtpUrl(), ""Message 4"", ""4.txt""); - sendFile(getFtpUrl(), ""Message 5"", ""5.txt""); } } \ No newline at end of file" 8bd2486b519ed6dcdc638843514d9034b7f3c49f,hadoop,"HADOOP-6148. Implement a fast, pure Java CRC32- calculator which outperforms java.util.zip.CRC32. Contributed by Todd Lipcon- and Scott Carey--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@794944 13f79535-47bb-0310-9956-ffa450edef68-",a,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index 88ca9c8f0d2cd..06cf3033d5d60 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -475,6 +475,9 @@ Trunk (unreleased changes) HADOOP-6142. Update documentation and use of harchives for relative paths added in MAPREDUCE-739. (Mahadev Konar via cdouglas) + HADOOP-6148. Implement a fast, pure Java CRC32 calculator which outperforms + java.util.zip.CRC32. (Todd Lipcon and Scott Carey via szetszwo) + OPTIMIZATIONS HADOOP-5595. NameNode does not need to run a replicator to choose a diff --git a/src/java/org/apache/hadoop/fs/ChecksumFileSystem.java b/src/java/org/apache/hadoop/fs/ChecksumFileSystem.java index 72a09bd75f2c4..6f9701e4d729b 100644 --- a/src/java/org/apache/hadoop/fs/ChecksumFileSystem.java +++ b/src/java/org/apache/hadoop/fs/ChecksumFileSystem.java @@ -27,6 +27,7 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Progressable; +import org.apache.hadoop.util.PureJavaCrc32; import org.apache.hadoop.util.StringUtils; /**************************************************************** @@ -135,7 +136,7 @@ public ChecksumFSInputChecker(ChecksumFileSystem fs, Path file, int bufferSize) if (!Arrays.equals(version, CHECKSUM_VERSION)) throw new IOException(""Not a checksum file: ""+sumFile); this.bytesPerSum = sums.readInt(); - set(fs.verifyChecksum, new CRC32(), bytesPerSum, 4); + set(fs.verifyChecksum, new PureJavaCrc32(), bytesPerSum, 4); } catch (FileNotFoundException e) { // quietly ignore set(fs.verifyChecksum, null, 1, 0); } catch (IOException e) { // loudly ignore @@ -330,7 +331,7 @@ public ChecksumFSOutputSummer(ChecksumFileSystem fs, long blockSize, Progressable progress) throws IOException { - super(new CRC32(), fs.getBytesPerSum(), 4); + super(new PureJavaCrc32(), fs.getBytesPerSum(), 4); int bytesPerSum = fs.getBytesPerSum(); this.datas = fs.getRawFileSystem().create(file, overwrite, bufferSize, replication, blockSize, progress); diff --git a/src/java/org/apache/hadoop/util/DataChecksum.java b/src/java/org/apache/hadoop/util/DataChecksum.java index 9aa339025b3d3..eb529bc483e64 100644 --- a/src/java/org/apache/hadoop/util/DataChecksum.java +++ b/src/java/org/apache/hadoop/util/DataChecksum.java @@ -16,7 +16,7 @@ * limitations under the License. */ -package org.apache.hadoop.util; +package org.apache.hadoop.util; import java.util.zip.Checksum; import java.util.zip.CRC32; @@ -51,7 +51,7 @@ public static DataChecksum newDataChecksum( int type, int bytesPerChecksum ) { return new DataChecksum( CHECKSUM_NULL, new ChecksumNull(), CHECKSUM_NULL_SIZE, bytesPerChecksum ); case CHECKSUM_CRC32 : - return new DataChecksum( CHECKSUM_CRC32, new CRC32(), + return new DataChecksum( CHECKSUM_CRC32, new PureJavaCrc32(), CHECKSUM_CRC32_SIZE, bytesPerChecksum ); default: return null; @@ -205,10 +205,10 @@ public int getBytesPerChecksum() { public int getNumBytesInSum() { return inSum; } - - public static final int SIZE_OF_INTEGER = Integer.SIZE / Byte.SIZE; + + public static final int SIZE_OF_INTEGER = Integer.SIZE / Byte.SIZE; static public int getChecksumHeaderSize() { - return 1 + SIZE_OF_INTEGER; // type byte, bytesPerChecksum int + return 1 + SIZE_OF_INTEGER; // type byte, bytesPerChecksum int } //Checksum Interface. Just a wrapper around member summer. public long getValue() { diff --git a/src/java/org/apache/hadoop/util/PureJavaCrc32.java b/src/java/org/apache/hadoop/util/PureJavaCrc32.java new file mode 100644 index 0000000000000..206f931b2674f --- /dev/null +++ b/src/java/org/apache/hadoop/util/PureJavaCrc32.java @@ -0,0 +1,351 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.util; + +import java.util.zip.Checksum; + +/** + * A pure-java implementation of the CRC32 checksum that uses + * the same polynomial as the built-in native CRC32. + * + * This is to avoid the JNI overhead for certain uses of Checksumming + * where many small pieces of data are checksummed in succession. + * + * The current version is ~10x to 1.8x as fast as Sun's native + * java.util.zip.CRC32 in Java 1.6 + * + * @see java.util.zip.CRC32 + */ +public class PureJavaCrc32 implements Checksum { + + /** the current CRC value, bit-flipped */ + private int crc; + + public PureJavaCrc32() { + reset(); + } + + /** {@inheritDoc} */ + public long getValue() { + return (~crc) & 0xffffffffL; + } + + /** {@inheritDoc} */ + public void reset() { + crc = 0xffffffff; + } + + /** {@inheritDoc} */ + public void update(byte[] b, int off, int len) { + while(len > 3) { + int c0 = crc ^ b[off++]; + int c1 = (crc >>>= 8) ^ b[off++]; + int c2 = (crc >>>= 8) ^ b[off++]; + int c3 = (crc >>>= 8) ^ b[off++]; + crc = T4[c0 & 0xff] ^ T3[c1 & 0xff] ^ T2[c2 & 0xff] ^ T1[c3 & 0xff]; + len -= 4; + } + while(len > 0) { + crc = (crc >>> 8) ^ T1[(crc ^ b[off++]) & 0xff]; + len--; + } + } + + /** {@inheritDoc} */ + final public void update(int b) { + crc = (crc >>> 8) ^ T1[(crc ^ b) & 0xff]; + } + + /** + * Pre-generated lookup tables. For the code to generate these tables + * please see HDFS-297. + */ + + /** T1[x] is ~CRC(x) */ + private static final int[] T1 = new int[] { + 0x0, 0x77073096, 0xee0e612c, 0x990951ba, + 0x76dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, + 0xedb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x9b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, + 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, + 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, + 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, + 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, + 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, + 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, + 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, + 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, + 0x76dc4190, 0x1db7106, 0x98d220bc, 0xefd5102a, + 0x71b18589, 0x6b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0xf00f934, 0x9609a88e, 0xe10e9818, + 0x7f6a0dbb, 0x86d3d2d, 0x91646c97, 0xe6635c01, + 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, + 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, + 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, + 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, + 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, + 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, + 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, + 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, + 0xedb88320, 0x9abfb3b6, 0x3b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x4db2615, 0x73dc1683, + 0xe3630b12, 0x94643b84, 0xd6d6a3e, 0x7a6a5aa8, + 0xe40ecf0b, 0x9309ff9d, 0xa00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, + 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, + 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, + 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, + 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, + 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, + 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, + 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, + 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x26d930a, + 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x5005713, + 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0xcb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0xbdbdf21, + 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, + 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, + 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, + 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, + 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, + 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, + 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, + 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d + }; + + /** T2[x] is ~CRC(x followed by one 0x00 byte) */ + private static final int[] T2 = new int[] { + 0x0, 0x191b3141, 0x32366282, 0x2b2d53c3, + 0x646cc504, 0x7d77f445, 0x565aa786, 0x4f4196c7, + 0xc8d98a08, 0xd1c2bb49, 0xfaefe88a, 0xe3f4d9cb, + 0xacb54f0c, 0xb5ae7e4d, 0x9e832d8e, 0x87981ccf, + 0x4ac21251, 0x53d92310, 0x78f470d3, 0x61ef4192, + 0x2eaed755, 0x37b5e614, 0x1c98b5d7, 0x5838496, + 0x821b9859, 0x9b00a918, 0xb02dfadb, 0xa936cb9a, + 0xe6775d5d, 0xff6c6c1c, 0xd4413fdf, 0xcd5a0e9e, + 0x958424a2, 0x8c9f15e3, 0xa7b24620, 0xbea97761, + 0xf1e8e1a6, 0xe8f3d0e7, 0xc3de8324, 0xdac5b265, + 0x5d5daeaa, 0x44469feb, 0x6f6bcc28, 0x7670fd69, + 0x39316bae, 0x202a5aef, 0xb07092c, 0x121c386d, + 0xdf4636f3, 0xc65d07b2, 0xed705471, 0xf46b6530, + 0xbb2af3f7, 0xa231c2b6, 0x891c9175, 0x9007a034, + 0x179fbcfb, 0xe848dba, 0x25a9de79, 0x3cb2ef38, + 0x73f379ff, 0x6ae848be, 0x41c51b7d, 0x58de2a3c, + 0xf0794f05, 0xe9627e44, 0xc24f2d87, 0xdb541cc6, + 0x94158a01, 0x8d0ebb40, 0xa623e883, 0xbf38d9c2, + 0x38a0c50d, 0x21bbf44c, 0xa96a78f, 0x138d96ce, + 0x5ccc0009, 0x45d73148, 0x6efa628b, 0x77e153ca, + 0xbabb5d54, 0xa3a06c15, 0x888d3fd6, 0x91960e97, + 0xded79850, 0xc7cca911, 0xece1fad2, 0xf5facb93, + 0x7262d75c, 0x6b79e61d, 0x4054b5de, 0x594f849f, + 0x160e1258, 0xf152319, 0x243870da, 0x3d23419b, + 0x65fd6ba7, 0x7ce65ae6, 0x57cb0925, 0x4ed03864, + 0x191aea3, 0x188a9fe2, 0x33a7cc21, 0x2abcfd60, + 0xad24e1af, 0xb43fd0ee, 0x9f12832d, 0x8609b26c, + 0xc94824ab, 0xd05315ea, 0xfb7e4629, 0xe2657768, + 0x2f3f79f6, 0x362448b7, 0x1d091b74, 0x4122a35, + 0x4b53bcf2, 0x52488db3, 0x7965de70, 0x607eef31, + 0xe7e6f3fe, 0xfefdc2bf, 0xd5d0917c, 0xcccba03d, + 0x838a36fa, 0x9a9107bb, 0xb1bc5478, 0xa8a76539, + 0x3b83984b, 0x2298a90a, 0x9b5fac9, 0x10aecb88, + 0x5fef5d4f, 0x46f46c0e, 0x6dd93fcd, 0x74c20e8c, + 0xf35a1243, 0xea412302, 0xc16c70c1, 0xd8774180, + 0x9736d747, 0x8e2de606, 0xa500b5c5, 0xbc1b8484, + 0x71418a1a, 0x685abb5b, 0x4377e898, 0x5a6cd9d9, + 0x152d4f1e, 0xc367e5f, 0x271b2d9c, 0x3e001cdd, + 0xb9980012, 0xa0833153, 0x8bae6290, 0x92b553d1, + 0xddf4c516, 0xc4eff457, 0xefc2a794, 0xf6d996d5, + 0xae07bce9, 0xb71c8da8, 0x9c31de6b, 0x852aef2a, + 0xca6b79ed, 0xd37048ac, 0xf85d1b6f, 0xe1462a2e, + 0x66de36e1, 0x7fc507a0, 0x54e85463, 0x4df36522, + 0x2b2f3e5, 0x1ba9c2a4, 0x30849167, 0x299fa026, + 0xe4c5aeb8, 0xfdde9ff9, 0xd6f3cc3a, 0xcfe8fd7b, + 0x80a96bbc, 0x99b25afd, 0xb29f093e, 0xab84387f, + 0x2c1c24b0, 0x350715f1, 0x1e2a4632, 0x7317773, + 0x4870e1b4, 0x516bd0f5, 0x7a468336, 0x635db277, + 0xcbfad74e, 0xd2e1e60f, 0xf9ccb5cc, 0xe0d7848d, + 0xaf96124a, 0xb68d230b, 0x9da070c8, 0x84bb4189, + 0x3235d46, 0x1a386c07, 0x31153fc4, 0x280e0e85, + 0x674f9842, 0x7e54a903, 0x5579fac0, 0x4c62cb81, + 0x8138c51f, 0x9823f45e, 0xb30ea79d, 0xaa1596dc, + 0xe554001b, 0xfc4f315a, 0xd7626299, 0xce7953d8, + 0x49e14f17, 0x50fa7e56, 0x7bd72d95, 0x62cc1cd4, + 0x2d8d8a13, 0x3496bb52, 0x1fbbe891, 0x6a0d9d0, + 0x5e7ef3ec, 0x4765c2ad, 0x6c48916e, 0x7553a02f, + 0x3a1236e8, 0x230907a9, 0x824546a, 0x113f652b, + 0x96a779e4, 0x8fbc48a5, 0xa4911b66, 0xbd8a2a27, + 0xf2cbbce0, 0xebd08da1, 0xc0fdde62, 0xd9e6ef23, + 0x14bce1bd, 0xda7d0fc, 0x268a833f, 0x3f91b27e, + 0x70d024b9, 0x69cb15f8, 0x42e6463b, 0x5bfd777a, + 0xdc656bb5, 0xc57e5af4, 0xee530937, 0xf7483876, + 0xb809aeb1, 0xa1129ff0, 0x8a3fcc33, 0x9324fd72 + }; + + /** T3[x] is ~CRC(x followed by two 0x00 bytes) */ + private static final int[] T3 = new int[] { + 0x0, 0x1c26a37, 0x384d46e, 0x246be59, + 0x709a8dc, 0x6cbc2eb, 0x48d7cb2, 0x54f1685, + 0xe1351b8, 0xfd13b8f, 0xd9785d6, 0xc55efe1, + 0x91af964, 0x8d89353, 0xa9e2d0a, 0xb5c473d, + 0x1c26a370, 0x1de4c947, 0x1fa2771e, 0x1e601d29, + 0x1b2f0bac, 0x1aed619b, 0x18abdfc2, 0x1969b5f5, + 0x1235f2c8, 0x13f798ff, 0x11b126a6, 0x10734c91, + 0x153c5a14, 0x14fe3023, 0x16b88e7a, 0x177ae44d, + 0x384d46e0, 0x398f2cd7, 0x3bc9928e, 0x3a0bf8b9, + 0x3f44ee3c, 0x3e86840b, 0x3cc03a52, 0x3d025065, + 0x365e1758, 0x379c7d6f, 0x35dac336, 0x3418a901, + 0x3157bf84, 0x3095d5b3, 0x32d36bea, 0x331101dd, + 0x246be590, 0x25a98fa7, 0x27ef31fe, 0x262d5bc9, + 0x23624d4c, 0x22a0277b, 0x20e69922, 0x2124f315, + 0x2a78b428, 0x2bbade1f, 0x29fc6046, 0x283e0a71, + 0x2d711cf4, 0x2cb376c3, 0x2ef5c89a, 0x2f37a2ad, + 0x709a8dc0, 0x7158e7f7, 0x731e59ae, 0x72dc3399, + 0x7793251c, 0x76514f2b, 0x7417f172, 0x75d59b45, + 0x7e89dc78, 0x7f4bb64f, 0x7d0d0816, 0x7ccf6221, + 0x798074a4, 0x78421e93, 0x7a04a0ca, 0x7bc6cafd, + 0x6cbc2eb0, 0x6d7e4487, 0x6f38fade, 0x6efa90e9, + 0x6bb5866c, 0x6a77ec5b, 0x68315202, 0x69f33835, + 0x62af7f08, 0x636d153f, 0x612bab66, 0x60e9c151, + 0x65a6d7d4, 0x6464bde3, 0x662203ba, 0x67e0698d, + 0x48d7cb20, 0x4915a117, 0x4b531f4e, 0x4a917579, + 0x4fde63fc, 0x4e1c09cb, 0x4c5ab792, 0x4d98dda5, + 0x46c49a98, 0x4706f0af, 0x45404ef6, 0x448224c1, + 0x41cd3244, 0x400f5873, 0x4249e62a, 0x438b8c1d, + 0x54f16850, 0x55330267, 0x5775bc3e, 0x56b7d609, + 0x53f8c08c, 0x523aaabb, 0x507c14e2, 0x51be7ed5, + 0x5ae239e8, 0x5b2053df, 0x5966ed86, 0x58a487b1, + 0x5deb9134, 0x5c29fb03, 0x5e6f455a, 0x5fad2f6d, + 0xe1351b80, 0xe0f771b7, 0xe2b1cfee, 0xe373a5d9, + 0xe63cb35c, 0xe7fed96b, 0xe5b86732, 0xe47a0d05, + 0xef264a38, 0xeee4200f, 0xeca29e56, 0xed60f461, + 0xe82fe2e4, 0xe9ed88d3, 0xebab368a, 0xea695cbd, + 0xfd13b8f0, 0xfcd1d2c7, 0xfe976c9e, 0xff5506a9, + 0xfa1a102c, 0xfbd87a1b, 0xf99ec442, 0xf85cae75, + 0xf300e948, 0xf2c2837f, 0xf0843d26, 0xf1465711, + 0xf4094194, 0xf5cb2ba3, 0xf78d95fa, 0xf64fffcd, + 0xd9785d60, 0xd8ba3757, 0xdafc890e, 0xdb3ee339, + 0xde71f5bc, 0xdfb39f8b, 0xddf521d2, 0xdc374be5, + 0xd76b0cd8, 0xd6a966ef, 0xd4efd8b6, 0xd52db281, + 0xd062a404, 0xd1a0ce33, 0xd3e6706a, 0xd2241a5d, + 0xc55efe10, 0xc49c9427, 0xc6da2a7e, 0xc7184049, + 0xc25756cc, 0xc3953cfb, 0xc1d382a2, 0xc011e895, + 0xcb4dafa8, 0xca8fc59f, 0xc8c97bc6, 0xc90b11f1, + 0xcc440774, 0xcd866d43, 0xcfc0d31a, 0xce02b92d, + 0x91af9640, 0x906dfc77, 0x922b422e, 0x93e92819, + 0x96a63e9c, 0x976454ab, 0x9522eaf2, 0x94e080c5, + 0x9fbcc7f8, 0x9e7eadcf, 0x9c381396, 0x9dfa79a1, + 0x98b56f24, 0x99770513, 0x9b31bb4a, 0x9af3d17d, + 0x8d893530, 0x8c4b5f07, 0x8e0de15e, 0x8fcf8b69, + 0x8a809dec, 0x8b42f7db, 0x89044982, 0x88c623b5, + 0x839a6488, 0x82580ebf, 0x801eb0e6, 0x81dcdad1, + 0x8493cc54, 0x8551a663, 0x8717183a, 0x86d5720d, + 0xa9e2d0a0, 0xa820ba97, 0xaa6604ce, 0xaba46ef9, + 0xaeeb787c, 0xaf29124b, 0xad6fac12, 0xacadc625, + 0xa7f18118, 0xa633eb2f, 0xa4755576, 0xa5b73f41, + 0xa0f829c4, 0xa13a43f3, 0xa37cfdaa, 0xa2be979d, + 0xb5c473d0, 0xb40619e7, 0xb640a7be, 0xb782cd89, + 0xb2cddb0c, 0xb30fb13b, 0xb1490f62, 0xb08b6555, + 0xbbd72268, 0xba15485f, 0xb853f606, 0xb9919c31, + 0xbcde8ab4, 0xbd1ce083, 0xbf5a5eda, 0xbe9834ed + }; + + /** T4[x] is ~CRC(x followed by three 0x00 bytes) */ + private static final int[] T4 = new int[] { + 0x0, 0xb8bc6765, 0xaa09c88b, 0x12b5afee, + 0x8f629757, 0x37def032, 0x256b5fdc, 0x9dd738b9, + 0xc5b428ef, 0x7d084f8a, 0x6fbde064, 0xd7018701, + 0x4ad6bfb8, 0xf26ad8dd, 0xe0df7733, 0x58631056, + 0x5019579f, 0xe8a530fa, 0xfa109f14, 0x42acf871, + 0xdf7bc0c8, 0x67c7a7ad, 0x75720843, 0xcdce6f26, + 0x95ad7f70, 0x2d111815, 0x3fa4b7fb, 0x8718d09e, + 0x1acfe827, 0xa2738f42, 0xb0c620ac, 0x87a47c9, + 0xa032af3e, 0x188ec85b, 0xa3b67b5, 0xb28700d0, + 0x2f503869, 0x97ec5f0c, 0x8559f0e2, 0x3de59787, + 0x658687d1, 0xdd3ae0b4, 0xcf8f4f5a, 0x7733283f, + 0xeae41086, 0x525877e3, 0x40edd80d, 0xf851bf68, + 0xf02bf8a1, 0x48979fc4, 0x5a22302a, 0xe29e574f, + 0x7f496ff6, 0xc7f50893, 0xd540a77d, 0x6dfcc018, + 0x359fd04e, 0x8d23b72b, 0x9f9618c5, 0x272a7fa0, + 0xbafd4719, 0x241207c, 0x10f48f92, 0xa848e8f7, + 0x9b14583d, 0x23a83f58, 0x311d90b6, 0x89a1f7d3, + 0x1476cf6a, 0xaccaa80f, 0xbe7f07e1, 0x6c36084, + 0x5ea070d2, 0xe61c17b7, 0xf4a9b859, 0x4c15df3c, + 0xd1c2e785, 0x697e80e0, 0x7bcb2f0e, 0xc377486b, + 0xcb0d0fa2, 0x73b168c7, 0x6104c729, 0xd9b8a04c, + 0x446f98f5, 0xfcd3ff90, 0xee66507e, 0x56da371b, + 0xeb9274d, 0xb6054028, 0xa4b0efc6, 0x1c0c88a3, + 0x81dbb01a, 0x3967d77f, 0x2bd27891, 0x936e1ff4, + 0x3b26f703, 0x839a9066, 0x912f3f88, 0x299358ed, + 0xb4446054, 0xcf80731, 0x1e4da8df, 0xa6f1cfba, + 0xfe92dfec, 0x462eb889, 0x549b1767, 0xec277002, + 0x71f048bb, 0xc94c2fde, 0xdbf98030, 0x6345e755, + 0x6b3fa09c, 0xd383c7f9, 0xc1366817, 0x798a0f72, + 0xe45d37cb, 0x5ce150ae, 0x4e54ff40, 0xf6e89825, + 0xae8b8873, 0x1637ef16, 0x48240f8, 0xbc3e279d, + 0x21e91f24, 0x99557841, 0x8be0d7af, 0x335cb0ca, + 0xed59b63b, 0x55e5d15e, 0x47507eb0, 0xffec19d5, + 0x623b216c, 0xda874609, 0xc832e9e7, 0x708e8e82, + 0x28ed9ed4, 0x9051f9b1, 0x82e4565f, 0x3a58313a, + 0xa78f0983, 0x1f336ee6, 0xd86c108, 0xb53aa66d, + 0xbd40e1a4, 0x5fc86c1, 0x1749292f, 0xaff54e4a, + 0x322276f3, 0x8a9e1196, 0x982bbe78, 0x2097d91d, + 0x78f4c94b, 0xc048ae2e, 0xd2fd01c0, 0x6a4166a5, + 0xf7965e1c, 0x4f2a3979, 0x5d9f9697, 0xe523f1f2, + 0x4d6b1905, 0xf5d77e60, 0xe762d18e, 0x5fdeb6eb, + 0xc2098e52, 0x7ab5e937, 0x680046d9, 0xd0bc21bc, + 0x88df31ea, 0x3063568f, 0x22d6f961, 0x9a6a9e04, + 0x7bda6bd, 0xbf01c1d8, 0xadb46e36, 0x15080953, + 0x1d724e9a, 0xa5ce29ff, 0xb77b8611, 0xfc7e174, + 0x9210d9cd, 0x2aacbea8, 0x38191146, 0x80a57623, + 0xd8c66675, 0x607a0110, 0x72cfaefe, 0xca73c99b, + 0x57a4f122, 0xef189647, 0xfdad39a9, 0x45115ecc, + 0x764dee06, 0xcef18963, 0xdc44268d, 0x64f841e8, + 0xf92f7951, 0x41931e34, 0x5326b1da, 0xeb9ad6bf, + 0xb3f9c6e9, 0xb45a18c, 0x19f00e62, 0xa14c6907, + 0x3c9b51be, 0x842736db, 0x96929935, 0x2e2efe50, + 0x2654b999, 0x9ee8defc, 0x8c5d7112, 0x34e11677, + 0xa9362ece, 0x118a49ab, 0x33fe645, 0xbb838120, + 0xe3e09176, 0x5b5cf613, 0x49e959fd, 0xf1553e98, + 0x6c820621, 0xd43e6144, 0xc68bceaa, 0x7e37a9cf, + 0xd67f4138, 0x6ec3265d, 0x7c7689b3, 0xc4caeed6, + 0x591dd66f, 0xe1a1b10a, 0xf3141ee4, 0x4ba87981, + 0x13cb69d7, 0xab770eb2, 0xb9c2a15c, 0x17ec639, + 0x9ca9fe80, 0x241599e5, 0x36a0360b, 0x8e1c516e, + 0x866616a7, 0x3eda71c2, 0x2c6fde2c, 0x94d3b949, + 0x90481f0, 0xb1b8e695, 0xa30d497b, 0x1bb12e1e, + 0x43d23e48, 0xfb6e592d, 0xe9dbf6c3, 0x516791a6, + 0xccb0a91f, 0x740cce7a, 0x66b96194, 0xde0506f1 + }; + +} diff --git a/src/test/core/org/apache/hadoop/util/TestPureJavaCrc32.java b/src/test/core/org/apache/hadoop/util/TestPureJavaCrc32.java new file mode 100644 index 0000000000000..715d8f620c9b6 --- /dev/null +++ b/src/test/core/org/apache/hadoop/util/TestPureJavaCrc32.java @@ -0,0 +1,171 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * ""License""); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.util; + +import junit.framework.TestCase; +import java.util.zip.CRC32; +import java.util.zip.Checksum; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Random; + +/** + * Unit test to verify that the pure-Java CRC32 algorithm gives + * the same results as the built-in implementation. + */ +public class TestPureJavaCrc32 extends TestCase { + private CRC32 theirs; + private PureJavaCrc32 ours; + + public void setUp() { + theirs = new CRC32(); + ours = new PureJavaCrc32(); + } + + public void testCorrectness() throws Exception { + checkSame(); + + theirs.update(104); + ours.update(104); + checkSame(); + + checkOnBytes(new byte[] {40, 60, 97, -70}, false); + + checkOnBytes(""hello world!"".getBytes(""UTF-8""), false); + + for (int i = 0; i < 10000; i++) { + byte randomBytes[] = new byte[new Random().nextInt(2048)]; + new Random().nextBytes(randomBytes); + checkOnBytes(randomBytes, false); + } + + } + + private void checkOnBytes(byte[] bytes, boolean print) { + theirs.reset(); + ours.reset(); + checkSame(); + + for (int i = 0; i < bytes.length; i++) { + ours.update(bytes[i]); + theirs.update(bytes[i]); + checkSame(); + } + + if (print) { + System.out.println(""theirs:\t"" + Long.toHexString(theirs.getValue()) + + ""\nours:\t"" + Long.toHexString(ours.getValue())); + } + + theirs.reset(); + ours.reset(); + + ours.update(bytes, 0, bytes.length); + theirs.update(bytes, 0, bytes.length); + if (print) { + System.out.println(""theirs:\t"" + Long.toHexString(theirs.getValue()) + + ""\nours:\t"" + Long.toHexString(ours.getValue())); + } + + checkSame(); + + if (bytes.length >= 10) { + ours.update(bytes, 5, 5); + theirs.update(bytes, 5, 5); + checkSame(); + } + } + + private void checkSame() { + assertEquals(theirs.getValue(), ours.getValue()); + } + + /** + * Performance tests to compare performance of the Pure Java implementation + * to the built-in java.util.zip implementation. This can be run from the + * command line with: + * + * java -cp path/to/test/classes:path/to/common/classes \ + * 'org.apache.hadoop.util.TestPureJavaCrc32$PerformanceTest' + * + * The output is in JIRA table format. + */ + public static class PerformanceTest { + public static final int MAX_LEN = 32*1024*1024; // up to 32MB chunks + public static final int BYTES_PER_SIZE = MAX_LEN * 4; + + public static LinkedHashMap getImplsToTest() { + LinkedHashMap impls = + new LinkedHashMap(); + impls.put(""BuiltIn"", new CRC32()); + impls.put(""PureJava"", new PureJavaCrc32()); + return impls; + } + + public static void main(String args[]) { + LinkedHashMap impls = getImplsToTest(); + + Random rand = new Random(); + byte[] bytes = new byte[MAX_LEN]; + rand.nextBytes(bytes); + + + // Print header + System.out.printf(""||num bytes||""); + for (String entry : impls.keySet()) { + System.out.printf(entry + "" MB/sec||""); + } + System.out.printf(""\n""); + + // Warm up implementations to get jit going. + for (Map.Entry entry : impls.entrySet()) { + doBench(""warmUp"" + entry.getKey(), + entry.getValue(), bytes, 2, false); + doBench(""warmUp"" + entry.getKey(), + entry.getValue(), bytes, 2101, false); + } + + // Test on a variety of sizes + for (int size = 1; size < MAX_LEN; size *= 2) { + System.out.printf(""| %d\t|"", size); + + for (Map.Entry entry : impls.entrySet()) { + System.gc(); + doBench(entry.getKey(), entry.getValue(), bytes, size, true); + } + System.out.printf(""\n""); + } + } + + private static void doBench(String id, Checksum crc, + byte[] bytes, int size, boolean printout) { + long st = System.nanoTime(); + int trials = BYTES_PER_SIZE / size; + for (int i = 0; i < trials; i++) { + crc.update(bytes, 0, size); + } + long et = System.nanoTime(); + + double mbProcessed = trials * size / 1024.0 / 1024.0; + double secsElapsed = (et - st) / 1000000000.0d; + if (printout) { + System.out.printf(""%.3f \t|"", mbProcessed / secsElapsed); + } + } + } +}" fb72a4d1f220c3d7d1d681ae17b4e22e89fb51d1,kotlin,Formatting--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java index 90dac89c0e8aa..a670390735d07 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/DescriptorResolver.java @@ -1179,8 +1179,18 @@ protected JetType compute() { return mutableClassDescriptor.getDefaultType(); } }); - ValueParameterDescriptorImpl parameterDescriptor = new ValueParameterDescriptorImpl(values,0,Collections.emptyList(),Name.identifier(""value""),false,JetStandardLibrary.getInstance().getStringType(),false,null); - values.initialize(null, classReceiver, Collections.emptyList(),Arrays.asList(parameterDescriptor), + ValueParameterDescriptor parameterDescriptor = new ValueParameterDescriptorImpl( + values, + 0, + Collections.emptyList(), + Name.identifier(""value""), + false, + JetStandardLibrary.getInstance().getStringType(), + false, + null); + values.initialize(null, classReceiver, + Collections.emptyList(), + Collections.singletonList(parameterDescriptor), type, Modality.FINAL, Visibilities.PUBLIC, false); return values;" ff642734febd8c5df95b67d5537c6f571a3c3aa2,ReactiveX-RxJava,remove warnings and cleanup--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/Notification.java b/rxjava-core/src/main/java/rx/Notification.java index 0c7af498a9..08c6113ec6 100644 --- a/rxjava-core/src/main/java/rx/Notification.java +++ b/rxjava-core/src/main/java/rx/Notification.java @@ -149,7 +149,7 @@ public boolean equals(Object obj) { return true; if (obj.getClass() != getClass()) return false; - Notification notification = (Notification) obj; + Notification notification = (Notification) obj; if (notification.getKind() != getKind()) return false; if (hasValue() && !getValue().equals(notification.getValue())) diff --git a/rxjava-core/src/main/java/rx/operators/OperationConcat.java b/rxjava-core/src/main/java/rx/operators/OperationConcat.java index 92516e9375..c621002533 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationConcat.java +++ b/rxjava-core/src/main/java/rx/operators/OperationConcat.java @@ -15,7 +15,6 @@ */ package rx.operators; - import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -43,8 +42,8 @@ public final class OperationConcat { * @param sequences * An observable sequence of elements to project. * @return An observable sequence whose elements are the result of combining the output from the list of Observables. - */ - public static Func1, Subscription> concat(final Observable... sequences) { + */ + public static Func1, Subscription> concat(final Observable... sequences) { return new Func1, Subscription>() { @Override @@ -55,143 +54,143 @@ public Subscription call(Observer observer) { } public static Func1, Subscription> concat(final List> sequences) { - @SuppressWarnings(""unchecked"") - Observable[] o = sequences.toArray((Observable[])Array.newInstance(Observable.class, sequences.size())); - return concat(o); + @SuppressWarnings(""unchecked"") + Observable[] o = sequences.toArray((Observable[]) Array.newInstance(Observable.class, sequences.size())); + return concat(o); } - public static Func1, Subscription> concat(final Observable> sequences) { - final List> list = new ArrayList>(); - sequences.toList().subscribe(new Action1>>(){ - @Override - public void call(List> t1) { - list.addAll(t1); - } - - }); - - return concat(list); + public static Func1, Subscription> concat(final Observable> sequences) { + final List> list = new ArrayList>(); + sequences.toList().subscribe(new Action1>>() { + @Override + public void call(List> t1) { + list.addAll(t1); + } + + }); + + return concat(list); } - + private static class Concat implements Func1, Subscription> { private final Observable[] sequences; private int num = 0; private int count = 0; private Subscription s; - + Concat(final Observable... sequences) { this.sequences = sequences; this.num = sequences.length - 1; } + private final AtomicObservableSubscription Subscription = new AtomicObservableSubscription(); - + private final Subscription actualSubscription = new Subscription() { - @Override - public void unsubscribe() { - if (null != s) - s.unsubscribe(); - } + @Override + public void unsubscribe() { + if (null != s) + s.unsubscribe(); + } }; - + public Subscription call(Observer observer) { - s = sequences[count].subscribe(new ConcatObserver(observer)); - + s = sequences[count].subscribe(new ConcatObserver(observer)); + return Subscription.wrap(actualSubscription); } - + private class ConcatObserver implements Observer { private final Observer observer; ConcatObserver(Observer observer) { this.observer = observer; } - - @Override - public void onCompleted() { - if (num == count) - observer.onCompleted(); - else { - count++; - s = sequences[count].subscribe(this); - } - } - - @Override - public void onError(Exception e) { - observer.onError(e); - - } - - @Override - public void onNext(T args) { - observer.onNext(args); - - } + + @Override + public void onCompleted() { + if (num == count) + observer.onCompleted(); + else { + count++; + s = sequences[count].subscribe(this); + } + } + + @Override + public void onError(Exception e) { + observer.onError(e); + + } + + @Override + public void onNext(T args) { + observer.onNext(args); + + } } } - - public static class UnitTest { - private final static String[] expected = {""1"", ""3"", ""5"", ""7"", ""2"", ""4"", ""6""}; - private int index = 0; - + + public static class UnitTest { + private final static String[] expected = { ""1"", ""3"", ""5"", ""7"", ""2"", ""4"", ""6"" }; + private int index = 0; + Observer observer = new Observer() { - @Override - public void onCompleted() { - } - - @Override - public void onError(Exception e) { - // TODO Auto-generated method stub - } - - @Override - public void onNext(String args) { - Assert.assertEquals(expected[index], args); - index++; - } + @Override + public void onCompleted() { + } + + @Override + public void onError(Exception e) { + // TODO Auto-generated method stub + } + + @Override + public void onNext(String args) { + Assert.assertEquals(expected[index], args); + index++; + } }; - + @Before public void before() { index = 0; } - - @Test - public void testConcat() { - final String[] o = {""1"", ""3"", ""5"", ""7""}; - final String[] e = {""2"", ""4"", ""6""}; - - final Observable odds = Observable.toObservable(o); - final Observable even = Observable.toObservable(e); - - @SuppressWarnings(""unchecked"") - Observable concat = Observable.create(concat(odds, even)); - concat.subscribe(observer); - Assert.assertEquals(expected.length, index); - - } - - @Test - public void testConcatWithList() { - final String[] o = {""1"", ""3"", ""5"", ""7""}; - final String[] e = {""2"", ""4"", ""6""}; - - final Observable odds = Observable.toObservable(o); - final Observable even = Observable.toObservable(e); - final List> list = new ArrayList>(); - list.add(odds); - list.add(even); - @SuppressWarnings(""unchecked"") - Observable concat = Observable.create(concat(list)); - concat.subscribe(observer); - Assert.assertEquals(expected.length, index); - - } - - @Test - public void testConcatUnsubscribe() { + + @Test + public void testConcat() { + final String[] o = { ""1"", ""3"", ""5"", ""7"" }; + final String[] e = { ""2"", ""4"", ""6"" }; + + final Observable odds = Observable.toObservable(o); + final Observable even = Observable.toObservable(e); + + @SuppressWarnings(""unchecked"") + Observable concat = Observable.create(concat(odds, even)); + concat.subscribe(observer); + Assert.assertEquals(expected.length, index); + + } + + @Test + public void testConcatWithList() { + final String[] o = { ""1"", ""3"", ""5"", ""7"" }; + final String[] e = { ""2"", ""4"", ""6"" }; + + final Observable odds = Observable.toObservable(o); + final Observable even = Observable.toObservable(e); + final List> list = new ArrayList>(); + list.add(odds); + list.add(even); + Observable concat = Observable.create(concat(list)); + concat.subscribe(observer); + Assert.assertEquals(expected.length, index); + + } + + @Test + public void testConcatUnsubscribe() { final CountDownLatch callOnce = new CountDownLatch(1); final CountDownLatch okToContinue = new CountDownLatch(1); final TestObservable w1 = new TestObservable(null, null, ""one"", ""two"", ""three""); @@ -202,14 +201,14 @@ public void testConcatUnsubscribe() { @SuppressWarnings(""unchecked"") Observable concat = Observable.create(concat(w1, w2)); Subscription s1 = concat.subscribe(aObserver); - + try { //Block main thread to allow observable ""w1"" to complete and observable ""w2"" to call onNext once. - callOnce.await(); + callOnce.await(); s1.unsubscribe(); //Unblock the observable to continue. okToContinue.countDown(); - w1.t.join(); + w1.t.join(); w2.t.join(); } catch (Exception e) { e.printStackTrace(); @@ -222,15 +221,15 @@ public void testConcatUnsubscribe() { verify(aObserver, times(1)).onNext(""four""); verify(aObserver, never()).onNext(""five""); verify(aObserver, never()).onNext(""six""); - } - + } + @Test public void testMergeObservableOfObservables() { - final String[] o = {""1"", ""3"", ""5"", ""7""}; - final String[] e = {""2"", ""4"", ""6""}; - - final Observable odds = Observable.toObservable(o); - final Observable even = Observable.toObservable(e); + final String[] o = { ""1"", ""3"", ""5"", ""7"" }; + final String[] e = { ""2"", ""4"", ""6"" }; + + final Observable odds = Observable.toObservable(o); + final Observable even = Observable.toObservable(e); Observable> observableOfObservables = Observable.create(new Func1>, Subscription>() { @@ -252,68 +251,65 @@ public void unsubscribe() { } }); - @SuppressWarnings(""unchecked"") - Observable concat = Observable.create(concat(observableOfObservables)); - concat.subscribe(observer); - Assert.assertEquals(expected.length, index); - } - - - private static class TestObservable extends Observable { - - private final Subscription s = new Subscription() { - - @Override - public void unsubscribe() { - // TODO Auto-generated method stub - subscribed = false; - } - - }; - private final String[] values; - private Thread t = null; - private int count = 0; - private boolean subscribed = true; - private final CountDownLatch once; - private final CountDownLatch okToContinue; - - public TestObservable(CountDownLatch once, CountDownLatch okToContinue, String... values) { - this.values = values; - this.once = once; - this.okToContinue = okToContinue; - } - - @Override - public Subscription subscribe(final Observer observer) { - t = new Thread(new Runnable() { - - @Override - public void run() { - try { - while(count < values.length && subscribed) { - observer.onNext(values[count]); - count++; - //Unblock the main thread to call unsubscribe. - if (null != once) - once.countDown(); - //Block until the main thread has called unsubscribe. - if (null != once) - okToContinue.await(); - } - if (subscribed) - observer.onCompleted(); - } catch (InterruptedException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - } - - }); - t.start(); - return s; - } - - } - + Observable concat = Observable.create(concat(observableOfObservables)); + concat.subscribe(observer); + Assert.assertEquals(expected.length, index); + } + + private static class TestObservable extends Observable { + + private final Subscription s = new Subscription() { + + @Override + public void unsubscribe() { + subscribed = false; + } + + }; + private final String[] values; + private Thread t = null; + private int count = 0; + private boolean subscribed = true; + private final CountDownLatch once; + private final CountDownLatch okToContinue; + + public TestObservable(CountDownLatch once, CountDownLatch okToContinue, String... values) { + this.values = values; + this.once = once; + this.okToContinue = okToContinue; + } + + @Override + public Subscription subscribe(final Observer observer) { + t = new Thread(new Runnable() { + + @Override + public void run() { + try { + while (count < values.length && subscribed) { + observer.onNext(values[count]); + count++; + //Unblock the main thread to call unsubscribe. + if (null != once) + once.countDown(); + //Block until the main thread has called unsubscribe. + if (null != once) + okToContinue.await(); + } + if (subscribed) + observer.onCompleted(); + } catch (InterruptedException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + }); + t.start(); + return s; + } + + } + } } \ No newline at end of file diff --git a/rxjava-core/src/main/java/rx/operators/OperationToObservableFuture.java b/rxjava-core/src/main/java/rx/operators/OperationToObservableFuture.java index 7c1e59c9c2..0c19619e4e 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationToObservableFuture.java +++ b/rxjava-core/src/main/java/rx/operators/OperationToObservableFuture.java @@ -64,7 +64,7 @@ public void testSuccess() throws Exception { Future future = mock(Future.class); Object value = new Object(); when(future.get()).thenReturn(value); - ToObservableFuture ob = new ToObservableFuture(future); + ToObservableFuture ob = new ToObservableFuture(future); Observer o = mock(Observer.class); Subscription sub = ob.call(o); @@ -81,7 +81,7 @@ public void testFailure() throws Exception { Future future = mock(Future.class); RuntimeException e = new RuntimeException(); when(future.get()).thenThrow(e); - ToObservableFuture ob = new ToObservableFuture(future); + ToObservableFuture ob = new ToObservableFuture(future); Observer o = mock(Observer.class); Subscription sub = ob.call(o);" 6ed722529007866fd89f6d996b8be5f4129c27a5,hbase,HBASE-3167 HBase Export: Add ability to export- specific Column Family; Turn Block Cache off during export; improve usage doc--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1028546 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt index cf58b9047fd3..7216b71e1739 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1049,6 +1049,9 @@ Release 0.21.0 - Unreleased LZO when LZO isn't available HBASE-3082 For ICV gets, first look in MemStore before reading StoreFiles (prakash via jgray) + HBASE-3167 HBase Export: Add ability to export specific Column Family; + Turn Block Cache off during export; improve usage doc + (Kannan Muthukkaruppan via Stack) NEW FEATURES HBASE-1961 HBase EC2 scripts diff --git a/src/main/java/org/apache/hadoop/hbase/mapreduce/Export.java b/src/main/java/org/apache/hadoop/hbase/mapreduce/Export.java index d328915dbfad..a42a125fea4d 100644 --- a/src/main/java/org/apache/hadoop/hbase/mapreduce/Export.java +++ b/src/main/java/org/apache/hadoop/hbase/mapreduce/Export.java @@ -27,6 +27,7 @@ import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; +import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; @@ -91,6 +92,10 @@ public static Job createSubmittableJob(Configuration conf, String[] args) long startTime = args.length > 3? Long.parseLong(args[3]): 0L; long endTime = args.length > 4? Long.parseLong(args[4]): Long.MAX_VALUE; s.setTimeRange(startTime, endTime); + s.setCacheBlocks(false); + if (conf.get(TableInputFormat.SCAN_COLUMN_FAMILY) != null) { + s.addFamily(Bytes.toBytes(conf.get(TableInputFormat.SCAN_COLUMN_FAMILY))); + } LOG.info(""verisons="" + versions + "", starttime="" + startTime + "", endtime="" + endTime); TableMapReduceUtil.initTableMapperJob(tableName, s, Exporter.class, null, @@ -111,8 +116,16 @@ private static void usage(final String errorMsg) { if (errorMsg != null && errorMsg.length() > 0) { System.err.println(""ERROR: "" + errorMsg); } - System.err.println(""Usage: Export [ "" + - ""[ []]]""); + System.err.println(""Usage: Export [-D ]* [ "" + + ""[ []]]\n""); + System.err.println("" Note: -D properties will be applied to the conf used. ""); + System.err.println("" For example: ""); + System.err.println("" -D mapred.output.compress=true""); + System.err.println("" -D mapred.output.compression.codec=org.apache.hadoop.io.compress.GzipCodec""); + System.err.println("" -D mapred.output.compression.type=BLOCK""); + System.err.println("" Additionally, the following SCAN properties can be specified""); + System.err.println("" to control/limit what is exported..""); + System.err.println("" -D "" + TableInputFormat.SCAN_COLUMN_FAMILY + ""=""); } /**" 14b92404cd1199d1e0e91786893295fe26cc8ec6,kotlin,add test for private-to-this visibility in traits--,p,https://github.com/JetBrains/kotlin,"diff --git a/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.kt b/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.kt new file mode 100644 index 0000000000000..cc19666ccdb26 --- /dev/null +++ b/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.kt @@ -0,0 +1,7 @@ +internal trait Test { + private/*private to this*/ final fun foo(): I { + throw Exception() + } + + private/*private to this*/ final val i: I get() = foo() +} diff --git a/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.txt b/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.txt new file mode 100644 index 0000000000000..3f4d06af6b9ab --- /dev/null +++ b/compiler/testData/diagnostics/tests/variance/privateToThis/Trait.txt @@ -0,0 +1,9 @@ +package + +internal trait Test { + private/*private to this*/ final val i: I + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + private/*private to this*/ final fun foo(): I + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String +} diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java index 455a62c0f6bdd..50c7a637eddb5 100644 --- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java @@ -12515,6 +12515,12 @@ public void testSetVar() throws Exception { doTest(fileName); } + @TestMetadata(""Trait.kt"") + public void testTrait() throws Exception { + String fileName = JetTestUtils.navigationMetadata(""compiler/testData/diagnostics/tests/variance/privateToThis/Trait.kt""); + doTest(fileName); + } + @TestMetadata(""ValReassigned.kt"") public void testValReassigned() throws Exception { String fileName = JetTestUtils.navigationMetadata(""compiler/testData/diagnostics/tests/variance/privateToThis/ValReassigned.kt"");" c689af142aefea121ae87e32fe775f9859b7344a,kotlin,Fixed highlighting for enum and object names in- code-- -KT-8134 Fixed-,c,https://github.com/JetBrains/kotlin,"diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java index 4f7f3f83e3016..249a00b8caa37 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java @@ -30,7 +30,15 @@ public R visitDeclaration(@NotNull JetDeclaration dcl, D data) { } public R visitClass(@NotNull JetClass klass, D data) { - return visitNamedDeclaration(klass, data); + return visitClassOrObject(klass, data); + } + + public R visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, D data) { + return visitClassOrObject(declaration, data); + } + + public R visitClassOrObject(@NotNull JetClassOrObject classOrObject, D data) { + return visitNamedDeclaration(classOrObject, data); } public R visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor, D data) { @@ -402,10 +410,6 @@ public R visitWhenConditionWithExpression(@NotNull JetWhenConditionWithExpressio return visitJetElement(condition, data); } - public R visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, D data) { - return visitNamedDeclaration(declaration, data); - } - public R visitObjectDeclarationName(@NotNull JetObjectDeclarationName declarationName, D data) { return visitExpression(declarationName, data); } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java index 78caf28882d0c..286fd42ad1f75 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java @@ -33,6 +33,10 @@ public void visitClass(@NotNull JetClass klass) { super.visitClass(klass, null); } + public void visitClassOrObject(@NotNull JetClassOrObject classOrObject) { + super.visitClassOrObject(classOrObject, null); + } + public void visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor) { super.visitSecondaryConstructor(constructor, null); } @@ -448,6 +452,12 @@ public final Void visitClass(@NotNull JetClass klass, Void data) { return null; } + @Override + public final Void visitClassOrObject(@NotNull JetClassOrObject classOrObject, Void data) { + visitClassOrObject(classOrObject); + return null; + } + @Override public final Void visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor, Void data) { visitSecondaryConstructor(constructor); diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt index 31ddc27f0a6cc..58abc341513df 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt @@ -154,7 +154,7 @@ public class LazyTopDownAnalyzer { fileScope.forceResolveImport(importDirective) } - private fun visitClassOrObject(classOrObject: JetClassOrObject) { + override fun visitClassOrObject(classOrObject: JetClassOrObject) { val descriptor = lazyDeclarationResolver!!.getClassDescriptor(classOrObject) as ClassDescriptorWithResolutionScopes c.getDeclaredClasses().put(classOrObject, descriptor) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties index 099b79fce1473..c57187ff1aaa4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties @@ -133,6 +133,7 @@ options.kotlin.attribute.descriptor.kdoc.comment=KDoc comment options.kotlin.attribute.descriptor.kdoc.tag=KDoc tag options.kotlin.attribute.descriptor.kdoc.value=Link in KDoc tag options.kotlin.attribute.descriptor.object=Object +options.kotlin.attribute.descriptor.enumEntry=Enum entry options.kotlin.attribute.descriptor.annotation=Annotation options.kotlin.attribute.descriptor.var=Var (mutable variable, parameter or property) options.kotlin.attribute.descriptor.local.variable=Local variable or value diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java index 62b237cf779a2..60f81964a740f 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java @@ -55,6 +55,7 @@ public class JetHighlightingColors { public static final TextAttributesKey TRAIT = createTextAttributesKey(""KOTLIN_TRAIT"", CodeInsightColors.INTERFACE_NAME_ATTRIBUTES); public static final TextAttributesKey ANNOTATION = createTextAttributesKey(""KOTLIN_ANNOTATION""); public static final TextAttributesKey OBJECT = createTextAttributesKey(""KOTLIN_OBJECT"", CLASS); + public static final TextAttributesKey ENUM_ENTRY = createTextAttributesKey(""KOTLIN_ENUM_ENTRY"", CodeInsightColors.INSTANCE_FIELD_ATTRIBUTES); // variable kinds public static final TextAttributesKey MUTABLE_VARIABLE = createTextAttributesKey(""KOTLIN_MUTABLE_VARIABLE""); diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java index db9b10016969b..a4267bd75fa46 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java @@ -62,14 +62,6 @@ private void highlightAnnotation(@NotNull JetSimpleNameExpression expression) { JetPsiChecker.highlightName(holder, toHighlight, JetHighlightingColors.ANNOTATION); } - @Override - public void visitObjectDeclarationName(@NotNull JetObjectDeclarationName declaration) { - PsiElement nameIdentifier = declaration.getNameIdentifier(); - if (nameIdentifier != null) { - highlightName(nameIdentifier, JetHighlightingColors.CLASS); - } - } - @Override public void visitTypeParameter(@NotNull JetTypeParameter parameter) { PsiElement identifier = parameter.getNameIdentifier(); @@ -80,18 +72,13 @@ public void visitTypeParameter(@NotNull JetTypeParameter parameter) { } @Override - public void visitEnumEntry(@NotNull JetEnumEntry enumEntry) { - // Do nothing, the name was already highlighted in visitObjectDeclarationName - } - - @Override - public void visitClass(@NotNull JetClass klass) { - PsiElement identifier = klass.getNameIdentifier(); - ClassDescriptor classDescriptor = bindingContext.get(BindingContext.CLASS, klass); + public void visitClassOrObject(@NotNull JetClassOrObject classOrObject) { + PsiElement identifier = classOrObject.getNameIdentifier(); + ClassDescriptor classDescriptor = bindingContext.get(BindingContext.CLASS, classOrObject); if (identifier != null && classDescriptor != null) { highlightName(identifier, textAttributesKeyForClass(classDescriptor)); } - super.visitClass(klass); + super.visitClassOrObject(classOrObject); } @Override @@ -113,7 +100,7 @@ private static TextAttributesKey textAttributesKeyForClass(@NotNull ClassDescrip case OBJECT: return JetHighlightingColors.OBJECT; case ENUM_ENTRY: - return JetHighlightingColors.INSTANCE_PROPERTY; + return JetHighlightingColors.ENUM_ENTRY; default: return descriptor.getModality() == Modality.ABSTRACT ? JetHighlightingColors.ABSTRACT_CLASS diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java b/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java index 0969b6e4983aa..9973ee9244129 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java @@ -82,6 +82,10 @@ public String getDemoText() { ""\n"" + ""public abstract class Abstract {\n"" + ""}\n"" + + ""\n"" + + ""object Obj\n"" + + ""\n"" + + ""enum class E { A }\n"" + "" Bad character: \\n\n""; } @@ -137,6 +141,7 @@ public AttributesDescriptor[] getAttributeDescriptors() { new AttributesDescriptor(""Interface"", JetHighlightingColors.TRAIT), new AttributesDescriptor(JetBundle.message(""options.kotlin.attribute.descriptor.annotation""), JetHighlightingColors.ANNOTATION), new AttributesDescriptor(JetBundle.message(""options.kotlin.attribute.descriptor.object""), JetHighlightingColors.OBJECT), + new AttributesDescriptor(JetBundle.message(""options.kotlin.attribute.descriptor.enumEntry""), JetHighlightingColors.ENUM_ENTRY), new AttributesDescriptor(JetBundle.message(""options.kotlin.attribute.descriptor.var""), JetHighlightingColors.MUTABLE_VARIABLE), diff --git a/idea/testData/highlighter/Enums.kt b/idea/testData/highlighter/Enums.kt index 835f6f1cffaac..4c194cc839292 100644 --- a/idea/testData/highlighter/Enums.kt +++ b/idea/testData/highlighter/Enums.kt @@ -1,11 +1,11 @@ package testing enum class Test { - FIRST, - SECOND + FIRST, + SECOND } fun testing(t1: Test, t2: Test): Test { - if (t1 != t2) return Test.FIRST - return testing(Test.FIRST, Test.SECOND) + if (t1 != t2) return Test.FIRST + return testing(Test.FIRST, Test.SECOND) } \ No newline at end of file diff --git a/idea/testData/highlighter/Object.kt b/idea/testData/highlighter/Object.kt index 1533b54340fd6..1e25e85a838f3 100644 --- a/idea/testData/highlighter/Object.kt +++ b/idea/testData/highlighter/Object.kt @@ -1,6 +1,6 @@ package testing -object O { +object O { fun foo() = 42 }" 197fc962fa8a3153dc058abfa2ae8c816d67ea04,orientdb,"Fixed a bug in concurrency: - adaptive lock can- be configured by OGlobalConfiguration - Created new- OGlobalConfiguration.ENVIRONMENT_CONCURRENT for this purpose -- OSharedResourceAdaptiveLinked class has no sense to exists anymore: removed -- segments don't lock the storage anymore but has own lock. This could be- removed but it will tested for a while - update and delete record operations- lock the storage in exclusive mode, but probably this can be optimized in the- next future ---",c,https://github.com/orientechnologies/orientdb,"diff --git a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptive.java b/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptive.java index 6844f13dd9c..abb34c5b199 100644 --- a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptive.java +++ b/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptive.java @@ -5,52 +5,32 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; public class OSharedResourceAdaptive { - private static final int UNLOCKED_WAIT_TIME = 30; - private ReadWriteLock lock = new ReentrantReadWriteLock(); - private AtomicInteger users = new AtomicInteger(0); - private volatile boolean runningWithoutLock = false; + private ReadWriteLock lock = new ReentrantReadWriteLock(); + private AtomicInteger users = new AtomicInteger(0); + private final boolean concurrent; - protected boolean acquireExclusiveLock() { - if (users.get() > 1) { - lock.writeLock().lock(); - - if (runningWithoutLock) - // WAIT UNTIL THE UNIQUE THREAD IS RUNNING WITHOUT LOCK FINISHES - while (runningWithoutLock) - try { - Thread.sleep(UNLOCKED_WAIT_TIME); - } catch (InterruptedException e) { - } - - return true; - } + public OSharedResourceAdaptive(final boolean iConcurrent) { + this.concurrent = iConcurrent; + } - runningWithoutLock = true; - return false; + protected void acquireExclusiveLock() { + if (concurrent) + lock.writeLock().lock(); } - protected boolean acquireSharedLock() { - if (users.get() > 1) { + protected void acquireSharedLock() { + if (concurrent) lock.readLock().lock(); - return true; - } - - runningWithoutLock = true; - return false; } - protected void releaseExclusiveLock(final boolean iLocked) { - if (iLocked) + protected void releaseExclusiveLock() { + if (concurrent) lock.writeLock().unlock(); - else - runningWithoutLock = false; } - protected void releaseSharedLock(final boolean iLocked) { - if (iLocked) + protected void releaseSharedLock() { + if (concurrent) lock.readLock().unlock(); - else - runningWithoutLock = false; } public int getUsers() { @@ -58,28 +38,18 @@ public int getUsers() { } public int addUser() { - // ASSURE TO ACQUIRE THE LOCK FIRST - lock.writeLock().lock(); - - try { - return users.incrementAndGet(); - - } finally { - lock.writeLock().unlock(); - } + return users.incrementAndGet(); } public int removeUser() { if (users.get() < 1) throw new IllegalStateException(""Can't remove user of the shared resource "" + toString() + "" because no user is using it""); - try { - lock.writeLock().lock(); - - return users.decrementAndGet(); + return users.decrementAndGet(); + } - } finally { - lock.writeLock().unlock(); - } + public boolean isConcurrent() { + return concurrent; } + } diff --git a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveExternal.java b/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveExternal.java index 5dd74bdf7cb..5991277f69e 100644 --- a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveExternal.java +++ b/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveExternal.java @@ -1,29 +1,33 @@ package com.orientechnologies.common.concur.resource; /** - * Optimize locks since they are enabled only when the resources is really shared among 2 or more users. + * Optimize locks since they are enabled only when the engine runs in MULTI-THREADS mode. * * @author Luca Garulli * */ public class OSharedResourceAdaptiveExternal extends OSharedResourceAdaptive { + public OSharedResourceAdaptiveExternal(final boolean iConcurrent) { + super(iConcurrent); + } + @Override - public boolean acquireExclusiveLock() { - return super.acquireExclusiveLock(); + public void acquireExclusiveLock() { + super.acquireExclusiveLock(); } @Override - public boolean acquireSharedLock() { - return super.acquireSharedLock(); + public void acquireSharedLock() { + super.acquireSharedLock(); } @Override - public void releaseExclusiveLock(final boolean iLocked) { - super.releaseExclusiveLock(iLocked); + public void releaseExclusiveLock() { + super.releaseExclusiveLock(); } @Override - public void releaseSharedLock(final boolean iLocked) { - super.releaseSharedLock(iLocked); + public void releaseSharedLock() { + super.releaseSharedLock(); } } diff --git a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveLinked.java b/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveLinked.java deleted file mode 100644 index b74ec0cfff9..00000000000 --- a/commons/src/main/java/com/orientechnologies/common/concur/resource/OSharedResourceAdaptiveLinked.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.orientechnologies.common.concur.resource; - -/** - * Optimize locks since they are enabled only when the resources is really shared among 2 or more users. - * - * @author Luca Garulli - * - */ -public class OSharedResourceAdaptiveLinked extends OSharedResourceAbstract { - private OSharedResourceAdaptive source; - - public OSharedResourceAdaptiveLinked(OSharedResourceAdaptive source) { - this.source = source; - } - - @Override - protected void acquireExclusiveLock() { - if (source.getUsers() > 1) - super.acquireExclusiveLock(); - } - - @Override - protected void acquireSharedLock() { - if (source.getUsers() > 1) - super.acquireSharedLock(); - } - - @Override - protected void releaseExclusiveLock() { - if (source.getUsers() > 1) - super.releaseExclusiveLock(); - } - - @Override - protected void releaseSharedLock() { - if (source.getUsers() > 1) - super.releaseSharedLock(); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java index aa07f14dda5..32e5cae9435 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java +++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java @@ -34,6 +34,11 @@ * */ public enum OGlobalConfiguration { + // ENVIRONMENT + ENVIRONMENT_CONCURRENT(""environment.concurrent"", + ""Tells if runs in multi-threads environment. Setting this to false turns off the internal lock management"", Boolean.class, + Boolean.TRUE), + // MEMORY MEMORY_OPTIMIZE_THRESHOLD(""memory.optimizeThreshold"", ""Threshold of heap memory where to start the optimization of memory usage. "", Float.class, 0.85, diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java index f1da38fb1f8..37322b19668 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java @@ -32,7 +32,8 @@ public abstract class OStorageAbstract extends OSharedContainerImpl implements O protected OLevel2RecordCache level2Cache; protected volatile boolean open = false; - protected OSharedResourceAdaptiveExternal lock = new OSharedResourceAdaptiveExternal(); + protected OSharedResourceAdaptiveExternal lock = new OSharedResourceAdaptiveExternal( + OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean()); public OStorageAbstract(final String iName, final String iFilePath, final String iMode) { if (OStringSerializerHelper.contains(iName, '/')) diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSegment.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSegment.java index d8ea61a3a3c..9130a983966 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSegment.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSegment.java @@ -15,14 +15,15 @@ */ package com.orientechnologies.orient.core.storage.impl.local; -import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveLinked; +import com.orientechnologies.common.concur.resource.OSharedResourceAdaptive; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; -public abstract class OSegment extends OSharedResourceAdaptiveLinked { +public abstract class OSegment extends OSharedResourceAdaptive { protected OStorageLocal storage; protected String name; public OSegment(final OStorageLocal iStorage, String iName) { - super(iStorage.getLock()); + super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean()); storage = iStorage; name = iName; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSingleFileSegment.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSingleFileSegment.java index 4c145a9766c..506b4a7ffdd 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSingleFileSegment.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OSingleFileSegment.java @@ -17,21 +17,23 @@ import java.io.IOException; -import com.orientechnologies.common.concur.resource.OSharedResourceAdaptiveLinked; +import com.orientechnologies.common.concur.resource.OSharedResourceAdaptive; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.common.log.OLogManager; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.config.OStorageFileConfiguration; import com.orientechnologies.orient.core.storage.fs.OFile; import com.orientechnologies.orient.core.storage.fs.OFileFactory; import com.orientechnologies.orient.core.storage.fs.OMMapManager; -public class OSingleFileSegment extends OSharedResourceAdaptiveLinked { +public class OSingleFileSegment extends OSharedResourceAdaptive { protected OStorageLocal storage; protected OFile file; protected OStorageFileConfiguration config; public OSingleFileSegment(OStorageLocal iStorage, final OStorageFileConfiguration iConfig) throws IOException { - super(iStorage.getLock()); + super(OGlobalConfiguration.ENVIRONMENT_CONCURRENT.getValueAsBoolean()); + config = iConfig; storage = iStorage; file = OFileFactory.create(iConfig.type, iStorage.getVariableParser().resolveVariables(iConfig.path), iStorage.getMode()); diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java index 8aa93d2ffc4..f484d1f576f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java @@ -111,7 +111,7 @@ public OStorageLocal(final String iName, final String iFilePath, final String iM public synchronized void open(final String iUserName, final String iUserPassword, final Map iProperties) { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { if (open) @@ -199,7 +199,7 @@ public synchronized void open(final String iUserName, final String iUserPassword clusterMap.clear(); throw new OStorageException(""Can't open local storage: "" + url + "", with mode="" + mode, e); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(""storage."" + name + "".open"", timer); } @@ -208,7 +208,7 @@ public synchronized void open(final String iUserName, final String iUserPassword public void create(final Map iProperties) { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { if (open) @@ -248,7 +248,7 @@ public void create(final Map iProperties) { throw new OStorageException(""Error on creation of storage: "" + name, e); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(""storage."" + name + "".create"", timer); } @@ -265,7 +265,7 @@ private boolean exists(String path) { public void close(final boolean iForce) { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { if (!checkForClose(iForce)) @@ -297,7 +297,7 @@ public void close(final boolean iForce) { OLogManager.instance().error(this, ""Error on closing of the storage '"" + name, e, OStorageException.class); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(""storage."" + name + "".close"", timer); } @@ -330,7 +330,7 @@ public void delete() { if (!dbDir.exists() || !dbDir.isDirectory()) dbDir = dbDir.getParentFile(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { // RETRIES @@ -374,7 +374,7 @@ public void delete() { throw new OStorageException(""Can't delete database '"" + name + ""' located in: "" + dbDir + "". Database files seems locked""); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(""storage."" + name + "".delete"", timer); } @@ -383,7 +383,7 @@ public void delete() { public ODataLocal getDataSegment(final int iDataSegmentId) { checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { if (iDataSegmentId >= dataSegments.length) @@ -392,7 +392,7 @@ public ODataLocal getDataSegment(final int iDataSegmentId) { return dataSegments[iDataSegmentId]; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -409,7 +409,7 @@ public int addDataSegment(String iSegmentName, final String iSegmentFileName) { iSegmentName = iSegmentName.toLowerCase(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { final OStorageDataConfiguration conf = new OStorageDataConfiguration(configuration, iSegmentName); @@ -430,7 +430,7 @@ public int addDataSegment(String iSegmentName, final String iSegmentFileName) { return -1; } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -484,7 +484,7 @@ public OStorageLocalTxExecuter getTxManager() { } public boolean dropCluster(final int iClusterId) { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { if (iClusterId < 0 || iClusterId >= clusters.length) @@ -511,7 +511,7 @@ public boolean dropCluster(final int iClusterId) { OLogManager.instance().exception(""Error while removing cluster '"" + iClusterId + ""'"", e, OStorageException.class); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } return false; @@ -520,7 +520,7 @@ public boolean dropCluster(final int iClusterId) { public long count(final int[] iClusterIds) { checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { long tot = 0; @@ -538,7 +538,7 @@ public long count(final int[] iClusterIds) { return tot; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -548,7 +548,7 @@ public long[] getClusterDataRange(final int iClusterId) { checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { return clusters[iClusterId] != null ? new long[] { clusters[iClusterId].getFirstEntryPosition(), @@ -560,7 +560,7 @@ public long[] getClusterDataRange(final int iClusterId) { return null; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -571,13 +571,13 @@ public long count(final int iClusterId) { // COUNT PHYSICAL CLUSTER IF ANY checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { return clusters[iClusterId] != null ? clusters[iClusterId].getEntries() : 0l; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -606,13 +606,13 @@ public boolean deleteRecord(final ORecordId iRid, final int iVersion) { public Set getClusterNames() { checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { return clusterMap.keySet(); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -631,13 +631,13 @@ public int getClusterIdByName(final String iClusterName) { // SEARCH IT BETWEEN PHYSICAL CLUSTERS OCluster segment; - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { segment = clusterMap.get(iClusterName.toLowerCase()); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } if (segment != null) @@ -655,13 +655,13 @@ public String getClusterTypeByName(final String iClusterName) { // SEARCH IT BETWEEN PHYSICAL CLUSTERS OCluster segment; - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { segment = clusterMap.get(iClusterName.toLowerCase()); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } if (segment != null) @@ -671,7 +671,7 @@ public String getClusterTypeByName(final String iClusterName) { } public void commit(final OTransaction iTx) { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { txManager.commitAllPendingRecords((OTransactionRealAbstract) iTx); @@ -684,7 +684,7 @@ public void commit(final OTransaction iTx) { rollback(iTx); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -696,7 +696,7 @@ public void synch() { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { saveVersion(); @@ -711,7 +711,7 @@ public void synch() { throw new OStorageException(""Error on synch"", e); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(""storage."" + name + "".synch"", timer); } @@ -725,7 +725,7 @@ public void synch() { public List getHolesList() { final List holes = new ArrayList(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { for (ODataLocal d : dataSegments) { @@ -734,7 +734,7 @@ public List getHolesList() { return holes; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -744,7 +744,7 @@ public List getHolesList() { * @throws IOException */ public long getHoles() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { long holes = 0; @@ -753,7 +753,7 @@ public long getHoles() { return holes; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -763,7 +763,7 @@ public long getHoles() { * @throws IOException */ public long getHoleSize() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { final List holes = getHolesList(); @@ -775,14 +775,14 @@ public long getHoleSize() { return size; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } public String getPhysicalClusterNameById(final int iClusterId) { checkOpeness(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { if (iClusterId >= clusters.length) @@ -791,7 +791,7 @@ public String getPhysicalClusterNameById(final int iClusterId) { return clusters[iClusterId] != null ? clusters[iClusterId].getName() : null; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -805,7 +805,7 @@ public int getDefaultClusterId() { } public OCluster getClusterById(int iClusterId) { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { if (iClusterId == ORID.CLUSTER_ID_INVALID) @@ -817,13 +817,13 @@ public OCluster getClusterById(int iClusterId) { return clusters[iClusterId]; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @Override public OCluster getClusterByName(final String iClusterName) { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); @@ -833,12 +833,12 @@ public OCluster getClusterByName(final String iClusterName) { return cluster; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } public long getSize() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { long size = 0; @@ -853,7 +853,7 @@ public long getSize() { return size; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -876,7 +876,7 @@ public OStorageVariableParser getVariableParser() { public Set getClusters() { final Set result = new HashSet(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { // ADD ALL THE CLUSTERS @@ -884,7 +884,7 @@ public Set getClusters() { result.add(c); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } return result; @@ -983,7 +983,7 @@ protected long createRecord(final OCluster iClusterSegment, final byte[] iConten final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { lockManager.acquireLock(Thread.currentThread(), ORecordId.EMPTY_RECORD_ID, LOCK.EXCLUSIVE); @@ -1013,7 +1013,7 @@ protected long createRecord(final OCluster iClusterSegment, final byte[] iConten OLogManager.instance().error(this, ""Error on creating record in cluster: "" + iClusterSegment, e); return -1; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); OProfiler.getInstance().stopChrono(PROFILER_CREATE_RECORD, timer); } @@ -1031,7 +1031,9 @@ protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId // USUALLY BROWSING OPERATIONS (QUERY) AVOID ATOMIC LOCKING // TO IMPROVE PERFORMANCES BY LOCKING THE ENTIRE CLUSTER FROM THE // OUTSIDE. - final boolean locked = iAtomicLock ? lock.acquireSharedLock() : false; + if (iAtomicLock) + lock.acquireSharedLock(); + try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.SHARED); @@ -1061,7 +1063,8 @@ protected ORawBuffer readRecord(final OCluster iClusterSegment, final ORecordId return null; } finally { - lock.releaseSharedLock(locked); + if (iAtomicLock) + lock.releaseSharedLock(); OProfiler.getInstance().stopChrono(PROFILER_READ_RECORD, timer); } @@ -1071,7 +1074,7 @@ protected int updateRecord(final OCluster iClusterSegment, final ORecordId iRid, final byte iRecordType) { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireExclusiveLock(); try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); @@ -1118,7 +1121,7 @@ protected int updateRecord(final OCluster iClusterSegment, final ORecordId iRid, OLogManager.instance().error(this, ""Error on updating record "" + iRid + "" (cluster: "" + iClusterSegment + "")"", e); } finally { - lock.releaseSharedLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(PROFILER_UPDATE_RECORD, timer); } @@ -1129,7 +1132,7 @@ protected int updateRecord(final OCluster iClusterSegment, final ORecordId iRid, protected boolean deleteRecord(final OCluster iClusterSegment, final ORecordId iRid, final int iVersion) { final long timer = OProfiler.getInstance().startChrono(); - final boolean locked = lock.acquireSharedLock(); + lock.acquireExclusiveLock(); try { lockManager.acquireLock(Thread.currentThread(), iRid, LOCK.EXCLUSIVE); @@ -1166,7 +1169,7 @@ protected boolean deleteRecord(final OCluster iClusterSegment, final ORecordId i OLogManager.instance().error(this, ""Error on deleting record "" + iRid + ""( cluster: "" + iClusterSegment + "")"", e); } finally { - lock.releaseSharedLock(locked); + lock.releaseExclusiveLock(); OProfiler.getInstance().stopChrono(PROFILER_DELETE_RECORD, timer); } @@ -1180,13 +1183,13 @@ protected boolean deleteRecord(final OCluster iClusterSegment, final ORecordId i * @throws IOException */ private void saveVersion() throws IOException { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { dataSegments[0].saveVersion(version); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -1197,13 +1200,13 @@ private void saveVersion() throws IOException { * @throws IOException */ private long loadVersion() throws IOException { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { return version = dataSegments[0].loadVersion(); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -1213,7 +1216,7 @@ private long loadVersion() throws IOException { * @throws IOException */ private int addPhysicalCluster(final String iClusterName, String iClusterFileName, final int iStartSize) throws IOException { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { final OStoragePhysicalClusterConfiguration config = new OStoragePhysicalClusterConfiguration(configuration, iClusterName, @@ -1228,12 +1231,12 @@ private int addPhysicalCluster(final String iClusterName, String iClusterFileNam return id; } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } private int addLogicalCluster(final String iClusterName, final int iPhysicalCluster) throws IOException { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { final OStorageLogicalClusterConfiguration config = new OStorageLogicalClusterConfiguration(iClusterName, clusters.length, @@ -1249,12 +1252,12 @@ private int addLogicalCluster(final String iClusterName, final int iPhysicalClus return id; } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } private int addMemoryCluster(final String iClusterName) throws IOException { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { final OStorageMemoryClusterConfiguration config = new OStorageMemoryClusterConfiguration(iClusterName, clusters.length); @@ -1268,7 +1271,7 @@ private int addMemoryCluster(final String iClusterName) throws IOException { return id; } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java index 62706af4a9e..ec9e76f6bb1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java @@ -70,7 +70,7 @@ public OStorageMemory(final String iURL) { public void create(final Map iOptions) { addUser(); - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { addDataSegment(OStorage.DATA_DEFAULT_NAME); @@ -97,7 +97,7 @@ public void create(final Map iOptions) { throw new OStorageException(""Error on creation of storage: "" + name, e); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -109,7 +109,7 @@ public void open(final String iUserName, final String iUserPassword, final Map getClusterNames() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { Set result = new HashSet(); @@ -421,12 +421,12 @@ public Set getClusterNames() { return result; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } public void commit(final OTransaction iTx) { - final boolean locked = lock.acquireExclusiveLock(); + lock.acquireExclusiveLock(); try { final List allEntries = new ArrayList(); @@ -454,7 +454,7 @@ public void commit(final OTransaction iTx) { rollback(iTx); } finally { - lock.releaseExclusiveLock(locked); + lock.releaseExclusiveLock(); } } @@ -468,18 +468,18 @@ public void browse(final int[] iClusterId, final ORecordBrowsingListener iListen } public boolean exists() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { return clusters.size() > 0; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } public OCluster getClusterById(int iClusterId) { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { if (iClusterId == ORID.CLUSTER_ID_INVALID) @@ -489,18 +489,18 @@ public OCluster getClusterById(int iClusterId) { return clusters.get(iClusterId); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } public Collection getClusters() { - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { return Collections.unmodifiableCollection(clusters); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } } @@ -511,14 +511,14 @@ public int getDefaultClusterId() { public long getSize() { long size = 0; - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { size += data.getSize(); for (OClusterMemory c : clusters) size += c.getSize(); } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } return size; } @@ -528,14 +528,14 @@ public boolean checkForRecordValidity(final OPhysicalPosition ppos) { if (ppos.dataSegment > 0) return false; - final boolean locked = lock.acquireSharedLock(); + lock.acquireSharedLock(); try { if (ppos.dataPosition >= data.count()) return false; } finally { - lock.releaseSharedLock(locked); + lock.releaseSharedLock(); } return true; }" 9d2ba02ac12cb561895cbbc7652e55dac49a30d8,camel,CAMEL-1004 - added a ServiceStatus property to- most Service implementations - and exposed the status of a route--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@748071 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/CamelContext.java b/camel-core/src/main/java/org/apache/camel/CamelContext.java index 9db3fb088b53d..82b5b4201de5a 100644 --- a/camel-core/src/main/java/org/apache/camel/CamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/CamelContext.java @@ -333,4 +333,9 @@ public interface CamelContext extends Service { * @return the factory finder */ FactoryFinder createFactoryFinder(String path); + + /** + * Returns the current status of the given route + */ + ServiceStatus getRouteStatus(RouteType route); } diff --git a/camel-core/src/main/java/org/apache/camel/ServiceStatus.java b/camel-core/src/main/java/org/apache/camel/ServiceStatus.java new file mode 100644 index 0000000000000..a8d601b311f5f --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/ServiceStatus.java @@ -0,0 +1,27 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the ""License""); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel; + +/** + * Reresents the status of a {@link Service} instance + * + * @version $Revision: 1.1 $ + */ +public enum ServiceStatus { + Created, Starting, Started, Stopping, Stopped; +} diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index 2e7257bed41d9..f17b70fc7741a 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -39,6 +39,7 @@ import org.apache.camel.RuntimeCamelException; import org.apache.camel.Service; import org.apache.camel.TypeConverter; +import org.apache.camel.ServiceStatus; import org.apache.camel.builder.ErrorHandlerBuilder; import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.management.InstrumentationLifecycleStrategy; @@ -435,6 +436,21 @@ public void removeRouteDefinitions(Collection routeDefinitions) throw } + public ServiceStatus getRouteStatus(RouteType route) { + return getRouteStatus(route.idOrCreate()); + } + + /** + * Returns the status of the service of the given ID or null if there is no service created yet + */ + public ServiceStatus getRouteStatus(String key) { + RouteService routeService = routeServices.remove(key); + if (routeService != null) { + return routeService.getStatus(); + } + return null; + } + public void startRoute(RouteType route) throws Exception { Collection routes = new ArrayList(); List routeContexts = route.addRoutes(this, routes); @@ -444,9 +460,21 @@ public void startRoute(RouteType route) throws Exception { public void stopRoute(RouteType route) throws Exception { - stopRouteService(route.idOrCreate()); + stopRoute(route.idOrCreate()); } + /** + * Stops the route denoted by the given RouteType id + */ + public synchronized void stopRoute(String key) throws Exception { + RouteService routeService = routeServices.remove(key); + if (routeService != null) { + routeService.stop(); + } + } + + + /** * Adds a service, starting it so that it will be stopped with this context */ @@ -726,22 +754,13 @@ protected void startRoutes(Collection routeList) throws Exception { */ protected synchronized void startRouteService(RouteService routeService) throws Exception { String key = routeService.getId(); - stopRouteService(key); + stopRoute(key); routeServices.put(key, routeService); if (shouldStartRoutes()) { routeService.start(); } } - /** - * Stops the route denoted by the given RouteType id - */ - protected synchronized void stopRouteService(String key) throws Exception { - RouteService routeService = routeServices.remove(key); - if (routeService != null) { - routeService.stop(); - } - } protected synchronized void doStop() throws Exception { diff --git a/camel-core/src/main/java/org/apache/camel/impl/ServiceSupport.java b/camel-core/src/main/java/org/apache/camel/impl/ServiceSupport.java index 16e5c0ef34ea4..35b7951048f2d 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/ServiceSupport.java +++ b/camel-core/src/main/java/org/apache/camel/impl/ServiceSupport.java @@ -21,6 +21,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.camel.Service; +import org.apache.camel.ServiceStatus; import org.apache.camel.util.ObjectHelper; import org.apache.camel.util.ServiceHelper; @@ -68,6 +69,26 @@ public void stop() throws Exception { } } + /** + * Returns the current status + */ + public ServiceStatus getStatus() { + // lets check these in oldest first as these flags can be changing in a concurrent world + if (isStarting()) { + return ServiceStatus.Starting; + } + if (isStarted()) { + return ServiceStatus.Started; + } + if (isStopping()) { + return ServiceStatus.Stopping; + } + if (isStopped()) { + return ServiceStatus.Stopped; + } + return ServiceStatus.Created; + } + /** * @return true if this service has been started */" fa8fcb53c58b5759ad500fdaf50a66ccb8c08a12,kotlin,Introduce Variable: Forbid extraction from class- initializer (aside of its body) -KT-8329 Fixed--,c,https://github.com/JetBrains/kotlin,"diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java index b458f0b15be14..44767692efad2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java @@ -330,8 +330,7 @@ private void run( JetProperty property = psiFactory.createProperty(variableText); PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces); if (anchor == null) return; - boolean needBraces = !(commonContainer instanceof JetBlockExpression || - commonContainer instanceof JetClassInitializer); + boolean needBraces = !(commonContainer instanceof JetBlockExpression); if (!needBraces) { property = (JetProperty)commonContainer.addBefore(property, anchor); commonContainer.addBefore(psiFactory.createNewLine(), anchor); @@ -548,7 +547,7 @@ private static boolean shouldReplaceOccurrence( @Nullable private static PsiElement getContainer(PsiElement place) { - if (place instanceof JetBlockExpression || place instanceof JetClassInitializer) { + if (place instanceof JetBlockExpression) { return place; } while (place != null) { @@ -559,8 +558,7 @@ private static PsiElement getContainer(PsiElement place) { } } if (parent instanceof JetBlockExpression - || (parent instanceof JetWhenEntry && place == ((JetWhenEntry) parent).getExpression()) - || parent instanceof JetClassInitializer) { + || (parent instanceof JetWhenEntry && place == ((JetWhenEntry) parent).getExpression())) { return parent; } if (parent instanceof JetDeclarationWithBody && ((JetDeclarationWithBody) parent).getBodyExpression() == place) { @@ -596,7 +594,7 @@ private static PsiElement getOccurrenceContainer(PsiElement place) { result = parent; } } - else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) { + else if (parent instanceof JetClassBody || parent instanceof JetFile) { return result; } else if (parent instanceof JetBlockExpression) { diff --git a/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt new file mode 100644 index 0000000000000..ace8099d55bee --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt @@ -0,0 +1,4 @@ +class C { + deprecated("""") + init {} +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts new file mode 100644 index 0000000000000..1568c6aea626f --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts @@ -0,0 +1 @@ +Cannot refactor in this place diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java index 2d1b47fe1da96..507243e27052b 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java @@ -145,6 +145,12 @@ public void testIfThenValuedAddBlock() throws Exception { doIntroduceVariableTest(fileName); } + @TestMetadata(""InsideOfInitializerAnnotation.kt"") + public void testInsideOfInitializerAnnotation() throws Exception { + String fileName = JetTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt""); + doIntroduceVariableTest(fileName); + } + @TestMetadata(""IntroduceAndCreateBlock.kt"") public void testIntroduceAndCreateBlock() throws Exception { String fileName = JetTestUtils.navigationMetadata(""idea/testData/refactoring/introduceVariable/IntroduceAndCreateBlock.kt"");" c63e3f027bfe01e421fb692f6a86bcf1a4cecc5f,hadoop,"Merge r1606407 from trunk. YARN-614. Changed- ResourceManager to not count disk failure, node loss and RM restart towards- app failures. Contributed by Xuan Gong--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1606408 13f79535-47bb-0310-9956-ffa450edef68-",a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 5fa2745426540..670355e9480c9 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -180,6 +180,9 @@ Release 2.5.0 - UNRELEASED YARN-2171. Improved CapacityScheduling to not lock on nodemanager-count when AMs heartbeat in. (Jason Lowe via vinodkv) + YARN-614. Changed ResourceManager to not count disk failure, node loss and + RM restart towards app failures. (Xuan Gong via jianhe) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java index b6ca684a7393f..bff41cfc219aa 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java @@ -687,9 +687,10 @@ private void createNewAttempt() { new RMAppAttemptImpl(appAttemptId, rmContext, scheduler, masterService, submissionContext, conf, // The newly created attempt maybe last attempt if (number of - // previously NonPreempted attempts + 1) equal to the max-attempt + // previously failed attempts(which should not include Preempted, + // hardware error and NM resync) + 1) equal to the max-attempt // limit. - maxAppAttempts == (getNumNonPreemptedAppAttempts() + 1)); + maxAppAttempts == (getNumFailedAppAttempts() + 1)); attempts.put(appAttemptId, attempt); currentAttempt = attempt; } @@ -797,7 +798,7 @@ public RMAppState transition(RMAppImpl app, RMAppEvent event) { && (app.currentAttempt.getState() == RMAppAttemptState.KILLED || app.currentAttempt.getState() == RMAppAttemptState.FINISHED || (app.currentAttempt.getState() == RMAppAttemptState.FAILED - && app.getNumNonPreemptedAppAttempts() == app.maxAppAttempts))) { + && app.getNumFailedAppAttempts() == app.maxAppAttempts))) { return RMAppState.ACCEPTED; } @@ -888,7 +889,7 @@ private String getAppAttemptFailedDiagnostics(RMAppEvent event) { msg = ""Unmanaged application "" + this.getApplicationId() + "" failed due to "" + failedEvent.getDiagnostics() + "". Failing the application.""; - } else if (getNumNonPreemptedAppAttempts() >= this.maxAppAttempts) { + } else if (getNumFailedAppAttempts() >= this.maxAppAttempts) { msg = ""Application "" + this.getApplicationId() + "" failed "" + this.maxAppAttempts + "" times due to "" + failedEvent.getDiagnostics() + "". Failing the application.""; @@ -1105,11 +1106,12 @@ public void transition(RMAppImpl app, RMAppEvent event) { }; } - private int getNumNonPreemptedAppAttempts() { + private int getNumFailedAppAttempts() { int completedAttempts = 0; - // Do not count AM preemption as attempt failure. + // Do not count AM preemption, hardware failures or NM resync + // as attempt failure. for (RMAppAttempt attempt : attempts.values()) { - if (!attempt.isPreempted()) { + if (attempt.shouldCountTowardsMaxAttemptRetry()) { completedAttempts++; } } @@ -1129,7 +1131,7 @@ public AttemptFailedTransition(RMAppState initialState) { public RMAppState transition(RMAppImpl app, RMAppEvent event) { if (!app.submissionContext.getUnmanagedAM() - && app.getNumNonPreemptedAppAttempts() < app.maxAppAttempts) { + && app.getNumFailedAppAttempts() < app.maxAppAttempts) { boolean transferStateFromPreviousAttempt = false; RMAppFailedAttemptEvent failedEvent = (RMAppFailedAttemptEvent) event; transferStateFromPreviousAttempt = diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttempt.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttempt.java index 42c37a93aba7f..68a068b98116d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttempt.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttempt.java @@ -197,8 +197,14 @@ public interface RMAppAttempt extends EventHandler { ApplicationAttemptReport createApplicationAttemptReport(); /** - * Return the flag which indicates whether the attempt is preempted by the - * scheduler. - */ - boolean isPreempted(); + * Return the flag which indicates whether the attempt failure should be + * counted to attempt retry count. + *
        + * There failure types should not be counted to attempt retry count: + *
      • preempted by the scheduler.
      • + *
      • hardware failures, such as NM failing, lost NM and NM disk errors.
      • + *
      • killed by RM because of RM restart or failover.
      • + *
      + */ + boolean shouldCountTowardsMaxAttemptRetry(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java index 1e7693f5b71c8..ef572d42daa37 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java @@ -149,9 +149,10 @@ public class RMAppAttemptImpl implements RMAppAttempt, Recoverable { private int amContainerExitStatus = ContainerExitStatus.INVALID; private Configuration conf; - // Since AM preemption is not counted towards AM failure count, - // even if this flag is true, a new attempt can still be re-created if this - // attempt is eventually preempted. So this flag indicates that this may be + // Since AM preemption, hardware error and NM resync are not counted towards + // AM failure count, even if this flag is true, a new attempt can still be + // re-created if this attempt is eventually failed because of preemption, + // hardware error or NM resync. So this flag indicates that this may be // last attempt. private final boolean maybeLastAttempt; private static final ExpiredTransition EXPIRED_TRANSITION = @@ -1087,12 +1088,13 @@ public void transition(RMAppAttemptImpl appAttempt, .getKeepContainersAcrossApplicationAttempts() && !appAttempt.submissionContext.getUnmanagedAM()) { // See if we should retain containers for non-unmanaged applications - if (appAttempt.isPreempted()) { - // Premption doesn't count towards app-failures and so we should - // retain containers. + if (!appAttempt.shouldCountTowardsMaxAttemptRetry()) { + // Premption, hardware failures, NM resync doesn't count towards + // app-failures and so we should retain containers. keepContainersAcrossAppAttempts = true; } else if (!appAttempt.maybeLastAttempt) { - // Not preemption. Not last-attempt too - keep containers. + // Not preemption, hardware failures or NM resync. + // Not last-attempt too - keep containers. keepContainersAcrossAppAttempts = true; } } @@ -1136,8 +1138,17 @@ public void transition(RMAppAttemptImpl appAttempt, } @Override - public boolean isPreempted() { - return getAMContainerExitStatus() == ContainerExitStatus.PREEMPTED; + public boolean shouldCountTowardsMaxAttemptRetry() { + try { + this.readLock.lock(); + int exitStatus = getAMContainerExitStatus(); + return !(exitStatus == ContainerExitStatus.PREEMPTED + || exitStatus == ContainerExitStatus.ABORTED + || exitStatus == ContainerExitStatus.DISKS_FAILED + || exitStatus == ContainerExitStatus.KILLED_BY_RESOURCEMANAGER); + } finally { + this.readLock.unlock(); + } } private static final class UnmanagedAMAttemptSavedTransition diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRestart.java index 4145b6411d8a8..de0987808e6a5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRestart.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRestart.java @@ -19,13 +19,16 @@ package org.apache.hadoop.yarn.server.resourcemanager.applicationsmanager; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerExitStatus; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -34,6 +37,7 @@ import org.apache.hadoop.yarn.api.records.NMToken; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.conf.YarnConfiguration; +import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.resourcemanager.MockAM; import org.apache.hadoop.yarn.server.resourcemanager.MockNM; import org.apache.hadoop.yarn.server.resourcemanager.MockRM; @@ -49,6 +53,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; +import org.apache.hadoop.yarn.util.Records; import org.junit.Assert; import org.junit.Test; @@ -347,15 +352,20 @@ public void testNMTokensRebindOnAMRestart() throws Exception { rm1.stop(); } - // AM container preempted should not be counted towards AM max retry count. - @Test(timeout = 20000) - public void testAMPreemptedNotCountedForAMFailures() throws Exception { + // AM container preempted, nm disk failure + // should not be counted towards AM max retry count. + @Test(timeout = 100000) + public void testShouldNotCountFailureToMaxAttemptRetry() throws Exception { YarnConfiguration conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); // explicitly set max-am-retry count as 1. conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); - MockRM rm1 = new MockRM(conf); + conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); + conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); + MemoryRMStateStore memStore = new MemoryRMStateStore(); + memStore.init(conf); + MockRM rm1 = new MockRM(conf, memStore); rm1.start(); MockNM nm1 = new MockNM(""127.0.0.1:1234"", 8000, rm1.getResourceTrackerService()); @@ -371,8 +381,10 @@ public void testAMPreemptedNotCountedForAMFailures() throws Exception { scheduler.killContainer(scheduler.getRMContainer(amContainer)); am1.waitForState(RMAppAttemptState.FAILED); - Assert.assertTrue(attempt1.isPreempted()); + Assert.assertTrue(! attempt1.shouldCountTowardsMaxAttemptRetry()); rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); + ApplicationState appState = + memStore.getState().getApplicationState().get(app1.getApplicationId()); // AM should be restarted even though max-am-attempt is 1. MockAM am2 = MockRM.launchAndRegisterAM(app1, rm1, nm1); RMAppAttempt attempt2 = app1.getCurrentAppAttempt(); @@ -384,20 +396,62 @@ public void testAMPreemptedNotCountedForAMFailures() throws Exception { scheduler.killContainer(scheduler.getRMContainer(amContainer2)); am2.waitForState(RMAppAttemptState.FAILED); - Assert.assertTrue(attempt2.isPreempted()); + Assert.assertTrue(! attempt2.shouldCountTowardsMaxAttemptRetry()); rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); MockAM am3 = MockRM.launchAndRegisterAM(app1, rm1, nm1); RMAppAttempt attempt3 = app1.getCurrentAppAttempt(); Assert.assertTrue(((RMAppAttemptImpl) attempt3).mayBeLastAttempt()); - // fail the AM normally - nm1.nodeHeartbeat(am3.getApplicationAttemptId(), 1, ContainerState.COMPLETE); + // mimic NM disk_failure + ContainerStatus containerStatus = Records.newRecord(ContainerStatus.class); + containerStatus.setContainerId(attempt3.getMasterContainer().getId()); + containerStatus.setDiagnostics(""mimic NM disk_failure""); + containerStatus.setState(ContainerState.COMPLETE); + containerStatus.setExitStatus(ContainerExitStatus.DISKS_FAILED); + Map> conts = + new HashMap>(); + conts.put(app1.getApplicationId(), + Collections.singletonList(containerStatus)); + nm1.nodeHeartbeat(conts, true); + am3.waitForState(RMAppAttemptState.FAILED); - Assert.assertFalse(attempt3.isPreempted()); + Assert.assertTrue(! attempt3.shouldCountTowardsMaxAttemptRetry()); + Assert.assertEquals(ContainerExitStatus.DISKS_FAILED, + appState.getAttempt(am3.getApplicationAttemptId()) + .getAMContainerExitStatus()); + + rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); + MockAM am4 = MockRM.launchAndRegisterAM(app1, rm1, nm1); + RMAppAttempt attempt4 = app1.getCurrentAppAttempt(); + Assert.assertTrue(((RMAppAttemptImpl) attempt4).mayBeLastAttempt()); + + // create second NM, and register to rm1 + MockNM nm2 = + new MockNM(""127.0.0.1:2234"", 8000, rm1.getResourceTrackerService()); + nm2.registerNode(); + // nm1 heartbeats to report unhealthy + // This will mimic ContainerExitStatus.ABORT + nm1.nodeHeartbeat(false); + am4.waitForState(RMAppAttemptState.FAILED); + Assert.assertTrue(! attempt4.shouldCountTowardsMaxAttemptRetry()); + Assert.assertEquals(ContainerExitStatus.ABORTED, + appState.getAttempt(am4.getApplicationAttemptId()) + .getAMContainerExitStatus()); + // launch next AM in nm2 + nm2.nodeHeartbeat(true); + MockAM am5 = + rm1.waitForNewAMToLaunchAndRegister(app1.getApplicationId(), 5, nm2); + RMAppAttempt attempt5 = app1.getCurrentAppAttempt(); + Assert.assertTrue(((RMAppAttemptImpl) attempt5).mayBeLastAttempt()); + // fail the AM normally + nm2 + .nodeHeartbeat(am5.getApplicationAttemptId(), 1, ContainerState.COMPLETE); + am5.waitForState(RMAppAttemptState.FAILED); + Assert.assertTrue(attempt5.shouldCountTowardsMaxAttemptRetry()); // AM should not be restarted. rm1.waitForState(app1.getApplicationId(), RMAppState.FAILED); - Assert.assertEquals(3, app1.getAppAttempts().size()); + Assert.assertEquals(5, app1.getAppAttempts().size()); rm1.stop(); } @@ -433,7 +487,7 @@ public void testPreemptedAMRestartOnRMRestart() throws Exception { scheduler.killContainer(scheduler.getRMContainer(amContainer)); am1.waitForState(RMAppAttemptState.FAILED); - Assert.assertTrue(attempt1.isPreempted()); + Assert.assertTrue(! attempt1.shouldCountTowardsMaxAttemptRetry()); rm1.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); // state store has 1 attempt stored. @@ -457,11 +511,74 @@ public void testPreemptedAMRestartOnRMRestart() throws Exception { RMAppAttempt attempt2 = rm2.getRMContext().getRMApps().get(app1.getApplicationId()) .getCurrentAppAttempt(); - Assert.assertFalse(attempt2.isPreempted()); + Assert.assertTrue(attempt2.shouldCountTowardsMaxAttemptRetry()); Assert.assertEquals(ContainerExitStatus.INVALID, appState.getAttempt(am2.getApplicationAttemptId()) .getAMContainerExitStatus()); rm1.stop(); rm2.stop(); } + + // Test regular RM restart/failover, new RM should not count + // AM failure towards the max-retry-account and should be able to + // re-launch the AM. + @Test(timeout = 50000) + public void testRMRestartOrFailoverNotCountedForAMFailures() + throws Exception { + YarnConfiguration conf = new YarnConfiguration(); + conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, + ResourceScheduler.class); + conf.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); + conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); + // explicitly set max-am-retry count as 1. + conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1); + MemoryRMStateStore memStore = new MemoryRMStateStore(); + memStore.init(conf); + + MockRM rm1 = new MockRM(conf, memStore); + rm1.start(); + MockNM nm1 = + new MockNM(""127.0.0.1:1234"", 8000, rm1.getResourceTrackerService()); + nm1.registerNode(); + RMApp app1 = rm1.submitApp(200); + // AM should be restarted even though max-am-attempt is 1. + MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); + RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); + Assert.assertTrue(((RMAppAttemptImpl) attempt1).mayBeLastAttempt()); + + // Restart rm. + MockRM rm2 = new MockRM(conf, memStore); + rm2.start(); + ApplicationState appState = + memStore.getState().getApplicationState().get(app1.getApplicationId()); + // re-register the NM + nm1.setResourceTrackerService(rm2.getResourceTrackerService()); + NMContainerStatus status = Records.newRecord(NMContainerStatus.class); + status + .setContainerExitStatus(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER); + status.setContainerId(attempt1.getMasterContainer().getId()); + status.setContainerState(ContainerState.COMPLETE); + status.setDiagnostics(""""); + nm1.registerNode(Collections.singletonList(status), null); + + rm2.waitForState(attempt1.getAppAttemptId(), RMAppAttemptState.FAILED); + Assert.assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER, + appState.getAttempt(am1.getApplicationAttemptId()) + .getAMContainerExitStatus()); + // Will automatically start a new AppAttempt in rm2 + rm2.waitForState(app1.getApplicationId(), RMAppState.ACCEPTED); + MockAM am2 = + rm2.waitForNewAMToLaunchAndRegister(app1.getApplicationId(), 2, nm1); + MockRM.finishAMAndVerifyAppState(app1, rm2, nm1, am2); + RMAppAttempt attempt3 = + rm2.getRMContext().getRMApps().get(app1.getApplicationId()) + .getCurrentAppAttempt(); + Assert.assertTrue(attempt3.shouldCountTowardsMaxAttemptRetry()); + Assert.assertEquals(ContainerExitStatus.INVALID, + appState.getAttempt(am2.getApplicationAttemptId()) + .getAMContainerExitStatus()); + + rm1.stop(); + rm2.stop(); + } }" 6945d04785d7322df45b5c71053ba18431f606cd,orientdb,Further work or traverse: - supported new- OSQLPredicate to specify a predicate using SQL language--,a,https://github.com/orientechnologies/orientdb,"diff --git a/build.number b/build.number index 19e55caca3e..1c3c6d61de5 100644 --- a/build.number +++ b/build.number @@ -1,3 +1,3 @@ #Build Number for ANT. Do not edit! -#Sat Apr 28 19:00:06 CEST 2012 -build.number=11815 +#Sat Apr 28 20:56:54 CEST 2012 +build.number=11818 diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java index 2416ee1d4c8..358eedfa27b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverse.java @@ -45,7 +45,7 @@ public class OTraverse implements OCommand, Iterable, Iterator execute() { final List result = new ArrayList(); while (hasNext()) result.add(next()); @@ -114,6 +114,17 @@ public OTraverseContext getContext() { return context; } + public OTraverse target(final Iterable iTarget) { + return target(iTarget.iterator()); + } + + public OTraverse target(final OIdentifiable... iRecords) { + final List list = new ArrayList(); + for (OIdentifiable id : iRecords) + list.add(id); + return target(list.iterator()); + } + @SuppressWarnings(""unchecked"") public OTraverse target(final Iterator iTarget) { target = iTarget; @@ -147,6 +158,12 @@ public OTraverse fields(final Collection iFields) { return this; } + public OTraverse fields(final String... iFields) { + for (String f : iFields) + field(f); + return this; + } + public List getFields() { return fields; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java index 297e8846907..47f06163454 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OTraverseContext.java @@ -28,9 +28,9 @@ public class OTraverseContext implements OCommandContext { private OCommandContext nestedStack; - private Set allTraversed = new HashSet(); - private List> stack = new ArrayList>(); - private int depth = -1; + private Set history = new HashSet(); + private List> stack = new ArrayList>(); + private int depth = -1; public void push(final OTraverseAbstractProcess iProcess) { stack.add(iProcess); @@ -55,11 +55,11 @@ public void reset() { } public boolean isAlreadyTraversed(final OIdentifiable identity) { - return allTraversed.contains(identity.getIdentity()); + return history.contains(identity.getIdentity()); } public void addTraversed(final OIdentifiable identity) { - allTraversed.add(identity.getIdentity()); + history.add(identity.getIdentity()); } public int incrementDepth() { @@ -77,6 +77,8 @@ else if (""path"".equalsIgnoreCase(iName)) return getPath(); else if (""stack"".equalsIgnoreCase(iName)) return stack; + else if (""history"".equalsIgnoreCase(iName)) + return history; else if (nestedStack != null) // DELEGATE nestedStack.getVariable(iName); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java index 11f34176254..e1668449d26 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLHelper.java @@ -39,6 +39,7 @@ import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField; import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemParameter; import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemVariable; +import com.orientechnologies.orient.core.sql.filter.OSQLPredicate; import com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime; /** @@ -182,7 +183,7 @@ else if (t == OType.DATE || t == OType.DATETIME) return null; } - public static Object parseValue(final OSQLFilter iSQLFilter, final OCommandToParse iCommand, final String iWord, + public static Object parseValue(final OSQLPredicate iSQLFilter, final OCommandToParse iCommand, final String iWord, final OCommandContext iContext) { if (iWord.charAt(0) == OStringSerializerHelper.PARAMETER_POSITIONAL || iWord.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java index 4c15ece5ec2..7a23f87dcc7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilter.java @@ -17,27 +17,20 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; import com.orientechnologies.common.parser.OStringParser; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.command.OCommandExecutor; import com.orientechnologies.orient.core.command.OCommandManager; import com.orientechnologies.orient.core.command.OCommandPredicate; -import com.orientechnologies.orient.core.command.OCommandToParse; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.exception.OQueryParsingException; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordSchemaAware; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; @@ -46,11 +39,7 @@ import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.OCommandSQLParsingException; import com.orientechnologies.orient.core.sql.OCommandSQLResultset; -import com.orientechnologies.orient.core.sql.OSQLEngine; import com.orientechnologies.orient.core.sql.OSQLHelper; -import com.orientechnologies.orient.core.sql.operator.OQueryOperator; -import com.orientechnologies.orient.core.sql.operator.OQueryOperatorNot; -import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; /** * Parsed query. It's built once a query is parsed. @@ -58,26 +47,19 @@ * @author Luca Garulli * */ -public class OSQLFilter extends OCommandToParse implements OCommandPredicate { - protected ODatabaseRecord database; +public class OSQLFilter extends OSQLPredicate implements OCommandPredicate { protected Iterable targetRecords; protected Map targetClusters; protected Map targetClasses; protected String targetIndex; - protected Set properties = new HashSet(); - protected OSQLFilterCondition rootCondition; - protected List recordTransformed; - protected List parameterItems; - protected int braces; - private OCommandContext context; public OSQLFilter(final String iText, final OCommandContext iContext) { + super(); context = iContext; - try { - database = ODatabaseRecordThreadLocal.INSTANCE.get(); - text = iText; - textUpperCase = text.toUpperCase(Locale.ENGLISH); + text = iText; + textUpperCase = iText.toUpperCase(); + try { if (extractTargets()) { // IF WHERE EXISTS EXTRACT CONDITIONS @@ -85,8 +67,17 @@ public OSQLFilter(final String iText, final OCommandContext iContext) { int newPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, true); if (newPos > -1) { if (word.toString().equals(OCommandExecutorSQLAbstract.KEYWORD_WHERE)) { - currentPos = newPos; - rootCondition = (OSQLFilterCondition) extractConditions(null); + final int lastPos = newPos; + final String lastText = text; + final String lastTextUpperCase = textUpperCase; + + text(text.substring(newPos)); + + if (currentPos > -1) + currentPos += lastPos; + text = lastText; + textUpperCase = lastTextUpperCase; + } else if (word.toString().equals(OCommandExecutorSQLAbstract.KEYWORD_LIMIT) || word.toString().equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || word.toString().equals(OCommandExecutorSQLSelect.KEYWORD_SKIP)) @@ -115,7 +106,7 @@ public boolean evaluate(final ORecord iRecord, final OCommandContext iContext @SuppressWarnings(""unchecked"") private boolean extractTargets() { - jumpWhiteSpaces(); + currentPos = OStringParser.jumpWhiteSpaces(text, currentPos); if (currentPos == -1) throw new OQueryParsingException(""No query target found"", text, 0); @@ -210,7 +201,7 @@ private boolean extractTargets() { if (targetClasses == null) targetClasses = new HashMap(); - OClass cls = database.getMetadata().getSchema().getClass(subjectName); + final OClass cls = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getSchema().getClass(subjectName); if (cls == null) throw new OCommandExecutionException(""Class '"" + subjectName + ""' was not found in current database""); @@ -222,213 +213,6 @@ private boolean extractTargets() { return currentPos > -1; } - private Object extractConditions(final OSQLFilterCondition iParentCondition) { - final int oldPosition = currentPos; - final String[] words = nextValue(true); - - if (words != null && words.length > 0 && (words[0].equalsIgnoreCase(""SELECT"") || words[0].equalsIgnoreCase(""TRAVERSE""))) { - // SUB QUERY - final StringBuilder embedded = new StringBuilder(); - OStringSerializerHelper.getEmbedded(text, oldPosition - 1, -1, embedded); - currentPos += embedded.length() + 1; - return new OSQLSynchQuery(embedded.toString()); - } - - currentPos = oldPosition; - final OSQLFilterCondition currentCondition = extractCondition(); - - // CHECK IF THERE IS ANOTHER CONDITION ON RIGHT - if (!jumpWhiteSpaces()) - // END OF TEXT - return currentCondition; - - if (currentPos > -1 && text.charAt(currentPos) == ')') - return currentCondition; - - final OQueryOperator nextOperator = extractConditionOperator(); - if (nextOperator == null) - return currentCondition; - - if (nextOperator.precedence > currentCondition.getOperator().precedence) { - // SWAP ITEMS - final OSQLFilterCondition subCondition = new OSQLFilterCondition(currentCondition.right, nextOperator); - currentCondition.right = subCondition; - subCondition.right = extractConditions(subCondition); - return currentCondition; - } else { - final OSQLFilterCondition parentCondition = new OSQLFilterCondition(currentCondition, nextOperator); - parentCondition.right = extractConditions(parentCondition); - return parentCondition; - } - } - - protected OSQLFilterCondition extractCondition() { - if (!jumpWhiteSpaces()) - // END OF TEXT - return null; - - // EXTRACT ITEMS - Object left = extractConditionItem(true, 1); - - if (checkForEnd(left.toString())) - return null; - - final OQueryOperator oper; - final Object right; - - if (left instanceof OQueryOperator && ((OQueryOperator) left).isUnary()) { - oper = (OQueryOperator) left; - left = extractConditionItem(false, 1); - right = null; - } else { - oper = extractConditionOperator(); - right = oper != null ? extractConditionItem(false, oper.expectedRightWords) : null; - } - - // CREATE THE CONDITION OBJECT - return new OSQLFilterCondition(left, oper, right); - } - - protected boolean checkForEnd(final String iWord) { - if (iWord != null - && (iWord.equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || iWord.equals(OCommandExecutorSQLSelect.KEYWORD_LIMIT) || iWord - .equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))) { - currentPos -= iWord.length(); - return true; - } - return false; - } - - private OQueryOperator extractConditionOperator() { - if (!jumpWhiteSpaces()) - // END OF PARSING: JUST RETURN - return null; - - if (text.charAt(currentPos) == ')') - // FOUND ')': JUST RETURN - return null; - - String word; - word = nextWord(true, "" 0123456789'\""""); - - if (checkForEnd(word)) - return null; - - for (OQueryOperator op : OSQLEngine.getInstance().getRecordOperators()) { - if (word.startsWith(op.keyword)) { - final List params = new ArrayList(); - // CHECK FOR PARAMETERS - if (word.length() > op.keyword.length() && word.charAt(op.keyword.length()) == OStringSerializerHelper.EMBEDDED_BEGIN) { - int paramBeginPos = currentPos - (word.length() - op.keyword.length()); - currentPos = OStringSerializerHelper.getParameters(text, paramBeginPos, -1, params); - } else if (!word.equals(op.keyword)) - throw new OQueryParsingException(""Malformed usage of operator '"" + op.toString() + ""'. Parsed operator is: "" + word); - - try { - return op.configure(params); - } catch (Exception e) { - throw new OQueryParsingException(""Syntax error using the operator '"" + op.toString() + ""'. Syntax is: "" + op.getSyntax()); - } - } - } - - throw new OQueryParsingException(""Unknown operator "" + word, text, currentPos); - } - - private Object extractConditionItem(final boolean iAllowOperator, final int iExpectedWords) { - final Object[] result = new Object[iExpectedWords]; - - for (int i = 0; i < iExpectedWords; ++i) { - final String[] words = nextValue(true); - if (words == null) - break; - - if (words[0].length() > 0 && words[0].charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) { - braces++; - - // SUB-CONDITION - currentPos = currentPos - words[0].length() + 1; - - final Object subCondition = extractConditions(null); - - if (!jumpWhiteSpaces() || text.charAt(currentPos) == ')') - braces--; - - if (currentPos > -1) - currentPos++; - - result[i] = subCondition; - } else if (words[0].charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) { - // COLLECTION OF ELEMENTS - currentPos = currentPos - words[0].length(); - - final List stringItems = new ArrayList(); - currentPos = OStringSerializerHelper.getCollection(text, currentPos, stringItems); - - if (stringItems.get(0).charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) { - - final List> coll = new ArrayList>(); - for (String stringItem : stringItems) { - final List stringSubItems = new ArrayList(); - OStringSerializerHelper.getCollection(stringItem, 0, stringSubItems); - - coll.add(convertCollectionItems(stringSubItems)); - } - - result[i] = coll; - - } else { - result[i] = convertCollectionItems(stringItems); - } - - currentPos++; - - } else if (words[0].startsWith(OSQLFilterItemFieldAll.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { - - result[i] = new OSQLFilterItemFieldAll(this, words[1]); - - } else if (words[0].startsWith(OSQLFilterItemFieldAny.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { - - result[i] = new OSQLFilterItemFieldAny(this, words[1]); - - } else { - - if (words[0].equals(""NOT"")) { - if (iAllowOperator) - return new OQueryOperatorNot(); - else { - // GET THE NEXT VALUE - final String[] nextWord = nextValue(true); - if (nextWord != null && nextWord.length == 2) { - words[1] = words[1] + "" "" + nextWord[1]; - - if (words[1].endsWith("")"")) - words[1] = words[1].substring(0, words[1].length() - 1); - } - } - } - - if (words[1].endsWith("")"")) { - final int openParenthesis = words[1].indexOf('('); - if (openParenthesis == -1) - words[1] = words[1].substring(0, words[1].length() - 1); - } - - result[i] = OSQLHelper.parseValue(this, this, words[1], context); - } - } - - return iExpectedWords == 1 ? result[0] : result; - } - - private List convertCollectionItems(List stringItems) { - List coll = new ArrayList(); - for (String s : stringItems) { - coll.add(OSQLHelper.parseValue(this, this, s, context)); - } - return coll; - } - public Map getTargetClusters() { return targetClusters; } @@ -449,85 +233,6 @@ public OSQLFilterCondition getRootCondition() { return rootCondition; } - private String[] nextValue(final boolean iAdvanceWhenNotFound) { - if (!jumpWhiteSpaces()) - return null; - - int begin = currentPos; - char c; - char stringBeginCharacter = ' '; - int openBraces = 0; - int openBraket = 0; - boolean escaped = false; - boolean escapingOn = false; - - for (; currentPos < text.length(); ++currentPos) { - c = text.charAt(currentPos); - - if (stringBeginCharacter == ' ' && (c == '""' || c == '\'')) { - // QUOTED STRING: GET UNTIL THE END OF QUOTING - stringBeginCharacter = c; - } else if (stringBeginCharacter != ' ') { - // INSIDE TEXT - if (c == '\\') { - escapingOn = true; - escaped = true; - } else { - if (c == stringBeginCharacter && !escapingOn) { - stringBeginCharacter = ' '; - - if (openBraket == 0 && openBraces == 0) { - if (iAdvanceWhenNotFound) - currentPos++; - break; - } - } - - if (escapingOn) - escapingOn = false; - } - } else if (c == '#' && currentPos == begin) { - // BEGIN OF RID - } else if (c == '(') { - openBraces++; - } else if (c == ')' && openBraces > 0) { - openBraces--; - } else if (c == OStringSerializerHelper.COLLECTION_BEGIN) { - openBraket++; - } else if (c == OStringSerializerHelper.COLLECTION_END) { - openBraket--; - if (openBraket == 0 && openBraces == 0) { - // currentPos++; - // break; - } - } else if (c == ' ' && openBraces == 0) { - break; - } else if (!Character.isLetter(c) && !Character.isDigit(c) && c != '.' && c != '$' && c != ':' && c != '-' && c != '_' - && c != '+' && c != '@' && openBraces == 0 && openBraket == 0) { - if (iAdvanceWhenNotFound) - currentPos++; - break; - } - } - - if (escaped) - return new String[] { OStringSerializerHelper.decode(textUpperCase.substring(begin, currentPos)), - OStringSerializerHelper.decode(text.substring(begin, currentPos)) }; - else - return new String[] { textUpperCase.substring(begin, currentPos), text.substring(begin, currentPos) }; - } - - private String nextWord(final boolean iForceUpperCase, final String iSeparators) { - StringBuilder word = new StringBuilder(); - currentPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, iForceUpperCase, iSeparators); - return word.toString(); - } - - private boolean jumpWhiteSpaces() { - currentPos = OStringParser.jumpWhiteSpaces(text, currentPos); - return currentPos > -1; - } - @Override public String toString() { if (rootCondition != null) @@ -535,52 +240,4 @@ public String toString() { return ""Unparsed: "" + text; } - /** - * Binds parameters. - * - * @param iArgs - */ - public void bindParameters(final Map iArgs) { - if (parameterItems == null || iArgs == null || iArgs.size() == 0) - return; - - for (Entry entry : iArgs.entrySet()) { - if (entry.getKey() instanceof Integer) - parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue())); - else { - String paramName = entry.getKey().toString(); - for (OSQLFilterItemParameter value : parameterItems) { - if (value.getName().equalsIgnoreCase(paramName)) { - value.setValue(entry.getValue()); - break; - } - } - } - } - } - - public OSQLFilterItemParameter addParameter(final String iName) { - final String name; - if (iName.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) { - name = iName.substring(1); - - // CHECK THE PARAMETER NAME IS CORRECT - if (!OStringSerializerHelper.isAlphanumeric(name)) { - throw new OQueryParsingException(""Parameter name '"" + name + ""' is invalid, only alphanumeric characters are allowed""); - } - } else - name = iName; - - final OSQLFilterItemParameter param = new OSQLFilterItemParameter(name); - - if (parameterItems == null) - parameterItems = new ArrayList(); - - parameterItems.add(param); - return param; - } - - public void setRootCondition(final OSQLFilterCondition iCondition) { - rootCondition = iCondition; - } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java index 46262c81b26..2c8d701397e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java @@ -47,271 +47,271 @@ * */ public class OSQLFilterCondition { - private static final String NULL_VALUE = ""null""; - protected Object left; - protected OQueryOperator operator; - protected Object right; - - public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator) { - this.left = iLeft; - this.operator = iOperator; - } - - public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator, final Object iRight) { - this.left = iLeft; - this.operator = iOperator; - this.right = iRight; - } - - public Object evaluate(final OIdentifiable o, final OCommandContext iContext) { - // EXECUTE SUB QUERIES ONCE - if (left instanceof OSQLQuery) - left = ((OSQLQuery) left).setContext(iContext).execute(); - - if (right instanceof OSQLQuery) - right = ((OSQLQuery) right).setContext(iContext).execute(); - - Object l = evaluate(o, left, iContext); - Object r = evaluate(o, right, iContext); - - final Object[] convertedValues = checkForConversion(o, l, r); - if (convertedValues != null) { - l = convertedValues[0]; - r = convertedValues[1]; - } - - if (operator == null) { - if (l == null) - // THE LEFT RETURNED NULL - return Boolean.FALSE; - - // UNITARY OPERATOR: JUST RETURN LEFT RESULT - return l; - } - - return operator.evaluateRecord(o, this, l, r, iContext); - } - - public ORID getBeginRidRange() { - if (operator == null) - if (left instanceof OSQLFilterCondition) - return ((OSQLFilterCondition) left).getBeginRidRange(); - else - return null; - - return operator.getBeginRidRange(left, right); - } - - public ORID getEndRidRange() { - if (operator == null) - if (left instanceof OSQLFilterCondition) - return ((OSQLFilterCondition) left).getEndRidRange(); - else - return null; - - return operator.getEndRidRange(left, right); - } - - private Object[] checkForConversion(final OIdentifiable o, final Object l, final Object r) { - Object[] result = null; - - // DEFINED OPERATOR - if ((r instanceof String && r.equals(OSQLHelper.DEFINED)) || (l instanceof String && l.equals(OSQLHelper.DEFINED))) { - result = new Object[] { ((OSQLFilterItemAbstract) this.left).getRoot(), r }; - } - - // NOT_NULL OPERATOR - else if ((r instanceof String && r.equals(OSQLHelper.NOT_NULL)) || (l instanceof String && l.equals(OSQLHelper.NOT_NULL))) { - result = null; - } - - else if (l != null && r != null && !l.getClass().isAssignableFrom(r.getClass()) && !r.getClass().isAssignableFrom(l.getClass())) - // INTEGERS - if (r instanceof Integer && !(l instanceof Number)) { - if (l instanceof String && ((String) l).indexOf('.') > -1) - result = new Object[] { new Float((String) l).intValue(), r }; - else if (l instanceof Date) - result = new Object[] { ((Date) l).getTime(), r }; - else if (!(l instanceof OQueryRuntimeValueMulti) && !(l instanceof Collection) && !l.getClass().isArray() - && !(l instanceof Map)) - result = new Object[] { getInteger(l), r }; - } else if (l instanceof Integer && !(r instanceof Number)) { - if (r instanceof String && ((String) r).indexOf('.') > -1) - result = new Object[] { l, new Float((String) r).intValue() }; - else if (r instanceof Date) - result = new Object[] { l, ((Date) r).getTime() }; - else if (!(r instanceof OQueryRuntimeValueMulti) && !(r instanceof Collection) && !r.getClass().isArray() - && !(r instanceof Map)) - result = new Object[] { l, getInteger(r) }; - } - - // FLOATS - else if (r instanceof Float && !(l instanceof Float)) - result = new Object[] { getFloat(l), r }; - else if (l instanceof Float && !(r instanceof Float)) - result = new Object[] { l, getFloat(r) }; - - // DATES - else if (r instanceof Date && !(l instanceof Collection || l instanceof Date)) { - result = new Object[] { getDate(l), r }; - } else if (l instanceof Date && !(r instanceof Collection || r instanceof Date)) { - result = new Object[] { l, getDate(r) }; - } - - // RIDS - else if (r instanceof ORID && l instanceof String && !l.equals(OSQLHelper.NOT_NULL)) { - result = new Object[] { new ORecordId((String) l), r }; - } else if (l instanceof ORID && r instanceof String && !r.equals(OSQLHelper.NOT_NULL)) { - result = new Object[] { l, new ORecordId((String) r) }; - } - - return result; - } - - protected Integer getInteger(Object iValue) { - if (iValue == null) - return null; - - final String stringValue = iValue.toString(); - - if (NULL_VALUE.equals(stringValue)) - return null; - if (OSQLHelper.DEFINED.equals(stringValue)) - return null; - - if (OStringSerializerHelper.contains(stringValue, '.') || OStringSerializerHelper.contains(stringValue, ',')) - return (int) Float.parseFloat(stringValue); - else - return stringValue.length() > 0 ? new Integer(stringValue) : new Integer(0); - } - - protected Float getFloat(final Object iValue) { - if (iValue == null) - return null; - - final String stringValue = iValue.toString(); - - if (NULL_VALUE.equals(stringValue)) - return null; - - return stringValue.length() > 0 ? new Float(stringValue) : new Float(0); - } - - protected Date getDate(final Object iValue) { - if (iValue == null) - return null; - - if (iValue instanceof Long) - return new Date(((Long) iValue).longValue()); - - String stringValue = iValue.toString(); - - if (NULL_VALUE.equals(stringValue)) - return null; - - if (stringValue.length() <= 0) - return null; - - if (Pattern.matches(""^\\d+$"", stringValue)) { - return new Date(Long.valueOf(stringValue).longValue()); - } - - final OStorageConfiguration config = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration(); - - SimpleDateFormat formatter = config.getDateFormatInstance(); - - if (stringValue.length() > config.dateFormat.length()) { - // ASSUMES YOU'RE USING THE DATE-TIME FORMATTE - formatter = config.getDateTimeFormatInstance(); - } - - try { - return formatter.parse(stringValue); - } catch (ParseException pe) { - throw new OQueryParsingException(""Error on conversion of date '"" + stringValue + ""' using the format: "" - + formatter.toPattern()); - } - } - - protected Object evaluate(OIdentifiable o, final Object iValue, final OCommandContext iContext) { - if (o.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) { - try { - o = o.getRecord().load(); - } catch (ORecordNotFoundException e) { - return null; - } - } - - if (iValue instanceof OSQLFilterItem) - return ((OSQLFilterItem) iValue).getValue(o, iContext); - - if (iValue instanceof OSQLFilterCondition) - // NESTED CONDITION: EVALUATE IT RECURSIVELY - return ((OSQLFilterCondition) iValue).evaluate(o, iContext); - - if (iValue instanceof OSQLFunctionRuntime) { - // STATELESS FUNCTION: EXECUTE IT - final OSQLFunctionRuntime f = (OSQLFunctionRuntime) iValue; - return f.execute(o, null); - } - - final Iterable multiValue = OMultiValue.getMultiValueIterable(iValue); - - if (multiValue != null) { - // MULTI VALUE: RETURN A COPY - final ArrayList result = new ArrayList(OMultiValue.getSize(iValue)); - - for (final Object value : multiValue) { - if (value instanceof OSQLFilterItem) - result.add(((OSQLFilterItem) value).getValue(o, null)); - else - result.add(value); - } - return result; - } - - // SIMPLE VALUE: JUST RETURN IT - return iValue; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - - buffer.append('('); - buffer.append(left); - if (operator != null) { - buffer.append(' '); - buffer.append(operator); - buffer.append(' '); - if (right instanceof String) - buffer.append('\''); - buffer.append(right); - if (right instanceof String) - buffer.append('\''); - buffer.append(')'); - } - - return buffer.toString(); - } - - public Object getLeft() { - return left; - } - - public Object getRight() { - return right; - } - - public OQueryOperator getOperator() { - return operator; - } - - public void setLeft(final Object iValue) { - left = iValue; - } - - public void setRight(final Object iValue) { - right = iValue; - } + private static final String NULL_VALUE = ""null""; + protected Object left; + protected OQueryOperator operator; + protected Object right; + + public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator) { + this.left = iLeft; + this.operator = iOperator; + } + + public OSQLFilterCondition(final Object iLeft, final OQueryOperator iOperator, final Object iRight) { + this.left = iLeft; + this.operator = iOperator; + this.right = iRight; + } + + public Object evaluate(final OIdentifiable o, final OCommandContext iContext) { + // EXECUTE SUB QUERIES ONCE + if (left instanceof OSQLQuery) + left = ((OSQLQuery) left).setContext(iContext).execute(); + + if (right instanceof OSQLQuery) + right = ((OSQLQuery) right).setContext(iContext).execute(); + + Object l = evaluate(o, left, iContext); + Object r = evaluate(o, right, iContext); + + final Object[] convertedValues = checkForConversion(o, l, r); + if (convertedValues != null) { + l = convertedValues[0]; + r = convertedValues[1]; + } + + if (operator == null) { + if (l == null) + // THE LEFT RETURNED NULL + return Boolean.FALSE; + + // UNITARY OPERATOR: JUST RETURN LEFT RESULT + return l; + } + + return operator.evaluateRecord(o, this, l, r, iContext); + } + + public ORID getBeginRidRange() { + if (operator == null) + if (left instanceof OSQLFilterCondition) + return ((OSQLFilterCondition) left).getBeginRidRange(); + else + return null; + + return operator.getBeginRidRange(left, right); + } + + public ORID getEndRidRange() { + if (operator == null) + if (left instanceof OSQLFilterCondition) + return ((OSQLFilterCondition) left).getEndRidRange(); + else + return null; + + return operator.getEndRidRange(left, right); + } + + private Object[] checkForConversion(final OIdentifiable o, final Object l, final Object r) { + Object[] result = null; + + // DEFINED OPERATOR + if ((r instanceof String && r.equals(OSQLHelper.DEFINED)) || (l instanceof String && l.equals(OSQLHelper.DEFINED))) { + result = new Object[] { ((OSQLFilterItemAbstract) this.left).getRoot(), r }; + } + + // NOT_NULL OPERATOR + else if ((r instanceof String && r.equals(OSQLHelper.NOT_NULL)) || (l instanceof String && l.equals(OSQLHelper.NOT_NULL))) { + result = null; + } + + else if (l != null && r != null && !l.getClass().isAssignableFrom(r.getClass()) && !r.getClass().isAssignableFrom(l.getClass())) + // INTEGERS + if (r instanceof Integer && !(l instanceof Number)) { + if (l instanceof String && ((String) l).indexOf('.') > -1) + result = new Object[] { new Float((String) l).intValue(), r }; + else if (l instanceof Date) + result = new Object[] { ((Date) l).getTime(), r }; + else if (!(l instanceof OQueryRuntimeValueMulti) && !(l instanceof Collection) && !l.getClass().isArray() + && !(l instanceof Map)) + result = new Object[] { getInteger(l), r }; + } else if (l instanceof Integer && !(r instanceof Number)) { + if (r instanceof String && ((String) r).indexOf('.') > -1) + result = new Object[] { l, new Float((String) r).intValue() }; + else if (r instanceof Date) + result = new Object[] { l, ((Date) r).getTime() }; + else if (!(r instanceof OQueryRuntimeValueMulti) && !(r instanceof Collection) && !r.getClass().isArray() + && !(r instanceof Map)) + result = new Object[] { l, getInteger(r) }; + } + + // FLOATS + else if (r instanceof Float && !(l instanceof Float)) + result = new Object[] { getFloat(l), r }; + else if (l instanceof Float && !(r instanceof Float)) + result = new Object[] { l, getFloat(r) }; + + // DATES + else if (r instanceof Date && !(l instanceof Collection || l instanceof Date)) { + result = new Object[] { getDate(l), r }; + } else if (l instanceof Date && !(r instanceof Collection || r instanceof Date)) { + result = new Object[] { l, getDate(r) }; + } + + // RIDS + else if (r instanceof ORID && l instanceof String && !l.equals(OSQLHelper.NOT_NULL)) { + result = new Object[] { new ORecordId((String) l), r }; + } else if (l instanceof ORID && r instanceof String && !r.equals(OSQLHelper.NOT_NULL)) { + result = new Object[] { l, new ORecordId((String) r) }; + } + + return result; + } + + protected Integer getInteger(Object iValue) { + if (iValue == null) + return null; + + final String stringValue = iValue.toString(); + + if (NULL_VALUE.equals(stringValue)) + return null; + if (OSQLHelper.DEFINED.equals(stringValue)) + return null; + + if (OStringSerializerHelper.contains(stringValue, '.') || OStringSerializerHelper.contains(stringValue, ',')) + return (int) Float.parseFloat(stringValue); + else + return stringValue.length() > 0 ? new Integer(stringValue) : new Integer(0); + } + + protected Float getFloat(final Object iValue) { + if (iValue == null) + return null; + + final String stringValue = iValue.toString(); + + if (NULL_VALUE.equals(stringValue)) + return null; + + return stringValue.length() > 0 ? new Float(stringValue) : new Float(0); + } + + protected Date getDate(final Object iValue) { + if (iValue == null) + return null; + + if (iValue instanceof Long) + return new Date(((Long) iValue).longValue()); + + String stringValue = iValue.toString(); + + if (NULL_VALUE.equals(stringValue)) + return null; + + if (stringValue.length() <= 0) + return null; + + if (Pattern.matches(""^\\d+$"", stringValue)) { + return new Date(Long.valueOf(stringValue).longValue()); + } + + final OStorageConfiguration config = ODatabaseRecordThreadLocal.INSTANCE.get().getStorage().getConfiguration(); + + SimpleDateFormat formatter = config.getDateFormatInstance(); + + if (stringValue.length() > config.dateFormat.length()) { + // ASSUMES YOU'RE USING THE DATE-TIME FORMATTE + formatter = config.getDateTimeFormatInstance(); + } + + try { + return formatter.parse(stringValue); + } catch (ParseException pe) { + throw new OQueryParsingException(""Error on conversion of date '"" + stringValue + ""' using the format: "" + + formatter.toPattern()); + } + } + + protected Object evaluate(OIdentifiable o, final Object iValue, final OCommandContext iContext) { + if (o.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) { + try { + o = o.getRecord().load(); + } catch (ORecordNotFoundException e) { + return null; + } + } + + if (iValue instanceof OSQLFilterItem) + return ((OSQLFilterItem) iValue).getValue(o, iContext); + + if (iValue instanceof OSQLFilterCondition) + // NESTED CONDITION: EVALUATE IT RECURSIVELY + return ((OSQLFilterCondition) iValue).evaluate(o, iContext); + + if (iValue instanceof OSQLFunctionRuntime) { + // STATELESS FUNCTION: EXECUTE IT + final OSQLFunctionRuntime f = (OSQLFunctionRuntime) iValue; + return f.execute(o, null); + } + + final Iterable multiValue = OMultiValue.getMultiValueIterable(iValue); + + if (multiValue != null) { + // MULTI VALUE: RETURN A COPY + final ArrayList result = new ArrayList(OMultiValue.getSize(iValue)); + + for (final Object value : multiValue) { + if (value instanceof OSQLFilterItem) + result.add(((OSQLFilterItem) value).getValue(o, null)); + else + result.add(value); + } + return result; + } + + // SIMPLE VALUE: JUST RETURN IT + return iValue; + } + + @Override + public String toString() { + StringBuilder buffer = new StringBuilder(); + + buffer.append('('); + buffer.append(left); + if (operator != null) { + buffer.append(' '); + buffer.append(operator); + buffer.append(' '); + if (right instanceof String) + buffer.append('\''); + buffer.append(right); + if (right instanceof String) + buffer.append('\''); + buffer.append(')'); + } + + return buffer.toString(); + } + + public Object getLeft() { + return left; + } + + public Object getRight() { + return right; + } + + public OQueryOperator getOperator() { + return operator; + } + + public void setLeft(final Object iValue) { + left = iValue; + } + + public void setRight(final Object iValue) { + right = iValue; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java index 31de0848b1a..67bff01bb6d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAll.java @@ -28,7 +28,7 @@ public class OSQLFilterItemFieldAll extends OSQLFilterItemFieldMultiAbstract { public static final String NAME = ""ALL""; public static final String FULL_NAME = ""ALL()""; - public OSQLFilterItemFieldAll(final OSQLFilter iQueryCompiled, final String iName) { + public OSQLFilterItemFieldAll(final OSQLPredicate iQueryCompiled, final String iName) { super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName)); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java index fad3f6aac1c..145347f9e86 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldAny.java @@ -25,19 +25,19 @@ * */ public class OSQLFilterItemFieldAny extends OSQLFilterItemFieldMultiAbstract { - public static final String NAME = ""ANY""; - public static final String FULL_NAME = ""ANY()""; + public static final String NAME = ""ANY""; + public static final String FULL_NAME = ""ANY()""; - public OSQLFilterItemFieldAny(final OSQLFilter iQueryCompiled, final String iName) { - super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName)); - } + public OSQLFilterItemFieldAny(final OSQLPredicate iQueryCompiled, final String iName) { + super(iQueryCompiled, iName, OStringSerializerHelper.getParameters(iName)); + } - @Override - public String getRoot() { - return FULL_NAME; - } + @Override + public String getRoot() { + return FULL_NAME; + } - @Override - protected void setRoot(final OCommandToParse iQueryToParse, final String iRoot) { - } + @Override + protected void setRoot(final OCommandToParse iQueryToParse, final String iRoot) { + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java index 6181f1a7180..9002a582da5 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemFieldMultiAbstract.java @@ -30,25 +30,25 @@ * */ public abstract class OSQLFilterItemFieldMultiAbstract extends OSQLFilterItemAbstract { - private List names; + private List names; - public OSQLFilterItemFieldMultiAbstract(final OSQLFilter iQueryCompiled, final String iName, final List iNames) { - super(iQueryCompiled, iName); - names = iNames; - } + public OSQLFilterItemFieldMultiAbstract(final OSQLPredicate iQueryCompiled, final String iName, final List iNames) { + super(iQueryCompiled, iName); + names = iNames; + } - public Object getValue(final OIdentifiable iRecord, OCommandContext iContetx) { - if (names.size() == 1) - return transformValue(iRecord, ODocumentHelper.getIdentifiableValue(iRecord, names.get(0))); + public Object getValue(final OIdentifiable iRecord, OCommandContext iContetx) { + if (names.size() == 1) + return transformValue(iRecord, ODocumentHelper.getIdentifiableValue(iRecord, names.get(0))); - final Object[] values = ((ODocument) iRecord).fieldValues(); + final Object[] values = ((ODocument) iRecord).fieldValues(); - if (hasChainOperators()) { - // TRANSFORM ALL THE VALUES - for (int i = 0; i < values.length; ++i) - values[i] = transformValue(iRecord, values[i]); - } + if (hasChainOperators()) { + // TRANSFORM ALL THE VALUES + for (int i = 0; i < values.length; ++i) + values[i] = transformValue(iRecord, values[i]); + } - return new OQueryRuntimeValueMulti(this, values); - } + return new OQueryRuntimeValueMulti(this, values); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java new file mode 100644 index 00000000000..54eca8c0392 --- /dev/null +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLPredicate.java @@ -0,0 +1,435 @@ +/* + * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.orientechnologies.orient.core.sql.filter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.orientechnologies.common.parser.OStringParser; +import com.orientechnologies.orient.core.command.OCommandContext; +import com.orientechnologies.orient.core.command.OCommandPredicate; +import com.orientechnologies.orient.core.command.OCommandToParse; +import com.orientechnologies.orient.core.exception.OQueryParsingException; +import com.orientechnologies.orient.core.metadata.schema.OProperty; +import com.orientechnologies.orient.core.record.ORecord; +import com.orientechnologies.orient.core.record.ORecordSchemaAware; +import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; +import com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect; +import com.orientechnologies.orient.core.sql.OSQLEngine; +import com.orientechnologies.orient.core.sql.OSQLHelper; +import com.orientechnologies.orient.core.sql.operator.OQueryOperator; +import com.orientechnologies.orient.core.sql.operator.OQueryOperatorNot; +import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; + +/** + * Parses text in SQL format and build a tree of conditions. + * + * @author Luca Garulli + * + */ +public class OSQLPredicate extends OCommandToParse implements OCommandPredicate { + protected Set properties = new HashSet(); + protected OSQLFilterCondition rootCondition; + protected List recordTransformed; + protected List parameterItems; + protected int braces; + protected OCommandContext context; + + public OSQLPredicate() { + } + + public OSQLPredicate(final String iText) { + text(iText); + } + + public OSQLPredicate text(final String iText) { + try { + text = iText; + textUpperCase = text.toUpperCase(Locale.ENGLISH); + currentPos = 0; + jumpWhiteSpaces(); + + rootCondition = (OSQLFilterCondition) extractConditions(null); + } catch (OQueryParsingException e) { + if (e.getText() == null) + // QUERY EXCEPTION BUT WITHOUT TEXT: NEST IT + throw new OQueryParsingException(""Error on parsing query"", text, currentPos, e); + + throw e; + } catch (Throwable t) { + throw new OQueryParsingException(""Error on parsing query"", text, currentPos, t); + } + return this; + } + + public boolean evaluate(final ORecord iRecord, final OCommandContext iContext) { + if (rootCondition == null) + return true; + + return (Boolean) rootCondition.evaluate((ORecordSchemaAware) iRecord, iContext); + } + + private Object extractConditions(final OSQLFilterCondition iParentCondition) { + final int oldPosition = currentPos; + final String[] words = nextValue(true); + + if (words != null && words.length > 0 && (words[0].equalsIgnoreCase(""SELECT"") || words[0].equalsIgnoreCase(""TRAVERSE""))) { + // SUB QUERY + final StringBuilder embedded = new StringBuilder(); + OStringSerializerHelper.getEmbedded(text, oldPosition - 1, -1, embedded); + currentPos += embedded.length() + 1; + return new OSQLSynchQuery(embedded.toString()); + } + + currentPos = oldPosition; + final OSQLFilterCondition currentCondition = extractCondition(); + + // CHECK IF THERE IS ANOTHER CONDITION ON RIGHT + if (!jumpWhiteSpaces()) + // END OF TEXT + return currentCondition; + + if (currentPos > -1 && text.charAt(currentPos) == ')') + return currentCondition; + + final OQueryOperator nextOperator = extractConditionOperator(); + if (nextOperator == null) + return currentCondition; + + if (nextOperator.precedence > currentCondition.getOperator().precedence) { + // SWAP ITEMS + final OSQLFilterCondition subCondition = new OSQLFilterCondition(currentCondition.right, nextOperator); + currentCondition.right = subCondition; + subCondition.right = extractConditions(subCondition); + return currentCondition; + } else { + final OSQLFilterCondition parentCondition = new OSQLFilterCondition(currentCondition, nextOperator); + parentCondition.right = extractConditions(parentCondition); + return parentCondition; + } + } + + protected OSQLFilterCondition extractCondition() { + if (!jumpWhiteSpaces()) + // END OF TEXT + return null; + + // EXTRACT ITEMS + Object left = extractConditionItem(true, 1); + + if (checkForEnd(left.toString())) + return null; + + final OQueryOperator oper; + final Object right; + + if (left instanceof OQueryOperator && ((OQueryOperator) left).isUnary()) { + oper = (OQueryOperator) left; + left = extractConditionItem(false, 1); + right = null; + } else { + oper = extractConditionOperator(); + right = oper != null ? extractConditionItem(false, oper.expectedRightWords) : null; + } + + // CREATE THE CONDITION OBJECT + return new OSQLFilterCondition(left, oper, right); + } + + protected boolean checkForEnd(final String iWord) { + if (iWord != null + && (iWord.equals(OCommandExecutorSQLSelect.KEYWORD_ORDER) || iWord.equals(OCommandExecutorSQLSelect.KEYWORD_LIMIT) || iWord + .equals(OCommandExecutorSQLSelect.KEYWORD_SKIP))) { + currentPos -= iWord.length(); + return true; + } + return false; + } + + private OQueryOperator extractConditionOperator() { + if (!jumpWhiteSpaces()) + // END OF PARSING: JUST RETURN + return null; + + if (text.charAt(currentPos) == ')') + // FOUND ')': JUST RETURN + return null; + + String word; + word = nextWord(true, "" 0123456789'\""""); + + if (checkForEnd(word)) + return null; + + for (OQueryOperator op : OSQLEngine.getInstance().getRecordOperators()) { + if (word.startsWith(op.keyword)) { + final List params = new ArrayList(); + // CHECK FOR PARAMETERS + if (word.length() > op.keyword.length() && word.charAt(op.keyword.length()) == OStringSerializerHelper.EMBEDDED_BEGIN) { + int paramBeginPos = currentPos - (word.length() - op.keyword.length()); + currentPos = OStringSerializerHelper.getParameters(text, paramBeginPos, -1, params); + } else if (!word.equals(op.keyword)) + throw new OQueryParsingException(""Malformed usage of operator '"" + op.toString() + ""'. Parsed operator is: "" + word); + + try { + return op.configure(params); + } catch (Exception e) { + throw new OQueryParsingException(""Syntax error using the operator '"" + op.toString() + ""'. Syntax is: "" + op.getSyntax()); + } + } + } + + throw new OQueryParsingException(""Unknown operator "" + word, text, currentPos); + } + + private Object extractConditionItem(final boolean iAllowOperator, final int iExpectedWords) { + final Object[] result = new Object[iExpectedWords]; + + for (int i = 0; i < iExpectedWords; ++i) { + final String[] words = nextValue(true); + if (words == null) + break; + + if (words[0].length() > 0 && words[0].charAt(0) == OStringSerializerHelper.EMBEDDED_BEGIN) { + braces++; + + // SUB-CONDITION + currentPos = currentPos - words[0].length() + 1; + + final Object subCondition = extractConditions(null); + + if (!jumpWhiteSpaces() || text.charAt(currentPos) == ')') + braces--; + + if (currentPos > -1) + currentPos++; + + result[i] = subCondition; + } else if (words[0].charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) { + // COLLECTION OF ELEMENTS + currentPos = currentPos - words[0].length(); + + final List stringItems = new ArrayList(); + currentPos = OStringSerializerHelper.getCollection(text, currentPos, stringItems); + + if (stringItems.get(0).charAt(0) == OStringSerializerHelper.COLLECTION_BEGIN) { + + final List> coll = new ArrayList>(); + for (String stringItem : stringItems) { + final List stringSubItems = new ArrayList(); + OStringSerializerHelper.getCollection(stringItem, 0, stringSubItems); + + coll.add(convertCollectionItems(stringSubItems)); + } + + result[i] = coll; + + } else { + result[i] = convertCollectionItems(stringItems); + } + + currentPos++; + + } else if (words[0].startsWith(OSQLFilterItemFieldAll.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { + + result[i] = new OSQLFilterItemFieldAll(this, words[1]); + + } else if (words[0].startsWith(OSQLFilterItemFieldAny.NAME + OStringSerializerHelper.EMBEDDED_BEGIN)) { + + result[i] = new OSQLFilterItemFieldAny(this, words[1]); + + } else { + + if (words[0].equals(""NOT"")) { + if (iAllowOperator) + return new OQueryOperatorNot(); + else { + // GET THE NEXT VALUE + final String[] nextWord = nextValue(true); + if (nextWord != null && nextWord.length == 2) { + words[1] = words[1] + "" "" + nextWord[1]; + + if (words[1].endsWith("")"")) + words[1] = words[1].substring(0, words[1].length() - 1); + } + } + } + + if (words[1].endsWith("")"")) { + final int openParenthesis = words[1].indexOf('('); + if (openParenthesis == -1) + words[1] = words[1].substring(0, words[1].length() - 1); + } + + result[i] = OSQLHelper.parseValue(this, this, words[1], context); + } + } + + return iExpectedWords == 1 ? result[0] : result; + } + + private List convertCollectionItems(List stringItems) { + List coll = new ArrayList(); + for (String s : stringItems) { + coll.add(OSQLHelper.parseValue(this, this, s, context)); + } + return coll; + } + + public OSQLFilterCondition getRootCondition() { + return rootCondition; + } + + private String[] nextValue(final boolean iAdvanceWhenNotFound) { + if (!jumpWhiteSpaces()) + return null; + + int begin = currentPos; + char c; + char stringBeginCharacter = ' '; + int openBraces = 0; + int openBraket = 0; + boolean escaped = false; + boolean escapingOn = false; + + for (; currentPos < text.length(); ++currentPos) { + c = text.charAt(currentPos); + + if (stringBeginCharacter == ' ' && (c == '""' || c == '\'')) { + // QUOTED STRING: GET UNTIL THE END OF QUOTING + stringBeginCharacter = c; + } else if (stringBeginCharacter != ' ') { + // INSIDE TEXT + if (c == '\\') { + escapingOn = true; + escaped = true; + } else { + if (c == stringBeginCharacter && !escapingOn) { + stringBeginCharacter = ' '; + + if (openBraket == 0 && openBraces == 0) { + if (iAdvanceWhenNotFound) + currentPos++; + break; + } + } + + if (escapingOn) + escapingOn = false; + } + } else if (c == '#' && currentPos == begin) { + // BEGIN OF RID + } else if (c == '(') { + openBraces++; + } else if (c == ')' && openBraces > 0) { + openBraces--; + } else if (c == OStringSerializerHelper.COLLECTION_BEGIN) { + openBraket++; + } else if (c == OStringSerializerHelper.COLLECTION_END) { + openBraket--; + if (openBraket == 0 && openBraces == 0) { + // currentPos++; + // break; + } + } else if (c == ' ' && openBraces == 0) { + break; + } else if (!Character.isLetter(c) && !Character.isDigit(c) && c != '.' && c != '$' && c != ':' && c != '-' && c != '_' + && c != '+' && c != '@' && openBraces == 0 && openBraket == 0) { + if (iAdvanceWhenNotFound) + currentPos++; + break; + } + } + + if (escaped) + return new String[] { OStringSerializerHelper.decode(textUpperCase.substring(begin, currentPos)), + OStringSerializerHelper.decode(text.substring(begin, currentPos)) }; + else + return new String[] { textUpperCase.substring(begin, currentPos), text.substring(begin, currentPos) }; + } + + private String nextWord(final boolean iForceUpperCase, final String iSeparators) { + StringBuilder word = new StringBuilder(); + currentPos = OSQLHelper.nextWord(text, textUpperCase, currentPos, word, iForceUpperCase, iSeparators); + return word.toString(); + } + + private boolean jumpWhiteSpaces() { + currentPos = OStringParser.jumpWhiteSpaces(text, currentPos); + return currentPos > -1; + } + + @Override + public String toString() { + if (rootCondition != null) + return ""Parsed: "" + rootCondition.toString(); + return ""Unparsed: "" + text; + } + + /** + * Binds parameters. + * + * @param iArgs + */ + public void bindParameters(final Map iArgs) { + if (parameterItems == null || iArgs == null || iArgs.size() == 0) + return; + + for (Entry entry : iArgs.entrySet()) { + if (entry.getKey() instanceof Integer) + parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue())); + else { + String paramName = entry.getKey().toString(); + for (OSQLFilterItemParameter value : parameterItems) { + if (value.getName().equalsIgnoreCase(paramName)) { + value.setValue(entry.getValue()); + break; + } + } + } + } + } + + public OSQLFilterItemParameter addParameter(final String iName) { + final String name; + if (iName.charAt(0) == OStringSerializerHelper.PARAMETER_NAMED) { + name = iName.substring(1); + + // CHECK THE PARAMETER NAME IS CORRECT + if (!OStringSerializerHelper.isAlphanumeric(name)) { + throw new OQueryParsingException(""Parameter name '"" + name + ""' is invalid, only alphanumeric characters are allowed""); + } + } else + name = iName; + + final OSQLFilterItemParameter param = new OSQLFilterItemParameter(name); + + if (parameterItems == null) + parameterItems = new ArrayList(); + + parameterItems.add(param); + return param; + } + + public void setRootCondition(final OSQLFilterCondition iCondition) { + rootCondition = iCondition; + } +} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java index f26315aace1..bdd1bd0f66d 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TraverseTest.java @@ -24,9 +24,14 @@ import org.testng.annotations.Parameters; import org.testng.annotations.Test; +import com.orientechnologies.orient.core.command.OCommandContext; +import com.orientechnologies.orient.core.command.OCommandPredicate; +import com.orientechnologies.orient.core.command.traverse.OTraverse; import com.orientechnologies.orient.core.db.graph.OGraphDatabase; import com.orientechnologies.orient.core.db.record.OIdentifiable; +import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.sql.filter.OSQLPredicate; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; @Test @@ -89,18 +94,27 @@ public void deinit() { database.close(); } - public void traverseAllFromActorNoWhere() { + public void traverseSQLAllFromActorNoWhere() { List result1 = database.command(new OSQLSynchQuery(""traverse * from "" + tomCruise.getIdentity())) .execute(); Assert.assertEquals(result1.size(), totalElements); } - public void traverseOutFromOneActorNoWhere() { + public void traverseAPIAllFromActorNoWhere() { + List result1 = new OTraverse().fields(""*"").target(tomCruise.getIdentity()).execute(); + Assert.assertEquals(result1.size(), totalElements); + } + + public void traverseSQLOutFromOneActorNoWhere() { database.command(new OSQLSynchQuery(""traverse out from "" + tomCruise.getIdentity())).execute(); } + public void traverseAPIOutFromOneActorNoWhere() { + new OTraverse().field(""out"").target(tomCruise.getIdentity()).execute(); + } + @Test - public void traverseOutFromActor1Depth() { + public void traverseSQLOutFromActor1Depth() { List result1 = database.command( new OSQLSynchQuery(""traverse out from "" + tomCruise.getIdentity() + "" where $depth <= 1"")).execute(); @@ -111,14 +125,14 @@ public void traverseOutFromActor1Depth() { } @Test - public void traverseDept02() { + public void traverseSQLDept02() { List result1 = database.command(new OSQLSynchQuery(""traverse any() from Movie where $depth < 2"")) .execute(); } @Test - public void traverseMoviesOnly() { + public void traverseSQLMoviesOnly() { List result1 = database.command( new OSQLSynchQuery(""select from ( traverse any() from Movie ) where @class = 'Movie'"")).execute(); Assert.assertTrue(result1.size() > 0); @@ -128,7 +142,7 @@ public void traverseMoviesOnly() { } @Test - public void traversePerClassFields() { + public void traverseSQLPerClassFields() { List result1 = database.command( new OSQLSynchQuery(""select from ( traverse V.out, E.in from "" + tomCruise.getIdentity() + "") where @class = 'Movie'"")).execute(); @@ -139,7 +153,7 @@ public void traversePerClassFields() { } @Test - public void traverseMoviesOnlyDepth() { + public void traverseSQLMoviesOnlyDepth() { List result1 = database.command( new OSQLSynchQuery(""select from ( traverse * from "" + tomCruise.getIdentity() + "" where $depth <= 1 ) where @class = 'Movie'"")).execute(); @@ -170,7 +184,7 @@ public void traverseSelect() { } @Test - public void traverseSelectAndTraverseNested() { + public void traverseSQLSelectAndTraverseNested() { List result1 = database.command( new OSQLSynchQuery(""traverse * from ( select from ( traverse * from "" + tomCruise.getIdentity() + "" where $depth <= 2 ) where @class = 'Movie' )"")).execute(); @@ -178,7 +192,15 @@ public void traverseSelectAndTraverseNested() { } @Test - public void traverseIterating() { + public void traverseAPISelectAndTraverseNested() { + List result1 = database.command( + new OSQLSynchQuery(""traverse * from ( select from ( traverse * from "" + tomCruise.getIdentity() + + "" where $depth <= 2 ) where @class = 'Movie' )"")).execute(); + Assert.assertEquals(result1.size(), totalElements); + } + + @Test + public void traverseSQLIterating() { int cycles = 0; for (OIdentifiable id : new OSQLSynchQuery(""traverse * from Movie where $depth < 2"")) { cycles++; @@ -186,6 +208,29 @@ public void traverseIterating() { Assert.assertTrue(cycles > 0); } + @Test + public void traverseAPIIterating() { + int cycles = 0; + for (OIdentifiable id : new OTraverse().target(database.browseClass(""Movie"").iterator()).predicate(new OCommandPredicate() { + public boolean evaluate(ORecord iRecord, OCommandContext iContext) { + return ((Integer) iContext.getVariable(""depth"")) <= 2; + } + })) { + cycles++; + } + Assert.assertTrue(cycles > 0); + } + + @Test + public void traverseAPIandSQLIterating() { + int cycles = 0; + for (OIdentifiable id : new OTraverse().target(database.browseClass(""Movie"").iterator()).predicate( + new OSQLPredicate(""$depth <= 2""))) { + cycles++; + } + Assert.assertTrue(cycles > 0); + } + @Test public void traverseSelectIterable() { int cycles = 0;" 504b801ca0e7fd3944872d3214539feb2d614f06,hadoop,HDFS-73. DFSOutputStream does not close all the- sockets. Contributed by Uma Maheswara Rao G--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1157232 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hdfs/CHANGES.txt b/hdfs/CHANGES.txt index 5148ea243d7e0..02c8864284dd2 100644 --- a/hdfs/CHANGES.txt +++ b/hdfs/CHANGES.txt @@ -964,6 +964,9 @@ Trunk (unreleased changes) HDFS-2240. Fix a deadlock in LeaseRenewer by enforcing lock acquisition ordering. (szetszwo) + HDFS-73. DFSOutputStream does not close all the sockets. + (Uma Maheswara Rao G via eli) + BREAKDOWN OF HDFS-1073 SUBTASKS HDFS-1521. Persist transaction ID on disk between NN restarts. diff --git a/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java b/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java index d267bf8a8d4a3..03879338dd273 100644 --- a/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java +++ b/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java @@ -36,7 +36,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSOutputSummer; import org.apache.hadoop.fs.FileAlreadyExistsException; @@ -63,7 +62,6 @@ import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status; import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; -import org.apache.hadoop.hdfs.server.datanode.DataNode; import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException; import org.apache.hadoop.hdfs.server.namenode.SafeModeException; import org.apache.hadoop.io.EnumSetWritable; @@ -606,6 +604,7 @@ private void closeStream() { try { blockStream.close(); } catch (IOException e) { + setLastException(e); } finally { blockStream = null; } @@ -614,10 +613,20 @@ private void closeStream() { try { blockReplyStream.close(); } catch (IOException e) { + setLastException(e); } finally { blockReplyStream = null; } } + if (null != s) { + try { + s.close(); + } catch (IOException e) { + setLastException(e); + } finally { + s = null; + } + } } // @@ -1003,16 +1012,20 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, persistBlocks.set(true); boolean result = false; + DataOutputStream out = null; try { + assert null == s : ""Previous socket unclosed""; s = createSocketForPipeline(nodes[0], nodes.length, dfsClient); long writeTimeout = dfsClient.getDatanodeWriteTimeout(nodes.length); // // Xmit header info to datanode // - DataOutputStream out = new DataOutputStream(new BufferedOutputStream( + out = new DataOutputStream(new BufferedOutputStream( NetUtils.getOutputStream(s, writeTimeout), FSConstants.SMALL_BUFFER_SIZE)); + + assert null == blockReplyStream : ""Previous blockReplyStream unclosed""; blockReplyStream = new DataInputStream(NetUtils.getInputStream(s)); // send the request @@ -1038,7 +1051,7 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, + firstBadLink); } } - + assert null == blockStream : ""Previous blockStream unclosed""; blockStream = out; result = true; // success @@ -1059,12 +1072,15 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, } hasError = true; setLastException(ie); - blockReplyStream = null; result = false; // error } finally { if (!result) { IOUtils.closeSocket(s); s = null; + IOUtils.closeStream(out); + out = null; + IOUtils.closeStream(blockReplyStream); + blockReplyStream = null; } } return result;" 3c3d4b1658b3bd3c8aff620116f3a110bdc3d6d6,orientdb,Issue -1607 Fix blueprints tests and TX NPEs.--,c,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java b/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java index 709c22b0294..99f7f0b3b10 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/engine/OSBTreeIndexEngine.java @@ -341,7 +341,7 @@ public boolean addResult(OSBTreeBucket.SBTreeEntry entry) { Collection identifiables = transformer.transformFromValue(entry.value); for (OIdentifiable identifiable : identifiables) { if (identifiable.equals(value)) - keySetToRemove.add(value); + keySetToRemove.add(entry.key); } } return true; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java index c306ea4f81b..c15d49b0439 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocalAbstract.java @@ -96,7 +96,7 @@ protected void startStorageTx(OTransaction clientTx) throws IOException { } protected void rollbackStorageTx() throws IOException { - if (writeAheadLog == null) + if (writeAheadLog == null || transaction == null) return; writeAheadLog.log(new OAtomicUnitEndRecord(transaction.getOperationUnitId(), true));" ecbe69e87d908f4cc8bfec5f9a47244b8947fb0b,intellij-community,NPE fix--,c,https://github.com/JetBrains/intellij-community,"diff --git a/ui/impl/com/intellij/ide/ui/search/SearchUtil.java b/ui/impl/com/intellij/ide/ui/search/SearchUtil.java index 4b333642d9593..058e68931b919 100644 --- a/ui/impl/com/intellij/ide/ui/search/SearchUtil.java +++ b/ui/impl/com/intellij/ide/ui/search/SearchUtil.java @@ -14,7 +14,6 @@ import com.intellij.ui.TabbedPaneWrapper; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.border.Border; @@ -212,7 +211,8 @@ else if (rootComponent instanceof JRadioButton) { return highlight; } - public static boolean isComponentHighlighted(@NotNull String text, @NotNull String option, final boolean force, final SearchableConfigurable configurable){ + public static boolean isComponentHighlighted(String text, String option, final boolean force, final SearchableConfigurable configurable){ + if (text == null || option == null) return false; SearchableOptionsRegistrar searchableOptionsRegistrar = SearchableOptionsRegistrar.getInstance(); final Set options = searchableOptionsRegistrar.replaceSynonyms(searchableOptionsRegistrar.getProcessedWords(option), configurable); final Set tokens = searchableOptionsRegistrar.getProcessedWords(text);" 72d780f2cab2892259331c8d6f2d5b33d291d416,drools,"JBRULES-3200 Support for dynamic typing (aka- ""traits"")--",a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java b/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java index dbfb8b253b6..bfb18418e9f 100644 --- a/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java +++ b/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java @@ -102,6 +102,18 @@ public void setType( String name, String namespace ) { type = new QualifiedName( name, namespace ); } + public String getSuperTypeName() { + return superTypes == null ? null : superTypes.get(0).getName(); + } + + public String getSuperTypeNamespace() { + return superTypes == null ? null : superTypes.get(0).getNamespace(); + } + + public String getSupertTypeFullName() { + return superTypes == null ? null : superTypes.get(0).getFullName(); + } + /** * @return the fields" 12c81054044c429dd2356ac036b722c06e0f9e55,camel,Fixed test on other boxes--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@904741 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java b/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java index 20ebb8e293c12..2311db04e3574 100644 --- a/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java +++ b/camel-core/src/test/java/org/apache/camel/builder/NotifyBuilderTest.java @@ -324,15 +324,13 @@ public void testWhenExchangeReceivedWithDelay() throws Exception { long start = System.currentTimeMillis(); template.sendBody(""seda:cheese"", ""Hello Cheese""); long end = System.currentTimeMillis(); - assertTrue(""Should be faster than: "" + (end - start), (end - start) < 1500); - - assertEquals(false, notify.matches()); + assertTrue(""Should be faster than: "" + (end - start), (end - start) < 2000); // should be quick as its when received and NOT when done assertEquals(true, notify.matches(5, TimeUnit.SECONDS)); long end2 = System.currentTimeMillis(); - assertTrue(""Should be faster than: "" + (end2 - start), (end2 - start) < 1500); + assertTrue(""Should be faster than: "" + (end2 - start), (end2 - start) < 2000); } public void testWhenExchangeDoneWithDelay() throws Exception { @@ -343,7 +341,7 @@ public void testWhenExchangeDoneWithDelay() throws Exception { long start = System.currentTimeMillis(); template.sendBody(""seda:cheese"", ""Hello Cheese""); long end = System.currentTimeMillis(); - assertTrue(""Should be faster than: "" + (end - start), (end - start) < 1500); + assertTrue(""Should be faster than: "" + (end - start), (end - start) < 2000); assertEquals(false, notify.matches());" a1c7a707cac478b7288dfc34cd2fccecb68d0c35,hadoop,YARN-2502. Changed DistributedShell to support node- labels. Contributed by Wangda Tan (cherry picked from commit- f6b963fdfc517429149165e4bb6fb947be6e3c99)--,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index b1bd6eb104516..9c08db7de02f2 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -374,6 +374,9 @@ Release 2.6.0 - UNRELEASED sake of localization and log-aggregation for long-running services. (Jian He via vinodkv) + YARN-2502. Changed DistributedShell to support node labels. (Wangda Tan via + jianhe) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/Client.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/Client.java index 2067aca481031..0e9a4e4a495fa 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/Client.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/Client.java @@ -115,7 +115,7 @@ public class Client { private static final Log LOG = LogFactory.getLog(Client.class); - + // Configuration private Configuration conf; private YarnClient yarnClient; @@ -152,6 +152,7 @@ public class Client { private int containerVirtualCores = 1; // No. of containers in which the shell script needs to be executed private int numContainers = 1; + private String nodeLabelExpression = null; // log4j.properties file // if available, add to local resources and set into classpath @@ -280,7 +281,12 @@ public Client(Configuration conf) throws Exception { opts.addOption(""create"", false, ""Flag to indicate whether to create the "" + ""domain specified with -domain.""); opts.addOption(""help"", false, ""Print usage""); - + opts.addOption(""node_label_expression"", true, + ""Node label expression to determine the nodes"" + + "" where all the containers of this application"" + + "" will be allocated, \""\"" means containers"" + + "" can be allocated anywhere, if you don't specify the option,"" + + "" default node_label_expression of queue will be used.""); } /** @@ -391,6 +397,7 @@ public boolean init(String[] args) throws ParseException { containerMemory = Integer.parseInt(cliParser.getOptionValue(""container_memory"", ""10"")); containerVirtualCores = Integer.parseInt(cliParser.getOptionValue(""container_vcores"", ""1"")); numContainers = Integer.parseInt(cliParser.getOptionValue(""num_containers"", ""1"")); + if (containerMemory < 0 || containerVirtualCores < 0 || numContainers < 1) { throw new IllegalArgumentException(""Invalid no. of containers or container memory/vcores specified,"" @@ -399,6 +406,8 @@ public boolean init(String[] args) throws ParseException { + "", containerVirtualCores="" + containerVirtualCores + "", numContainer="" + numContainers); } + + nodeLabelExpression = cliParser.getOptionValue(""node_label_expression"", null); clientTimeout = Integer.parseInt(cliParser.getOptionValue(""timeout"", ""600000"")); @@ -617,6 +626,9 @@ public boolean run() throws IOException, YarnException { vargs.add(""--container_memory "" + String.valueOf(containerMemory)); vargs.add(""--container_vcores "" + String.valueOf(containerVirtualCores)); vargs.add(""--num_containers "" + String.valueOf(numContainers)); + if (null != nodeLabelExpression) { + appContext.setNodeLabelExpression(nodeLabelExpression); + } vargs.add(""--priority "" + String.valueOf(shellCmdPriority)); for (Map.Entry entry : shellEnv.entrySet()) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java index 2414d4d3ea964..0ded5bd60c53b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java @@ -30,7 +30,9 @@ import java.net.URL; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; @@ -42,6 +44,7 @@ import org.apache.hadoop.util.JarFinder; import org.apache.hadoop.util.Shell; import org.apache.hadoop.yarn.api.records.ApplicationReport; +import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.api.records.timeline.TimelineDomain; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities; @@ -49,40 +52,81 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.server.MiniYARNCluster; import org.apache.hadoop.yarn.server.nodemanager.NodeManager; -import org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerManagerImpl; -import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; -import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; +import org.apache.hadoop.yarn.server.resourcemanager.RMContext; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import com.google.common.collect.ImmutableMap; + public class TestDistributedShell { private static final Log LOG = LogFactory.getLog(TestDistributedShell.class); protected MiniYARNCluster yarnCluster = null; - protected Configuration conf = new YarnConfiguration(); + private int numNodeManager = 1; + + private YarnConfiguration conf = null; protected final static String APPMASTER_JAR = JarFinder.getJar(ApplicationMaster.class); + + private void initializeNodeLabels() throws IOException { + RMContext rmContext = yarnCluster.getResourceManager(0).getRMContext(); + + // Setup node labels + RMNodeLabelsManager labelsMgr = rmContext.getNodeLabelManager(); + Set labels = new HashSet(); + labels.add(""x""); + labelsMgr.addToCluserNodeLabels(labels); + + // Setup queue access to node labels + conf.set(""yarn.scheduler.capacity.root.accessible-node-labels"", ""x""); + conf.set(""yarn.scheduler.capacity.root.default.accessible-node-labels"", ""x""); + conf.set( + ""yarn.scheduler.capacity.root.default.accessible-node-labels.x.capacity"", + ""100""); + + rmContext.getScheduler().reinitialize(conf, rmContext); + + // Fetch node-ids from yarn cluster + NodeId[] nodeIds = new NodeId[numNodeManager]; + for (int i = 0; i < numNodeManager; i++) { + NodeManager mgr = this.yarnCluster.getNodeManager(i); + nodeIds[i] = mgr.getNMContext().getNodeId(); + } + + // Set label x to NM[1] + labelsMgr.addLabelsToNode(ImmutableMap.of(nodeIds[1], labels)); + } @Before public void setup() throws Exception { LOG.info(""Starting up YARN cluster""); + + conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 128); - conf.setClass(YarnConfiguration.RM_SCHEDULER, - FifoScheduler.class, ResourceScheduler.class); conf.set(""yarn.log.dir"", ""target""); conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); + conf.set(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class.getName()); + numNodeManager = 2; + if (yarnCluster == null) { - yarnCluster = new MiniYARNCluster( - TestDistributedShell.class.getSimpleName(), 1, 1, 1, 1, true); + yarnCluster = + new MiniYARNCluster(TestDistributedShell.class.getSimpleName(), 1, + numNodeManager, 1, 1, true); yarnCluster.init(conf); + yarnCluster.start(); - NodeManager nm = yarnCluster.getNodeManager(0); - waitForNMToRegister(nm); + + waitForNMsToRegister(); + + // currently only capacity scheduler support node labels, + initializeNodeLabels(); URL url = Thread.currentThread().getContextClassLoader().getResource(""yarn-site.xml""); if (url == null) { @@ -757,13 +801,15 @@ public void testDSShellWithInvalidArgs() throws Exception { } } - protected static void waitForNMToRegister(NodeManager nm) - throws Exception { - int attempt = 60; - ContainerManagerImpl cm = - ((ContainerManagerImpl) nm.getNMContext().getContainerManager()); - while (cm.getBlockNewContainerRequestsStatus() && attempt-- > 0) { - Thread.sleep(2000); + protected void waitForNMsToRegister() throws Exception { + int sec = 60; + while (sec >= 0) { + if (yarnCluster.getResourceManager().getRMContext().getRMNodes().size() + >= numNodeManager) { + break; + } + Thread.sleep(1000); + sec--; } } @@ -892,5 +938,88 @@ private int verifyContainerLog(int containerNum, } return numOfWords; } + + @Test(timeout=90000) + public void testDSShellWithNodeLabelExpression() throws Exception { + // Start NMContainerMonitor + NMContainerMonitor mon = new NMContainerMonitor(); + Thread t = new Thread(mon); + t.start(); + + // Submit a job which will sleep for 60 sec + String[] args = { + ""--jar"", + APPMASTER_JAR, + ""--num_containers"", + ""4"", + ""--shell_command"", + ""sleep"", + ""--shell_args"", + ""15"", + ""--master_memory"", + ""512"", + ""--master_vcores"", + ""2"", + ""--container_memory"", + ""128"", + ""--container_vcores"", + ""1"", + ""--node_label_expression"", + ""x"" + }; + + LOG.info(""Initializing DS Client""); + final Client client = + new Client(new Configuration(yarnCluster.getConfig())); + boolean initSuccess = client.init(args); + Assert.assertTrue(initSuccess); + LOG.info(""Running DS Client""); + boolean result = client.run(); + LOG.info(""Client run completed. Result="" + result); + + t.interrupt(); + + // Check maximum number of containers on each NMs + int[] maxRunningContainersOnNMs = mon.getMaxRunningContainersReport(); + // Check no container allocated on NM[0] + Assert.assertEquals(0, maxRunningContainersOnNMs[0]); + // Check there're some containers allocated on NM[1] + Assert.assertTrue(maxRunningContainersOnNMs[1] > 0); + } + + /** + * Monitor containers running on NMs + */ + private class NMContainerMonitor implements Runnable { + // The interval of milliseconds of sampling (500ms) + final static int SAMPLING_INTERVAL_MS = 500; + + // The maximum number of containers running on each NMs + int[] maxRunningContainersOnNMs = new int[numNodeManager]; + + @Override + public void run() { + while (true) { + for (int i = 0; i < numNodeManager; i++) { + int nContainers = + yarnCluster.getNodeManager(i).getNMContext().getContainers() + .size(); + if (nContainers > maxRunningContainersOnNMs[i]) { + maxRunningContainersOnNMs[i] = nContainers; + } + } + try { + Thread.sleep(SAMPLING_INTERVAL_MS); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } + } + } + + public int[] getMaxRunningContainersReport() { + return maxRunningContainersOnNMs; + } + } }" b588da4eb4be8419dbffcafccc381b80dec25acb,hadoop,YARN-2269. Remove external links from YARN UI.- Contributed by Craig Welch--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1609591 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 32d88ae61bbbf..55607a612ec34 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -354,6 +354,8 @@ Release 2.5.0 - UNRELEASED YARN-2158. Improved assertion messages of TestRMWebServicesAppsModification. (Varun Vasudev via zjshen) + YARN-2269. Remove External links from YARN UI. (Craig Welch via xgong) + Release 2.4.1 - 2014-06-23 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java index eedf64b276946..ba85ac69d3f60 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java @@ -25,7 +25,6 @@ public class FooterBlock extends HtmlBlock { @Override protected void render(Block html) { html. - div(""#footer.ui-widget""). - a(""http://hadoop.apache.org/"", ""About Apache Hadoop"")._(); + div(""#footer.ui-widget"")._(); } }" 135f05e6728a3a0eb02c8974dafca434557080c0,drools,JBRULES-1736 Dynamically generated Types -Must get- classloader from the rulebase root classloader now--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@21573 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-clips/.classpath b/drools-clips/.classpath index d078808cf23..e330ced3ca6 100644 --- a/drools-clips/.classpath +++ b/drools-clips/.classpath @@ -9,7 +9,21 @@ - + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/drools-clips/src/main/java/org/drools/clips/ClipsShell.java b/drools-clips/src/main/java/org/drools/clips/ClipsShell.java index b9406261086..c3fd0da41c2 100644 --- a/drools-clips/src/main/java/org/drools/clips/ClipsShell.java +++ b/drools-clips/src/main/java/org/drools/clips/ClipsShell.java @@ -403,7 +403,8 @@ public void lispFormHandler(LispForm lispForm) { context.addPackageImport( importName.substring( 0, importName.length() - 2 ) ); } else { - Class cls = pkg.getDialectRuntimeRegistry().getClassLoader().loadClass( importName ); + + Class cls = ((InternalRuleBase)ruleBase).getRootClassLoader().loadClass( importName ); context.addImport( cls.getSimpleName(), (Class) cls ); } @@ -418,7 +419,7 @@ public void lispFormHandler(LispForm lispForm) { } ClassLoader tempClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( pkg.getPackageScopeClassLoader() ); + Thread.currentThread().setContextClassLoader( ((InternalRuleBase)ruleBase).getRootClassLoader() ); ExpressionCompiler expr = new ExpressionCompiler( appendable.toString() ); Serializable executable = expr.compile( context ); diff --git a/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java b/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java index 251ba45fdf0..6d8994bccc1 100644 --- a/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java +++ b/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java @@ -31,6 +31,7 @@ import org.drools.clips.functions.RunFunction; import org.drools.clips.functions.SetFunction; import org.drools.clips.functions.SwitchFunction; +import org.drools.common.InternalRuleBase; import org.drools.rule.Package; import org.drools.rule.Rule; @@ -251,7 +252,7 @@ public void FIXME_testTemplateCreation2() throws Exception { this.shell.eval( ""(defrule xxx (PersonTemplate (name ?name&bob) (age 30) ) (PersonTemplate (name ?name) (age 35)) => (printout t xx \"" \"" (eq 1 1) ) )"" ); this.shell.eval( ""(assert (PersonTemplate (name 'mike') (age 34)))"" ); - Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( ""MAIN"" ).getPackageScopeClassLoader().loadClass( ""MAIN.PersonTemplate"" ); + Class personClass = ((InternalRuleBase)this.shell.getStatefulSession().getRuleBase()).getRootClassLoader().loadClass( ""MAIN.PersonTemplate"" ); assertNotNull( personClass ); } @@ -287,7 +288,7 @@ public void testTemplateCreationWithJava() throws Exception { pkg.getRules().length ); WorkingMemory wm = shell.getStatefulSession(); - Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( ""MAIN"" ).getPackageScopeClassLoader().loadClass( ""MAIN.Person"" ); + Class personClass = ((InternalRuleBase)this.shell.getStatefulSession().getRuleBase()).getRootClassLoader().loadClass( ""MAIN.Person"" ); Method nameMethod = personClass.getMethod( ""setName"", new Class[]{String.class} );" f6f9278eefa378e57bf4f2ededee32e266c8f76d,restlet-framework-java,Fixed content negotiation issue in the servlet- extension.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java b/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java index 21de031c59..2a4e443cb0 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/ServerCall.java @@ -55,6 +55,7 @@ import org.restlet.engine.security.SslUtils; import org.restlet.engine.util.Base64; import org.restlet.engine.util.StringUtils; +import org.restlet.representation.EmptyRepresentation; import org.restlet.representation.InputRepresentation; import org.restlet.representation.ReadableRepresentation; import org.restlet.representation.Representation; @@ -154,19 +155,29 @@ public Representation getRequestEntity() { Representation result = null; long contentLength = getContentLength(); - // Create the result representation - InputStream requestStream = getRequestEntityStream(contentLength); - ReadableByteChannel requestChannel = getRequestEntityChannel(contentLength); + boolean chunkedEncoding = HeaderUtils.isChunkedEncoding(getRequestHeaders()); + // In some cases there is an entity without a content-length header + boolean connectionClosed = HeaderUtils.isConnectionClose(getRequestHeaders()); + + // Create the representation + if ((contentLength != Representation.UNKNOWN_SIZE && contentLength != 0) + || chunkedEncoding || connectionClosed) { + // Create the result representation + InputStream requestStream = getRequestEntityStream(contentLength); + ReadableByteChannel requestChannel = getRequestEntityChannel(contentLength); + + if (requestStream != null) { + result = new InputRepresentation(requestStream, null, contentLength); + } else if (requestChannel != null) { + result = new ReadableRepresentation(requestChannel, null, + contentLength); + } - if (requestStream != null) { - result = new InputRepresentation(requestStream, null, contentLength); - } else if (requestChannel != null) { - result = new ReadableRepresentation(requestChannel, null, - contentLength); + result.setSize(contentLength); + } else { + result = new EmptyRepresentation(); } - result.setSize(contentLength); - // Extract some interesting header values for (Parameter header : getRequestHeaders()) { if (header.getName().equalsIgnoreCase(" cfbc081dfdc76590d3f1e11b72caa1e30cf9134b,camel,Added some logs for debuging--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@757865 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java index 5ac4329600290..de37a6ef52bad 100644 --- a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java @@ -27,6 +27,8 @@ import org.apache.camel.impl.converter.AnnotationTypeConverterLoader; import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.impl.converter.TypeConverterLoader; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.springframework.osgi.context.BundleContextAware; @@ -35,7 +37,7 @@ * any spring application context involved. */ public class CamelContextFactory implements BundleContextAware { - + private static final transient Log LOG = LogFactory.getLog(CamelContextFactory.class); private BundleContext bundleContext; public BundleContext getBundleContext() { @@ -49,6 +51,7 @@ public void setBundleContext(BundleContext bundleContext) { public DefaultCamelContext createContext() { DefaultCamelContext context = new DefaultCamelContext(); if (bundleContext != null) { + LOG.debug(""The bundle context is not be null, let's setup the Osgi resolvers""); context.setPackageScanClassResolver(new OsgiPackageScanClassResolver(bundleContext)); context.setComponentResolver(new OsgiComponentResolver()); context.setLanguageResolver(new OsgiLanguageResolver()); @@ -74,5 +77,6 @@ protected void addOsgiAnnotationTypeConverterLoader(DefaultCamelContext context, typeConverterLoaders.remove(atLoader); } typeConverterLoaders.add(new OsgiAnnotationTypeConverterLoader(context.getPackageScanClassResolver())); + LOG.debug(""added the OsgiAnnotationTypeConverterLoader""); } } diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java index fa82a6cffeb97..c42a53625b749 100644 --- a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java @@ -26,13 +26,16 @@ import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.impl.converter.TypeConverterLoader; import org.apache.camel.spring.SpringCamelContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; import org.springframework.osgi.context.BundleContextAware; @XmlRootElement(name = ""camelContext"") @XmlAccessorType(XmlAccessType.FIELD) public class CamelContextFactoryBean extends org.apache.camel.spring.CamelContextFactoryBean implements BundleContextAware { - + private static final transient Log LOG = LogFactory.getLog(CamelContextFactoryBean.class); + @XmlTransient private BundleContext bundleContext; @@ -47,6 +50,7 @@ public void setBundleContext(BundleContext bundleContext) { protected SpringCamelContext createContext() { SpringCamelContext context = super.createContext(); if (bundleContext != null) { + LOG.debug(""The bundle context is not be null, let's setup the Osgi resolvers""); context.setPackageScanClassResolver(new OsgiPackageScanClassResolver(bundleContext)); context.setComponentResolver(new OsgiComponentResolver()); context.setLanguageResolver(new OsgiLanguageResolver()); @@ -74,6 +78,7 @@ protected void addOsgiAnnotationTypeConverterLoader(SpringCamelContext context) // add our osgi annotation loader typeConverterLoaders.add(new OsgiAnnotationTypeConverterLoader(context.getPackageScanClassResolver())); + LOG.debug(""added the OsgiAnnotationTypeConverterLoader""); } }" 7b9603d029bd651dd5cfb92903ea956e9eeaf712,drools,remove support of deprecated brl files--,p,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/BusinessRuleProviderFactory.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/BusinessRuleProviderFactory.java deleted file mode 100644 index 905d9a1ff64..00000000000 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/BusinessRuleProviderFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2011 JBoss Inc - * - * Licensed under the Apache License, Version 2.0 (the ""License""); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package org.drools.compiler.compiler; - -import org.drools.core.CheckedDroolsException; -import org.kie.internal.utils.ServiceRegistryImpl; - -public class BusinessRuleProviderFactory { - - private static BusinessRuleProviderFactory instance = new BusinessRuleProviderFactory(); - private static BusinessRuleProvider provider; - - private BusinessRuleProviderFactory() { - } - - public static BusinessRuleProviderFactory getInstance() { - return instance; - } - - public BusinessRuleProvider getProvider() throws CheckedDroolsException { - if ( null == provider ) loadProvider(); - return provider; - } - - public static synchronized void setBusinessRuleProvider(BusinessRuleProvider provider) { - BusinessRuleProviderFactory.provider = provider; - } - - private void loadProvider() throws CheckedDroolsException { - ServiceRegistryImpl.getInstance().addDefault( BusinessRuleProvider.class, - ""org.drools.ide.common.BusinessRuleProviderDefaultImpl"" ); - setBusinessRuleProvider( ServiceRegistryImpl.getInstance().get( BusinessRuleProvider.class ) ); - } - -} diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java index effd4c9df76..aa7f86bea3e 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java @@ -343,23 +343,6 @@ private Collection buildPackageDescr() { } } - resourcesByType = this.resourcesByType.remove(ResourceType.BRL); - if (resourcesByType != null) { - for (ResourceDescr resourceDescr : resourcesByType) { - try { - registerPackageDescr(packages, resourceDescr.resource, pkgBuilder.brlToPackageDescr(resourceDescr.resource)); - } catch (RuntimeException e) { - if (buildException == null) { - buildException = e; - } - } catch (Exception e) { - if (buildException == null) { - buildException = new RuntimeException( e ); - } - } - } - } - resourcesByType = this.resourcesByType.remove(ResourceType.DTABLE); if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java index 0da5d70ec46..3c1044abd40 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java @@ -596,41 +596,6 @@ PackageDescr dslrToPackageDescr(Resource resource) throws DroolsParserException return hasErrors ? null : pkg; } - public void addPackageFromBrl( final Resource resource ) throws DroolsParserException { - this.resource = resource; - try { - addPackage( brlToPackageDescr(resource) ); - } catch (Exception e) { - throw new DroolsParserException( e ); - } finally { - this.resource = null; - } - } - - PackageDescr brlToPackageDescr(Resource resource) throws Exception { - BusinessRuleProvider provider = BusinessRuleProviderFactory.getInstance().getProvider(); - Reader knowledge = provider.getKnowledgeReader( resource ); - - DrlParser parser = new DrlParser(configuration.getLanguageLevel()); - - if (provider.hasDSLSentences()) { - DefaultExpander expander = getDslExpander(); - - if (null != expander) { - knowledge = new StringReader( expander.expand( knowledge ) ); - if (expander.hasErrors()) - this.results.addAll( expander.getErrors() ); - } - } - - PackageDescr pkg = parser.parse( knowledge ); - if (parser.hasErrors()) { - this.results.addAll( parser.getErrors() ); - return null; - } - return pkg; - } - public void addDsl( Resource resource ) throws IOException { this.resource = resource; DSLTokenizedMappingFile file = new DSLTokenizedMappingFile(); @@ -703,8 +668,6 @@ public void addKnowledgeResource( Resource resource, addDsl( resource ); } else if (ResourceType.XDRL.equals( type )) { addPackageFromXml( resource ); - } else if (ResourceType.BRL.equals( type )) { - addPackageFromBrl( resource ); } else if (ResourceType.DRF.equals( type )) { addProcessFromXml( resource ); } else if (ResourceType.BPMN2.equals( type )) {" 77f1f5cd336bbd3c7b9d548a4916084bc1e56dc3,orientdb,Console: fixed jdk6 problem in more elegant way- (thanks to Andrey's suggestion)--,p,https://github.com/orientechnologies/orientdb,"diff --git a/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java b/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java index aaeb27f7b7d..804182cb751 100755 --- a/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java +++ b/commons/src/main/java/com/orientechnologies/common/console/ODFACommandStream.java @@ -107,11 +107,10 @@ public String nextCommand() { result = partialResult.toString(); } } else { - try { - result = buffer.subSequence(start, end + 1).toString(); - } catch (NoSuchMethodError e) { - result = buffer.toString().substring(start, end + 1); - } + // DON'T PUT THIS ON ONE LINE ONLY BECAUSE WITH JDK6 subSequence() RETURNS A CHAR CharSequence while JDK7+ RETURNS + // CharBuffer + final CharSequence cs = buffer.subSequence(start, end + 1); + result = cs.toString(); } buffer.position(buffer.position() + position);" 5acb3713b509efd92e51d2e3501988ff6ec4f34d,intellij-community,IDEA-81004 Deadlock (SoftWrapApplianceManager)--Breaking potentially endless loop and report an error-,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java index 948b08c570382..323e15b63b1a1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -419,13 +419,31 @@ private boolean processOutOfDateFoldRegion(FoldRegion foldRegion) { * 'Token' here stands for the number of subsequent symbols that are represented using the same font by IJ editor. */ private void processNonFoldToken() { + int limit = 3 * (myContext.tokenEndOffset - myContext.lineStartPosition.offset); + int counter = 0; + int startOffset = myContext.currentPosition.offset; while (myContext.currentPosition.offset < myContext.tokenEndOffset) { - //for (int i = myContext.startOffset; i < myContext.endOffset; i++) { + if (counter++ > limit) { + String editorInfo = myEditor instanceof EditorImpl ? ((EditorImpl)myEditor).dumpState() : myEditor.getClass().toString(); + LogMessageEx.error(LOG, ""Cycled soft wraps recalculation detected"", String.format( + ""Start recalculation offset: %d, visible area width: %d, calculation context: %s, editor info: %s"", + startOffset, myVisibleAreaWidth, myContext, editorInfo)); + for (int i = myContext.currentPosition.offset; i < myContext.tokenEndOffset; i++) { + char c = myContext.text.charAt(i); + if (c == '\n') { + myContext.onNewLine(); + } + else { + myContext.onNonLineFeedSymbol(c); + } + } + return; + } int offset = myContext.currentPosition.offset; if (offset > myContext.rangeEndOffset) { return; } - + if (myContext.delayedSoftWrap != null && myContext.delayedSoftWrap.getStart() == offset) { processSoftWrap(myContext.delayedSoftWrap); myContext.delayedSoftWrap = null; @@ -442,7 +460,7 @@ private void processNonFoldToken() { createSoftWrapIfPossible(); continue; } - + int newX = offsetToX(offset, c); if (myContext.exceedsVisualEdge(newX) && myContext.delayedSoftWrap == null) { createSoftWrapIfPossible(); @@ -1119,6 +1137,14 @@ private class ProcessingContext { public boolean notifyListenersOnLineStartPosition; public boolean skipToLineEnd; + @Override + public String toString() { + return ""reserved width: "" + reservedWidthInPixels + "", soft wrap start offset: "" + softWrapStartOffset + "", range end offset: "" + + rangeEndOffset + "", token offsets: ["" + tokenStartOffset + ""; "" + tokenEndOffset + ""], font type: "" + fontType + + "", skip to line end: "" + skipToLineEnd + "", delayed soft wrap: "" + delayedSoftWrap + "", current position: ""+ currentPosition + + ""line start position: "" + lineStartPosition; + } + public void reset() { text = null; lineStartPosition = null;" bd5a2f972f8c896a896f291d644f4f31b0c2395e,hbase,HBASE-7307 MetaReader.tableExists should not- return false if the specified table regions has been split (Rajesh)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1419998 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java index ebf60d5b0ccf..ea9da0c4ee2e 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/catalog/MetaReader.java @@ -322,7 +322,6 @@ public boolean visit(Result r) throws IOException { return true; } if (!isInsideTable(this.current, tableNameBytes)) return false; - if (this.current.isSplitParent()) return true; // Else call super and add this Result to the collection. super.visit(r); // Stop collecting regions from table after we get one. diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java index fcfb76478292..2780b93a4417 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java @@ -46,6 +46,7 @@ import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.UnknownRegionException; import org.apache.hadoop.hbase.ZooKeeperConnectionException; +import org.apache.hadoop.hbase.catalog.MetaReader; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; @@ -626,7 +627,48 @@ public void run() { } } } - + + @Test(timeout = 20000) + public void testTableExistsIfTheSpecifiedTableRegionIsSplitParent() throws Exception { + final byte[] tableName = + Bytes.toBytes(""testTableExistsIfTheSpecifiedTableRegionIsSplitParent""); + HRegionServer regionServer = null; + List regions = null; + HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); + try { + // Create table then get the single region for our new table. + HTableDescriptor htd = new HTableDescriptor(tableName); + htd.addFamily(new HColumnDescriptor(""cf"")); + admin.createTable(htd); + HTable t = new HTable(cluster.getConfiguration(), tableName); + regions = cluster.getRegions(tableName); + int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName()); + regionServer = cluster.getRegionServer(regionServerIndex); + insertData(tableName, admin, t); + // Turn off balancer so it doesn't cut in and mess up our placements. + admin.setBalancerRunning(false, false); + // Turn off the meta scanner so it don't remove parent on us. + cluster.getMaster().setCatalogJanitorEnabled(false); + boolean tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), + Bytes.toString(tableName)); + assertEquals(""The specified table should present."", true, tableExists); + SplitTransaction st = new SplitTransaction(regions.get(0), Bytes.toBytes(""row2"")); + try { + st.prepare(); + st.createDaughters(regionServer, regionServer); + } catch (IOException e) { + + } + tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), + Bytes.toString(tableName)); + assertEquals(""The specified table should present."", true, tableExists); + } finally { + admin.setBalancerRunning(true, false); + cluster.getMaster().setCatalogJanitorEnabled(true); + admin.close(); + } + } + private void insertData(final byte[] tableName, HBaseAdmin admin, HTable t) throws IOException, InterruptedException { Put p = new Put(Bytes.toBytes(""row1""));" 8aea3a2f7d179d0b7f935ec8247533787b0dc71d,elasticsearch,[TEST] fixed TestCluster size() javadocs--,p,https://github.com/elastic/elasticsearch,"diff --git a/src/test/java/org/elasticsearch/test/ImmutableTestCluster.java b/src/test/java/org/elasticsearch/test/ImmutableTestCluster.java index 644c6b75848a0..a37edfa52396d 100644 --- a/src/test/java/org/elasticsearch/test/ImmutableTestCluster.java +++ b/src/test/java/org/elasticsearch/test/ImmutableTestCluster.java @@ -114,7 +114,7 @@ public void assertAfterTest() { public abstract Client client(); /** - * Returns the size of the cluster + * Returns the number of nodes in the cluster. */ public abstract int size(); diff --git a/src/test/java/org/elasticsearch/test/TestCluster.java b/src/test/java/org/elasticsearch/test/TestCluster.java index 2eedaeed2b5a2..ced0f8dc85263 100644 --- a/src/test/java/org/elasticsearch/test/TestCluster.java +++ b/src/test/java/org/elasticsearch/test/TestCluster.java @@ -788,9 +788,6 @@ private synchronized T getInstanceFromNode(Class clazz, InternalNode node return node.injector().getInstance(clazz); } - /** - * Returns the number of nodes in the cluster. - */ @Override public synchronized int size() { return this.nodes.size();" 85cb78d8788f9f604ba9f644126c3ebf30bdfd7b,hbase,HBASE-8287 TestRegionMergeTransactionOnCluster- failed in trunk build -4010--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1465528 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/DispatchMergingRegionHandler.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/DispatchMergingRegionHandler.java index 88626f355734..65ff8c4000a5 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/DispatchMergingRegionHandler.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/DispatchMergingRegionHandler.java @@ -121,10 +121,14 @@ public void process() throws IOException { while (!masterServices.isStopped()) { try { Thread.sleep(20); + // Make sure check RIT first, then get region location, otherwise + // we would make a wrong result if region is online between getting + // region location and checking RIT + boolean isRIT = regionStates.isRegionInTransition(region_b); region_b_location = masterServices.getAssignmentManager() .getRegionStates().getRegionServerOfRegion(region_b); onSameRS = region_a_location.equals(region_b_location); - if (onSameRS || !regionStates.isRegionInTransition(region_b)) { + if (onSameRS || !isRIT) { // Regions are on the same RS, or region_b is not in // RegionInTransition any more break;" b580f0706dc1dcded6d1a584c37a83dd1cb2ea2a,restlet-framework-java, - The simplified logging formatter (one line)- is now available only in the Java SE edition as it could cause- troubles with Java EE container and potentially GAE/Android as we- reconfigure the default log manager programmatically. Reported by- Kristoffer Gronowski and Bo Xing.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 9f9255ad31..44c46f7a7b 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -11,6 +11,10 @@ Changes log 500 status being returned to the client instead of the given status. Reported by Avi Flax and Rhett Sutphin. - Misc + - The simplified logging formatter (one line) is now available only in + the Java SE edition as it could cause troubles with Java EE container + and potentially GAE/Android as we reconfigure the default log manager + programmatically. Reported by Kristoffer Gronowski and Bo Xing. - 2.1 Milestone 3 (03/31/2011) - Breaking changes diff --git a/modules/org.restlet/src/org/restlet/engine/Engine.java b/modules/org.restlet/src/org/restlet/engine/Engine.java index 0d0aba0756..d3d0799f87 100644 --- a/modules/org.restlet/src/org/restlet/engine/Engine.java +++ b/modules/org.restlet/src/org/restlet/engine/Engine.java @@ -101,13 +101,15 @@ public class Engine { /** The registered engine. */ private static volatile Engine instance = null; + // [ifdef jse] member /** The org.restlet log level . */ private static volatile boolean logConfigured = false; - // [ifndef gwt] member + // [ifdef jse] member /** The general log formatter. */ private static volatile Class logFormatter = org.restlet.engine.log.SimplestFormatter.class; + // [ifdef jse] member /** The general log level . */ private static volatile Level logLevel = Level.INFO; @@ -120,6 +122,7 @@ public class Engine { /** Release number. */ public static final String RELEASE_NUMBER = ""@release-type@@release-number@""; + // [ifdef jse] member /** The org.restlet log level . */ private static volatile Level restletLogLevel; @@ -148,11 +151,11 @@ public static void clearThreadLocalVariables() { org.restlet.Application.setCurrent(null); } + // [ifdef jse] method /** * Updates the global log configuration of the JVM programmatically. */ public static void configureLog() { - // [ifndef gwt] if ((System.getProperty(""java.util.logging.config.file"") == null) && (System.getProperty(""java.util.logging.config.class"") == null)) { StringBuilder sb = new StringBuilder(); @@ -188,13 +191,10 @@ public static void configureLog() { CharacterSet.DEFAULT)); } catch (Exception e) { e.printStackTrace(); - } finally { - logConfigured = true; } } - // [enddef] - // [ifdef gwt] instruction uncomment - // logConfigured = true; + + logConfigured = true; } /** @@ -222,7 +222,7 @@ public static synchronized Engine getInstance() { return result; } - // [ifndef gwt] method + // [ifdef jse] method /** * Returns the general log formatter. * @@ -284,6 +284,7 @@ public static Logger getLogger(String loggerName) { return getInstance().getLoggerFacade().getLogger(loggerName); } + // [ifdef jse] method /** * Returns the general log level. * @@ -305,6 +306,7 @@ public static java.net.URL getResource(String name) { return getInstance().getClassLoader().getResource(name); } + // [ifdef jse] method /** * Returns the Restlet log level. For loggers with a name starting with * ""org.restlet"". @@ -346,10 +348,11 @@ public static synchronized Engine register() { * @return The registered engine. */ public static synchronized Engine register(boolean discoverPlugins) { + // [ifdef jse] if (!logConfigured) { configureLog(); } - + // [enddef] Engine result = new Engine(discoverPlugins); org.restlet.engine.Engine.setInstance(result); return result; @@ -368,7 +371,7 @@ public static synchronized void setInstance(Engine engine) { instance = engine; } - // [ifndef gwt] method + // [ifdef jse] method /** * Sets the general log formatter. * @@ -380,6 +383,7 @@ public static void setLogFormatter(Class logFormatter) { configureLog(); } + // [ifdef jse] method /** * Sets the general log level. Modifies the global JVM's {@link LogManager}. * @@ -391,6 +395,7 @@ public static void setLogLevel(Level logLevel) { configureLog(); } + // [ifdef jse] method /** * Sets the Restlet log level. For loggers with a name starting with * ""org.restlet""." 111d34b6af146f675dd6ccd9ba67fc826386542a,restlet-framework-java, - Fixed selector exhaustion issue with- Grizzly connector. Reported by Bruce Lee.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/eclipse/dictionary.xml b/build/tmpl/eclipse/dictionary.xml index 92e6fd8dd5..2a53b7b82a 100644 --- a/build/tmpl/eclipse/dictionary.xml +++ b/build/tmpl/eclipse/dictionary.xml @@ -30,3 +30,5 @@ rhett sutphin codec waldin +arcand +francois diff --git a/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java b/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java index d3d16e4f10..a7b8214248 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java +++ b/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java @@ -74,12 +74,6 @@ public NbChannelOutputStream(WritableByteChannel channel) { this.selector = null; } - @Override - public void close() throws IOException { - NioUtils.release(this.selector, this.selectionKey); - super.close(); - } - /** * Effectively write the current byte buffer. * @@ -135,6 +129,7 @@ private void doWrite() throws IOException { + ioe.getLocalizedMessage()); } finally { this.bb.clear(); + NioUtils.release(this.selector, this.selectionKey); } } else { throw new IOException( diff --git a/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java b/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java index cd2220acf2..3e6b70a597 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java +++ b/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java @@ -38,20 +38,23 @@ * @author Jean-Francois Arcand */ public class SelectorFactory { - /** The number of Selector to create. */ - public static int maxSelectors = 20; + /** The maximum number of Selector to create. */ + public static final int MAX_SELECTORS = 20; + + /** The number of attempts to find an available selector. */ + public static final int MAX_ATTEMPTS = 2; /** Cache of Selector. */ - private final static Stack selectors = new Stack(); + private static final Stack SELECTORS = new Stack(); /** The timeout before we exit. */ - public static long timeout = 5000; + public static final long TIMEOUT = 5000; /** Creates the Selector. */ static { try { - for (int i = 0; i < maxSelectors; i++) { - selectors.add(Selector.open()); + for (int i = 0; i < MAX_SELECTORS; i++) { + SELECTORS.add(Selector.open()); } } catch (IOException ex) { // do nothing. @@ -64,24 +67,24 @@ public class SelectorFactory { * @return An exclusive Selector. */ public final static Selector getSelector() { - synchronized (selectors) { + synchronized (SELECTORS) { Selector selector = null; try { - if (selectors.size() != 0) { - selector = selectors.pop(); + if (SELECTORS.size() != 0) { + selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { } int attempts = 0; try { - while ((selector == null) && (attempts < 2)) { - selectors.wait(timeout); + while ((selector == null) && (attempts < MAX_ATTEMPTS)) { + SELECTORS.wait(TIMEOUT); try { - if (selectors.size() != 0) { - selector = selectors.pop(); + if (SELECTORS.size() != 0) { + selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { break; @@ -103,10 +106,10 @@ public final static Selector getSelector() { * The Selector to return. */ public final static void returnSelector(Selector selector) { - synchronized (selectors) { - selectors.push(selector); - if (selectors.size() == 1) { - selectors.notify(); + synchronized (SELECTORS) { + SELECTORS.push(selector); + if (SELECTORS.size() == 1) { + SELECTORS.notify(); } } }" 319b1c8ad41b769ff4bc5d8cb2d2eb9e3f5e9569,orientdb,"Minor: fixed javadoc, put a variable as final,- managed no return in OPLA/execute block--",p,https://github.com/orientechnologies/orientdb,"diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java index a917b02364d..4129b9cd427 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OSchemaShared.java @@ -451,7 +451,7 @@ public void changeClassName(String iOldName, String iNewName) { @Override public void fromStream() { // READ CURRENT SCHEMA VERSION - Integer schemaVersion = (Integer) document.field(""schemaVersion""); + final Integer schemaVersion = (Integer) document.field(""schemaVersion""); if (schemaVersion == null) { OLogManager .instance() diff --git a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OExecuteBlock.java b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OExecuteBlock.java index 32e5490f405..d362d20134b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OExecuteBlock.java +++ b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OExecuteBlock.java @@ -112,10 +112,13 @@ private Object executeBlock(OComposableProcessor iManager, final OCommandContext merge = Boolean.FALSE; Object result; - if (isBlock(iValue)) + if (isBlock(iValue)) { // EXECUTE SINGLE BLOCK - result = delegate(iName, iManager, (ODocument) iValue, iContext, iOutput, iReadOnly); - else { + final ODocument value = (ODocument) iValue; + result = delegate(iName, iManager, value, iContext, iOutput, iReadOnly); + if (value.containsField(""return"")) + return returnValue; + } else { // EXECUTE ENTIRE PROCESS try { result = iManager.processFromFile(iName, iContext, iReadOnly); diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/post/OServerCommandPostBatch.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/post/OServerCommandPostBatch.java index dac2e488b04..8aa9509e2f0 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/post/OServerCommandPostBatch.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/http/command/post/OServerCommandPostBatch.java @@ -26,9 +26,9 @@ import com.orientechnologies.orient.server.network.protocol.http.command.OServerCommandDocumentAbstract; /** - * Execute a batch of commands in one shot. This is useful to reduce network latency issuing multiple commands as multiple request. - * Batch command supports transactions.
      - * Format: { ""transaction"" : , ""operations"" : [ { ""type"" : """" }* ] }
      + * Executes a batch of operations in a single call. This is useful to reduce network latency issuing multiple commands as multiple + * requests. Batch command supports transactions as well.

      + * Format: { ""transaction"" : <true|false>, ""operations"" : [ { ""type"" : ""<type>"" }* ] }
      * Where: *
        *
      • type can be:" 40822746306f5d0e5d553504275046ec4906309b,spring-framework,SQLStateSQLExceptionTranslator checks exception- class name for timeout indication before resorting to- UncategorizedSQLException--Issue: SPR-11959-,c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslator.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslator.java index 0fc68068b158..1cd9144ff3d1 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslator.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLStateSQLExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.QueryTimeoutException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; @@ -87,6 +88,7 @@ public class SQLStateSQLExceptionTranslator extends AbstractFallbackSQLException @Override protected DataAccessException doTranslate(String task, String sql, SQLException ex) { + // First, the getSQLState check... String sqlState = getSqlState(ex); if (sqlState != null && sqlState.length() >= 2) { String classCode = sqlState.substring(0, 2); @@ -109,6 +111,14 @@ else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) { return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex); } } + + // For MySQL: exception class name indicating a timeout? + // (since MySQL doesn't throw the JDBC 4 SQLTimeoutException) + if (ex.getClass().getName().contains(""Timeout"")) { + return new QueryTimeoutException(buildMessage(task, sql, ex), ex); + } + + // Couldn't resolve anything proper - resort to UncategorizedSQLException. return null; }"