diff --git "a/test.csv" "b/test.csv" new file mode 100644--- /dev/null +++ "b/test.csv" @@ -0,0 +1,33205 @@ +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,"⚠️ Exception: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: /spring-projects/spring-framework/commit/a429e230b632c40cf3167cbac54ea87b6ad87297.diff (Caused by ConnectTimeoutError(, 'Connection to github.com timed out. (connect timeout=10)'))" +da5ff665396d5f0cbd70b9ea8a53387c0b40cbd1,orientdb,Fixed problem with linkeset modified right after- query in remote configuration--,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +2ea800d7cf8bb3d5455402af7291bac9deb2fe46,orientdb,Index in tx: Fixed issue 468 about deletion--,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +ae360480a9a955030a6621721a649bbf360d3c9a,orientdb,Improved performance by handling begin and end of- offsets in cluster data.--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,"⚠️ Exception: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: /JetBrains/intellij-community/commit/3b68aaa84cfa714a4d1b5ef0c615d924e75d2be0.diff (Caused by ConnectTimeoutError(, 'Connection to github.com timed out. (connect timeout=10)'))" +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/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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,"⚠️ Exception: HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: /apache/hadoop/commit/a3ecc3b910aa3bbc3ede2b8ba1bd040d02a26ca8.diff (Caused by ConnectTimeoutError(, 'Connection to github.com timed out. (connect timeout=10)'))" +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/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +c689af142aefea121ae87e32fe775f9859b7344a,kotlin,Fixed highlighting for enum and object names in- code-- -KT-8134 Fixed-,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +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; + }"