commit_id
stringlengths 40
40
| project
stringclasses 11
values | commit_message
stringlengths 3
3.04k
| type
stringclasses 3
values | url
stringclasses 11
values | git_diff
stringlengths 555
691k
|
|---|---|---|---|---|---|
ad7d030f22ff9450aaff6991680613ee5f90b792
|
camel
|
fixed test case which was failing sometimes on- linux--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@576445 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java b/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
index 8148943c3ba9c..5ee3229aaa570 100644
--- a/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
+++ b/components/camel-ibatis/src/test/java/org/apache/camel/component/ibatis/IBatisRouteTest.java
@@ -45,7 +45,7 @@ public void testSendAccountBean() throws Exception {
assertMockEndpointsSatisifed();
List<Exchange> list = endpoint.getReceivedExchanges();
- Exchange exchange = list.get(0);
+ Exchange exchange = list.get(list.size() - 1);
List body = exchange.getIn().getBody(List.class);
assertNotNull("Should have returned a List!", body);
assertEquals("Wrong size: " + body, 1, body.size());
|
b728ba8816547d2f4264404ada41083f4b971697
|
drools
|
[BZ-1200383] when a dependency cannot be found log- the complete stack trace only in debug mode--
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/kie-ci/src/main/java/org/kie/scanner/MavenRepository.java b/kie-ci/src/main/java/org/kie/scanner/MavenRepository.java
index 53556aca08c..53941b2ce78 100644
--- a/kie-ci/src/main/java/org/kie/scanner/MavenRepository.java
+++ b/kie-ci/src/main/java/org/kie/scanner/MavenRepository.java
@@ -217,7 +217,11 @@ public Artifact resolveArtifact(String artifactName, boolean logUnresolvedArtifa
return artifactResult.getArtifact();
} catch (ArtifactResolutionException e) {
if (logUnresolvedArtifact) {
- log.warn("Unable to resolve artifact: " + artifactName, e);
+ if (log.isDebugEnabled()) {
+ log.debug("Unable to resolve artifact: " + artifactName, e);
+ } else {
+ log.warn("Unable to resolve artifact: " + artifactName);
+ }
}
return null;
}
@@ -234,7 +238,11 @@ public Version resolveVersion(String artifactName) {
VersionRangeResult versionRangeResult = aether.getSystem().resolveVersionRange(aether.getSession(), versionRequest);
return versionRangeResult.getHighestVersion();
} catch (VersionRangeResolutionException e) {
- log.warn("Unable to resolve version range for artifact: " + artifactName, e);
+ if (log.isDebugEnabled()) {
+ log.debug("Unable to resolve version range for artifact: " + artifactName, e);
+ } else {
+ log.warn("Unable to resolve version range for artifact: " + artifactName);
+ }
return null;
}
}
|
063f561c851a1bfd717762d96a9d379b79bbb941
|
orientdb
|
Issue -71:- http://code.google.com/p/orient/issues/detail?id=71 Working in progress--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordFactory.java b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordFactory.java
index 04b8a5e9eb9..25c7793c58d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/record/ORecordFactory.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/record/ORecordFactory.java
@@ -55,6 +55,19 @@ public static ORecordFactory instance() {
return instance;
}
+ public static String getRecordTypeName(final byte iRecordType) {
+ if (iRecordType == ODocument.RECORD_TYPE)
+ return "document";
+ else if (iRecordType == ORecordFlat.RECORD_TYPE)
+ return "flat";
+ else if (iRecordType == ORecordBytes.RECORD_TYPE)
+ return "bytes";
+ else if (iRecordType == ORecordColumn.RECORD_TYPE)
+ return "column";
+
+ throw new IllegalArgumentException("Unsupported record type" + iRecordType);
+ }
+
public static ORecordInternal<?> newInstance(final byte iRecordType) {
if (iRecordType == ODocument.RECORD_TYPE)
return new ODocument();
@@ -65,6 +78,6 @@ else if (iRecordType == ORecordBytes.RECORD_TYPE)
else if (iRecordType == ORecordColumn.RECORD_TYPE)
return new ORecordColumn();
- throw new IllegalArgumentException("Unsuppurted record type" + iRecordType);
+ throw new IllegalArgumentException("Unsupported record type" + iRecordType);
}
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemRecordAttrib.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemRecordAttrib.java
new file mode 100644
index 00000000000..44dcb14617a
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterItemRecordAttrib.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.orientechnologies.orient.core.sql.filter;
+
+import java.io.IOException;
+
+import com.orientechnologies.orient.core.command.OCommandToParse;
+import com.orientechnologies.orient.core.record.ORecordFactory;
+import com.orientechnologies.orient.core.record.ORecordInternal;
+import com.orientechnologies.orient.core.record.ORecordSchemaAware;
+
+/**
+ * Represent a special attribute of the record such as:
+ * <ul>
+ * <li>@rid, the record id</li>
+ * <li>@class, the record class if it's schema aware</li>
+ * <li>@version, the version</li>
+ * <li>@type, the type between: 'document', 'column', 'flat', 'bytes'</li>
+ * <li>@size, the size on disk in bytes
+ * </ul>
+ *
+ * @author Luca Garulli
+ *
+ */
+public class OSQLFilterItemRecordAttrib extends OSQLFilterItemAbstract {
+ public OSQLFilterItemRecordAttrib(final OCommandToParse iQueryToParse, final String iName) {
+ super(iQueryToParse, iName);
+ }
+
+ public Object getValue(final ORecordInternal<?> iRecord) {
+ if (name.equals("@rid"))
+ return transformValue(iRecord.getDatabase(), iRecord.getIdentity());
+ else if (name.equals("@version"))
+ return transformValue(iRecord.getDatabase(), iRecord.getVersion());
+ else if (name.equals("@class") && iRecord instanceof ORecordSchemaAware<?>)
+ return transformValue(iRecord.getDatabase(), ((ORecordSchemaAware<?>) iRecord).getClassName());
+ else if (name.equals("@type"))
+ return transformValue(iRecord.getDatabase(), ORecordFactory.getRecordTypeName(iRecord.getRecordType()));
+ else if (name.equals("@size")) {
+ byte[] stream;
+ try {
+ stream = iRecord.toStream();
+ if (stream != null)
+ transformValue(iRecord.getDatabase(), stream.length);
+ } catch (IOException e) {
+ }
+ }
+
+ return null;
+ }
+}
|
d0441857cd6853975d83c612bbd2778b51007db8
|
elasticsearch
|
Fix typo in Hunspell logging--
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java b/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java
index f2ea0e37398fa..08e9ea9fa900c 100644
--- a/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java
+++ b/src/main/java/org/elasticsearch/indices/analysis/HunspellService.java
@@ -140,7 +140,7 @@ private void scanAndLoadDictionaries() {
*/
private Dictionary loadDictionary(String locale, Settings nodeSettings, Environment env) throws Exception {
if (logger.isDebugEnabled()) {
- logger.debug("Loading huspell dictionary [{}]...", locale);
+ logger.debug("Loading hunspell dictionary [{}]...", locale);
}
File dicDir = new File(hunspellDir, locale);
if (!dicDir.exists() || !dicDir.isDirectory()) {
|
d8ee4137885fa371259e75d3cbb2c1a55b1e0e90
|
restlet-framework-java
|
- Adjusted build.properties so that default values- work directly. - Refactored the usage of parameter lists by using a new- ParameterList (implementing List<Parameter>) and adding helper methods. -- Form now derives from ParameterList. - ConnectorCall.getRequestHeaders() and- getResponseHeaders() now return a ParameterList, other helper methods- removed. - Added urlEncode() on Parameter. - Reference now sets new scheme- names in lower case to respect normalization rules. - Added more unit tests- for the Resltet API; Contributed by Lars Heuer. - Fixed bug in Jetty 5 HTTPS- connector preventing the usage of the specified SSL keystore in certain- cases. Found by Dave Pawson. - Added constructors to DefaultServer using the- protocol's default port - Updated Jetty 6 to version beta 17. - Fixed type- in JdbcClient sample XML document. Reported by Thierry Boileau. - Added new- FileRepresentation constructor accepting a File instance. - Improved- ByteUtils.write() methods for streams by automatically buffering output- streams if necessary. - Templatized AbstractChainlet. Contributed by Lars- Heuer. - Fixed AbstractRestlet which was not reporting the proper error when- non standard Method instances were called but not handled. - Added FILE- protocol to Protocols enumeration. - Added- com.noelios.restlet.data.FileReference. - Added ReferenceList to handle- "text/uri-list" representations. - Renamed Resource.getVariantsMetadata() to- getVariants() for simplification purpose. - Added Resource.getIdentifier() :- Reference method. - Renamed com.noelios.restlet.impl.HttpServerCallImpl to- HttpServerCall. - Renamed "initParameters" into "properties" for Component- interface and related classes. - Refactored the methods allowing the- attachment of connectors in Component interface and related classes. -- Removed "name" property from Connector and Component interfaces and related- classes. - Added modifiable "properties" map to the Connector interface. -- Added FileClient implementing a client connector for the FILE protocol,- allowing standard access to local file systems. - Added- ServerCall.getRequestInput() method to factorize common logic among HTTP- server connectors. - Added ClientCall.getResponseOutput() method to- factorize common logic among HTTP and FILE connectors. - Moved- StringUtils.normalizePath() method to FileReference.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/main/org/restlet/Resource.java b/source/main/org/restlet/Resource.java
index d97a93a326..7ebcc19a69 100644
--- a/source/main/org/restlet/Resource.java
+++ b/source/main/org/restlet/Resource.java
@@ -24,6 +24,7 @@
import java.util.List;
+import org.restlet.data.Reference;
import org.restlet.data.Representation;
import org.restlet.data.RepresentationMetadata;
@@ -40,16 +41,22 @@
*/
public interface Resource
{
+ /**
+ * Returns the identifier reference.
+ * @return The identifier reference.
+ */
+ public Reference getIdentifier();
+
/**
* Returns the representation variants metadata.
* @return The representation variants metadata.
*/
- public List<RepresentationMetadata> getVariantsMetadata();
+ public List<RepresentationMetadata> getVariants();
/**
* Returns the representation matching the given metadata.
- * @param metadata The metadata to match.
+ * @param variant The variant metadata to match.
* @return The matching representation.
*/
- public Representation getRepresentation(RepresentationMetadata metadata);
+ public Representation getRepresentation(RepresentationMetadata variant);
}
diff --git a/source/main/org/restlet/connector/ClientCall.java b/source/main/org/restlet/connector/ClientCall.java
index 1c1c97e4ff..c637751063 100644
--- a/source/main/org/restlet/connector/ClientCall.java
+++ b/source/main/org/restlet/connector/ClientCall.java
@@ -58,23 +58,29 @@ public interface ClientCall extends ConnectorCall
* Returns the request entity channel if it exists.
* @return The request entity channel if it exists.
*/
- public WritableByteChannel getRequestChannel() throws IOException;
+ public WritableByteChannel getRequestChannel();
/**
* Returns the request entity stream if it exists.
* @return The request entity stream if it exists.
*/
- public OutputStream getRequestStream() throws IOException;
+ public OutputStream getRequestStream();
+
+ /**
+ * Returns the response output representation if available.
+ * @return The response output representation if available.
+ */
+ public Representation getResponseOutput();
/**
* Returns the response channel if it exists.
* @return The response channel if it exists.
*/
- public ReadableByteChannel getResponseChannel() throws IOException;
+ public ReadableByteChannel getResponseChannel();
/**
* Returns the response stream if it exists.
* @return The response stream if it exists.
*/
- public InputStream getResponseStream() throws IOException;
+ public InputStream getResponseStream();
}
diff --git a/source/main/org/restlet/connector/ServerCall.java b/source/main/org/restlet/connector/ServerCall.java
index e7d65bc373..7ae07af76a 100644
--- a/source/main/org/restlet/connector/ServerCall.java
+++ b/source/main/org/restlet/connector/ServerCall.java
@@ -54,7 +54,7 @@ public interface ServerCall extends ConnectorCall
* Sends the response headers.<br/>
* Must be called before sending the response output.
*/
- public void sendResponseHeaders();
+ public void sendResponseHeaders() throws IOException;
/**
* Sends the response output.
@@ -62,6 +62,12 @@ public interface ServerCall extends ConnectorCall
*/
public void sendResponseOutput(Representation output) throws IOException;
+ /**
+ * Returns the request input representation if available.
+ * @return The request input representation if available.
+ */
+ public Representation getRequestInput();
+
/**
* Returns the request entity channel if it exists.
* @return The request entity channel if it exists.
|
830df67181827218ed8525ac924b073cffe4536f
|
hbase
|
HADOOP-2398. Additional instrumentation for- NameNode and RPC server. Add support for accessing instrumentation statistics- via JMX. (Sanjay radia via dhruba)--git-svn-id: https://svn.apache.org/repos/asf/lucene/hadoop/trunk/src/contrib/hbase@611906 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java b/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java
index dd3f270fd4a0..6ddbd01215d8 100644
--- a/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java
+++ b/src/java/org/apache/hadoop/hbase/ipc/HbaseRPC.java
@@ -400,7 +400,7 @@ public Server(Object instance, Configuration conf, String bindAddress, int port
this.verbose = verbose;
}
- public Writable call(Writable param) throws IOException {
+ public Writable call(Writable param, long receiveTime) throws IOException {
try {
Invocation call = (Invocation)param;
if (verbose) log("Call: " + call);
|
d51eaf7a642b4b4572aa9628e66b760e5c3ee2d5
|
drools
|
JBRULES-1102 Bug in DefaultBetaConstraint class- indexing to never turn on -Fixed DefaultBetaConstraints -Added comprehensive- unit test--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@14396 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java
index 8a06d895ea6..5e1593a5228 100644
--- a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java
+++ b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java
@@ -72,7 +72,7 @@ public DefaultBetaConstraints(final BetaNodeFieldConstraint[] constraints,
// First create a LinkedList of constraints, with the indexed constraints first.
for ( int i = 0, length = constraints.length; i < length; i++ ) {
// Determine if this constraint is indexable
- if ( (!disableIndexing) && conf.isIndexLeftBetaMemory() && conf.isIndexRightBetaMemory() && isIndexable( constraints[i] ) && ( depth <= this.indexed ) ) {
+ if ( (!disableIndexing) && conf.isIndexLeftBetaMemory() && conf.isIndexRightBetaMemory() && isIndexable( constraints[i] ) && ( this.indexed < depth-1 ) ) {
if ( depth >= 1 && this.indexed == -1 ) {
// first index, so just add to the front
this.constraints.insertAfter( null,
@@ -189,7 +189,12 @@ public boolean isAllowedCachedRight(final ReteTuple tuple) {
}
public boolean isIndexed() {
- return this.indexed > 0;
+ // false if -1
+ return this.indexed >= 0;
+ }
+
+ public int getIndexCount() {
+ return this.indexed;
}
public boolean isEmpty() {
@@ -198,11 +203,11 @@ public boolean isEmpty() {
public BetaMemory createBetaMemory(RuleBaseConfiguration config) {
BetaMemory memory;
- if ( this.indexed > 0 ) {
+ if ( this.indexed >= 0 ) {
LinkedListEntry entry = (LinkedListEntry) this.constraints.getFirst();
final List list = new ArrayList();
- for ( int pos = 0; pos < this.indexed; pos++ ) {
+ for ( int pos = 0; pos <= this.indexed; pos++ ) {
final Constraint constraint = (Constraint) entry.getObject();
final VariableConstraint variableConstraint = (VariableConstraint) constraint;
final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(),
diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
index c50bffccc5d..353d6841b19 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
@@ -221,7 +221,7 @@ public synchronized StatefulSession newStatefulSession(final boolean keepReferen
throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" );
}
ReteooStatefulSession session = null;
-
+
synchronized ( this.pkgs ) {
ExecutorService executor = this.config.getExecutorService();
session = new ReteooStatefulSession( nextWorkingMemoryCounter(),
@@ -237,10 +237,10 @@ public synchronized StatefulSession newStatefulSession(final boolean keepReferen
final InitialFactHandle handle = new InitialFactHandle( session.getFactHandleFactory().newFactHandle( new InitialFactHandleDummyObject() ) );
session.queueWorkingMemoryAction( new WorkingMemoryReteAssertAction( handle,
- false,
- true,
- null,
- null ) );
+ false,
+ true,
+ null,
+ null ) );
}
return session;
}
diff --git a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java
index 53b19fb4cb0..a425e4175b7 100644
--- a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java
+++ b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java
@@ -434,7 +434,9 @@ public Evaluator getEvaluator() {
}
}
- public static interface Index {
+ public static interface Index {
+ public FieldIndex getFieldIndex(int index);
+
public int hashCodeOf(ReteTuple tuple);
public int hashCodeOf(Object object);
@@ -466,9 +468,16 @@ public SingleIndex(final FieldIndex[] indexes,
this.extractor = indexes[0].extractor;
this.declaration = indexes[0].declaration;
this.evaluator = indexes[0].evaluator;
-
}
+ public FieldIndex getFieldIndex(int index) {
+ if ( index > 0 ) {
+ throw new IllegalArgumentException("Index position " + index + " does not exist" );
+ }
+ return new FieldIndex(extractor, declaration, evaluator);
+ }
+
+
public int hashCodeOf(final Object object) {
int hashCode = this.startResult;
hashCode = TupleIndexHashTable.PRIME * hashCode + this.extractor.getHashCode( null, object );
@@ -534,7 +543,17 @@ public DoubleCompositeIndex(final FieldIndex[] indexes,
this.index0 = indexes[0];
this.index1 = indexes[1];
-
+ }
+
+ public FieldIndex getFieldIndex(int index) {
+ switch ( index ) {
+ case 0:
+ return index0;
+ case 1:
+ return index1;
+ default:
+ throw new IllegalArgumentException("Index position " + index + " does not exist" );
+ }
}
public int hashCodeOf(final Object object) {
@@ -622,8 +641,20 @@ public TripleCompositeIndex(final FieldIndex[] indexes,
this.index0 = indexes[0];
this.index1 = indexes[1];
this.index2 = indexes[2];
-
}
+
+ public FieldIndex getFieldIndex(int index) {
+ switch ( index ) {
+ case 0:
+ return index0;
+ case 1:
+ return index1;
+ case 2:
+ return index2;
+ default:
+ throw new IllegalArgumentException("Index position " + index + " does not exist" );
+ }
+ }
public int hashCodeOf(final Object object) {
int hashCode = this.startResult;
diff --git a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java
index a7d23b4bebe..f26f47938ee 100644
--- a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java
+++ b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java
@@ -77,6 +77,10 @@ public Iterator iterator(final ReteTuple tuple) {
public boolean isIndexed() {
return true;
}
+
+ public Index getIndex() {
+ return this.index;
+ }
public Entry getBucket(final Object object) {
final int hashCode = this.index.hashCodeOf( object );
diff --git a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java
index 44f8b092088..7971a8250d5 100644
--- a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java
+++ b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java
@@ -81,6 +81,10 @@ public Iterator iterator(final InternalFactHandle handle) {
public boolean isIndexed() {
return true;
}
+
+ public Index getIndex() {
+ return this.index;
+ }
public Entry getBucket(final Object object) {
final int hashCode = this.index.hashCodeOf( object );
diff --git a/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java b/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java
new file mode 100644
index 00000000000..f04181075ca
--- /dev/null
+++ b/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java
@@ -0,0 +1,249 @@
+package org.drools.common;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.drools.Cheese;
+import org.drools.Person;
+import org.drools.RuleBaseConfiguration;
+import org.drools.RuleBaseFactory;
+import org.drools.base.ClassFieldExtractor;
+import org.drools.base.ClassFieldExtractorCache;
+import org.drools.base.ClassObjectType;
+import org.drools.base.FieldFactory;
+import org.drools.base.ValueType;
+import org.drools.base.evaluators.Operator;
+import org.drools.base.evaluators.StringFactory;
+import org.drools.reteoo.BetaMemory;
+import org.drools.reteoo.ReteooRuleBase;
+import org.drools.rule.Declaration;
+import org.drools.rule.LiteralConstraint;
+import org.drools.rule.Pattern;
+import org.drools.rule.VariableConstraint;
+import org.drools.spi.BetaNodeFieldConstraint;
+import org.drools.spi.Evaluator;
+import org.drools.spi.FieldExtractor;
+import org.drools.spi.FieldValue;
+import org.drools.util.FactHandleIndexHashTable;
+import org.drools.util.FactHashTable;
+import org.drools.util.TupleHashTable;
+import org.drools.util.TupleIndexHashTable;
+import org.drools.util.AbstractHashTable.DoubleCompositeIndex;
+import org.drools.util.AbstractHashTable.FieldIndex;
+import org.drools.util.AbstractHashTable.Index;
+import org.drools.util.AbstractHashTable.SingleIndex;
+import org.drools.util.AbstractHashTable.TripleCompositeIndex;
+
+import junit.framework.TestCase;
+
+public class DefaultBetaConstraintsTest extends TestCase {
+
+ public void testNoIndexConstraints() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType0", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint5 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3,constraint5 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint6 = ( VariableConstraint ) getConstraint( "cheeseType6", Operator.NOT_EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5, constraint6 };
+ checkBetaConstraints( constraints );
+ }
+
+ public void testIndexedConstraint() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType0", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint5 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5 };
+ checkBetaConstraints( constraints );
+
+ VariableConstraint constraint6 = ( VariableConstraint ) getConstraint( "cheeseType6", Operator.EQUAL, "type", Cheese.class );
+ constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5, constraint6 };
+ checkBetaConstraints( constraints );
+ }
+
+
+ public void testSingleIndex() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+ checkBetaConstraints( constraints );
+ }
+
+ public void testSingleIndexNotFirst() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+
+ checkBetaConstraints( constraints );
+ }
+
+ public void testDoubleIndex() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+
+ checkBetaConstraints( constraints );
+ }
+
+ public void testDoubleIndexNotFirst() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+
+ checkBetaConstraints( constraints );
+ }
+
+
+ public void testTripleIndex() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+
+ checkBetaConstraints( constraints );
+ }
+
+ public void testTripleIndexNotFirst() {
+ VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class );
+ VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class );
+ VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class );
+
+ VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 };
+
+ checkBetaConstraints( constraints );
+ }
+
+ private BetaNodeFieldConstraint getConstraint(String identifier,
+ Operator operator,
+ String fieldName,
+ Class clazz) {
+ FieldExtractor extractor = ClassFieldExtractorCache.getExtractor( clazz,
+ fieldName,
+ getClass().getClassLoader() );
+ Declaration declaration = new Declaration( identifier,
+ extractor,
+ new Pattern( 0,
+ new ClassObjectType( clazz ) ) );
+ Evaluator evaluator = StringFactory.getInstance().getEvaluator( operator );
+ return new VariableConstraint( extractor,
+ declaration,
+ evaluator );
+ }
+
+
+ private void checkBetaConstraints(VariableConstraint[] constraints) {
+ RuleBaseConfiguration config = new RuleBaseConfiguration();
+ int depth = config.getCompositeKeyDepth();
+
+ List list = new ArrayList();
+
+ // get indexed positions
+ for ( int i = 0; i < constraints.length && list.size() < depth; i++ ) {
+ if ( constraints[i].getEvaluator().getOperator() == Operator.EQUAL ) {
+ list.add( new Integer(i) );
+ }
+ }
+
+ // convert to array
+ int[] indexedPositions = new int[ list.size() ];
+ for ( int i = 0; i < list.size(); i++ ) {
+ indexedPositions[i] = ( (Integer)list.get( i ) ).intValue();
+ }
+
+ DefaultBetaConstraints betaConstraints = new DefaultBetaConstraints(constraints, config );
+
+ assertEquals( ( indexedPositions.length > 0 ), betaConstraints.isIndexed() );
+ assertEquals(indexedPositions.length-1, betaConstraints.getIndexCount() );
+ BetaMemory betaMemory = betaConstraints.createBetaMemory( config );
+
+ // test tuple side
+ if ( indexedPositions.length > 0 ) {
+ TupleIndexHashTable tupleHashTable = ( TupleIndexHashTable ) betaMemory.getTupleMemory();
+ assertTrue( tupleHashTable.isIndexed() );
+ Index index = tupleHashTable.getIndex();
+
+ for ( int i = 0; i < indexedPositions.length; i++ ) {
+ checkSameConstraintForIndex( constraints[indexedPositions[i]], index.getFieldIndex(i) );
+ }
+
+ FactHandleIndexHashTable factHashTable = ( FactHandleIndexHashTable ) betaMemory.getFactHandleMemory();
+ assertTrue( factHashTable.isIndexed() );
+ index = factHashTable.getIndex();
+
+ for ( int i = 0; i < indexedPositions.length; i++ ) {
+ checkSameConstraintForIndex( constraints[indexedPositions[i]], index.getFieldIndex(i) );
+ }
+ } else {
+ TupleHashTable tupleHashTable = ( TupleHashTable ) betaMemory.getTupleMemory();
+ assertFalse( tupleHashTable.isIndexed() );
+
+ FactHashTable factHashTable = ( FactHashTable ) betaMemory.getFactHandleMemory();
+ assertFalse( factHashTable.isIndexed() );
+ }
+ }
+
+
+ private void checkSameConstraintForIndex(VariableConstraint constraint, FieldIndex fieldIndex) {
+ assertSame( constraint.getRequiredDeclarations()[0], fieldIndex.getDeclaration() );
+ assertSame( constraint.getEvaluator(), fieldIndex.getEvaluator() );
+ assertSame( constraint.getFieldExtractor(), fieldIndex.getExtractor() );
+ }
+}
|
e3f99578304cb30f1b59c34a4193b9b700f3566a
|
hbase
|
HBASE-12176 WALCellCodec Encoders support for- non-KeyValue Cells (Anoop Sam John)--
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
index 504e9cbb00af..46f3b88fb2cd 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SecureWALCellCodec.java
@@ -30,6 +30,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.KeyValueCodec;
import org.apache.hadoop.hbase.io.crypto.Decryptor;
import org.apache.hadoop.hbase.io.crypto.Encryption;
@@ -179,16 +180,11 @@ public EncryptedKvEncoder(OutputStream os, Encryptor encryptor) {
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
if (encryptor == null) {
super.write(cell);
return;
}
- KeyValue kv = (KeyValue)cell;
- byte[] kvBuffer = kv.getBuffer();
- int offset = kv.getOffset();
-
byte[] iv = nextIv();
encryptor.setIv(iv);
encryptor.reset();
@@ -205,23 +201,27 @@ public void write(Cell cell) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream cout = encryptor.createEncryptionStream(baos);
+ int tlen = cell.getTagsLength();
// Write the KeyValue infrastructure as VInts.
- StreamUtils.writeRawVInt32(cout, kv.getKeyLength());
- StreamUtils.writeRawVInt32(cout, kv.getValueLength());
+ StreamUtils.writeRawVInt32(cout, KeyValueUtil.keyLength(cell));
+ StreamUtils.writeRawVInt32(cout, cell.getValueLength());
// To support tags
- StreamUtils.writeRawVInt32(cout, kv.getTagsLength());
+ StreamUtils.writeRawVInt32(cout, tlen);
// Write row, qualifier, and family
- StreamUtils.writeRawVInt32(cout, kv.getRowLength());
- cout.write(kvBuffer, kv.getRowOffset(), kv.getRowLength());
- StreamUtils.writeRawVInt32(cout, kv.getFamilyLength());
- cout.write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength());
- StreamUtils.writeRawVInt32(cout, kv.getQualifierLength());
- cout.write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength());
- // Write the rest
- int pos = kv.getTimestampOffset();
- int remainingLength = kv.getLength() + offset - pos;
- cout.write(kvBuffer, pos, remainingLength);
+ StreamUtils.writeRawVInt32(cout, cell.getRowLength());
+ cout.write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
+ StreamUtils.writeRawVInt32(cout, cell.getFamilyLength());
+ cout.write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
+ StreamUtils.writeRawVInt32(cout, cell.getQualifierLength());
+ cout.write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
+ // Write the rest ie. ts, type, value and tags parts
+ StreamUtils.writeLong(cout, cell.getTimestamp());
+ cout.write(cell.getTypeByte());
+ cout.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
+ if (tlen > 0) {
+ cout.write(cell.getTagsArray(), cell.getTagsOffset(), tlen);
+ }
cout.close();
StreamUtils.writeRawVInt32(out, baos.size());
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
index ae8613127f5a..89f4b869fc10 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
@@ -27,6 +27,7 @@
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.BaseDecoder;
import org.apache.hadoop.hbase.codec.BaseEncoder;
import org.apache.hadoop.hbase.codec.Codec;
@@ -190,41 +191,34 @@ public CompressedKvEncoder(OutputStream out, CompressionContext compression) {
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
- KeyValue kv = (KeyValue)cell;
- byte[] kvBuffer = kv.getBuffer();
- int offset = kv.getOffset();
-
// We first write the KeyValue infrastructure as VInts.
- StreamUtils.writeRawVInt32(out, kv.getKeyLength());
- StreamUtils.writeRawVInt32(out, kv.getValueLength());
+ StreamUtils.writeRawVInt32(out, KeyValueUtil.keyLength(cell));
+ StreamUtils.writeRawVInt32(out, cell.getValueLength());
// To support tags
- int tagsLength = kv.getTagsLength();
+ int tagsLength = cell.getTagsLength();
StreamUtils.writeRawVInt32(out, tagsLength);
// Write row, qualifier, and family; use dictionary
// compression as they're likely to have duplicates.
- write(kvBuffer, kv.getRowOffset(), kv.getRowLength(), compression.rowDict);
- write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength(), compression.familyDict);
- write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength(), compression.qualifierDict);
+ write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), compression.rowDict);
+ write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
+ compression.familyDict);
+ write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(),
+ compression.qualifierDict);
// Write timestamp, type and value as uncompressed.
- int pos = kv.getTimestampOffset();
- int tsTypeValLen = kv.getLength() + offset - pos;
- if (tagsLength > 0) {
- tsTypeValLen = tsTypeValLen - tagsLength - KeyValue.TAGS_LENGTH_SIZE;
- }
- assert tsTypeValLen > 0;
- out.write(kvBuffer, pos, tsTypeValLen);
+ StreamUtils.writeLong(out, cell.getTimestamp());
+ out.write(cell.getTypeByte());
+ out.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
if (tagsLength > 0) {
if (compression.tagCompressionContext != null) {
// Write tags using Dictionary compression
- compression.tagCompressionContext.compressTags(out, kvBuffer, kv.getTagsOffset(),
- tagsLength);
+ compression.tagCompressionContext.compressTags(out, cell.getTagsArray(),
+ cell.getTagsOffset(), tagsLength);
} else {
// Tag compression is disabled within the WAL compression. Just write the tags bytes as
// it is.
- out.write(kvBuffer, kv.getTagsOffset(), tagsLength);
+ out.write(cell.getTagsArray(), cell.getTagsOffset(), tagsLength);
}
}
}
@@ -340,10 +334,9 @@ public EnsureKvEncoder(OutputStream out) {
}
@Override
public void write(Cell cell) throws IOException {
- if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
checkFlushed();
// Make sure to write tags into WAL
- KeyValue.oswrite((KeyValue) cell, this.out, true);
+ KeyValueUtil.oswrite(cell, this.out, true);
}
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
index 350f8ab50b30..df4fb72e1899 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
@@ -22,7 +22,7 @@
import java.util.Map;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
-import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.util.Bytes;
@@ -140,9 +140,10 @@ String toFamilyString() {
String qualifier;
if (o instanceof byte[]) {
qualifier = Bytes.toString((byte[])o);
- } else if (o instanceof KeyValue) {
- byte[] rawQualifier = ((KeyValue)o).getQualifier();
- qualifier = Bytes.toString(rawQualifier);
+ } else if (o instanceof Cell) {
+ Cell c = (Cell) o;
+ qualifier = Bytes.toString(c.getQualifierArray(), c.getQualifierOffset(),
+ c.getQualifierLength());
} else {
// Shouldn't really reach this?
qualifier = o.toString();
|
a4873a43416cb322957863fd3c34795a3808f7ac
|
hadoop
|
HDFS-3167. CLI-based driver for MiniDFSCluster.- Contributed by Henry Robinson.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1308160 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 62e45162a1ec0..c85adc18b1e01 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -68,6 +68,8 @@ Release 2.0.0 - UNRELEASED
DistributedFileSystem to @InterfaceAudience.LimitedPrivate.
(harsh via szetszwo)
+ HDFS-3167. CLI-based driver for MiniDFSCluster. (Henry Robinson via atm)
+
IMPROVEMENTS
HDFS-2018. Move all journal stream management code into one place.
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java
index 709a5012bfb2b..cdcf618c80dd5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/HdfsTestDriver.java
@@ -36,7 +36,9 @@ public HdfsTestDriver(ProgramDriver pgd) {
this.pgd = pgd;
try {
pgd.addClass("dfsthroughput", BenchmarkThroughput.class,
- "measure hdfs throughput");
+ "measure hdfs throughput");
+ pgd.addClass("minidfscluster", MiniDFSClusterManager.class,
+ "Run a single-process mini DFS cluster");
} catch(Throwable e) {
e.printStackTrace();
}
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java
new file mode 100644
index 0000000000000..4622b4cd5c53c
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/test/MiniDFSClusterManager.java
@@ -0,0 +1,259 @@
+/**
+ * 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.test;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hdfs.HdfsConfiguration;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
+import org.mortbay.util.ajax.JSON;
+
+/**
+ * This class drives the creation of a mini-cluster on the local machine. By
+ * default, a MiniDFSCluster is spawned on the first available ports that are
+ * found.
+ *
+ * A series of command line flags controls the startup cluster options.
+ *
+ * This class can dump a Hadoop configuration and some basic metadata (in JSON)
+ * into a textfile.
+ *
+ * To shutdown the cluster, kill the process.
+ *
+ * To run this from the command line, do the following (replacing the jar
+ * version as appropriate):
+ *
+ * $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/share/hadoop/hdfs/hadoop-hdfs-0.24.0-SNAPSHOT-tests.jar org.apache.hadoop.test.MiniDFSClusterManager -options...
+ */
+public class MiniDFSClusterManager {
+ private static final Log LOG =
+ LogFactory.getLog(MiniDFSClusterManager.class);
+
+ private MiniDFSCluster dfs;
+ private String writeDetails;
+ private int numDataNodes;
+ private int nameNodePort;
+ private StartupOption dfsOpts;
+ private String writeConfig;
+ private Configuration conf;
+
+ private static final long SLEEP_INTERVAL_MS = 1000 * 60;
+
+ /**
+ * Creates configuration options object.
+ */
+ @SuppressWarnings("static-access")
+ private Options makeOptions() {
+ Options options = new Options();
+ options
+ .addOption("datanodes", true, "How many datanodes to start (default 1)")
+ .addOption("format", false, "Format the DFS (default false)")
+ .addOption("cmdport", true,
+ "Which port to listen on for commands (default 0--we choose)")
+ .addOption("nnport", true, "NameNode port (default 0--we choose)")
+ .addOption("namenode", true, "URL of the namenode (default "
+ + "is either the DFS cluster or a temporary dir)")
+ .addOption(OptionBuilder
+ .hasArgs()
+ .withArgName("property=value")
+ .withDescription("Options to pass into configuration object")
+ .create("D"))
+ .addOption(OptionBuilder
+ .hasArg()
+ .withArgName("path")
+ .withDescription("Save configuration to this XML file.")
+ .create("writeConfig"))
+ .addOption(OptionBuilder
+ .hasArg()
+ .withArgName("path")
+ .withDescription("Write basic information to this JSON file.")
+ .create("writeDetails"))
+ .addOption(OptionBuilder.withDescription("Prints option help.")
+ .create("help"));
+ return options;
+ }
+
+ /**
+ * Main entry-point.
+ */
+ public void run(String[] args) throws IOException {
+ if (!parseArguments(args)) {
+ return;
+ }
+ start();
+ sleepForever();
+ }
+
+ private void sleepForever() {
+ while (true) {
+ try {
+ Thread.sleep(SLEEP_INTERVAL_MS);
+ if (!dfs.isClusterUp()) {
+ LOG.info("Cluster is no longer up, exiting");
+ return;
+ }
+ } catch (InterruptedException _) {
+ // nothing
+ }
+ }
+ }
+
+ /**
+ * Starts DFS as specified in member-variable options. Also writes out
+ * configuration and details, if requested.
+ */
+ public void start() throws IOException, FileNotFoundException {
+ dfs = new MiniDFSCluster.Builder(conf).nameNodePort(nameNodePort)
+ .numDataNodes(numDataNodes)
+ .startupOption(dfsOpts)
+ .build();
+ dfs.waitActive();
+
+ LOG.info("Started MiniDFSCluster -- namenode on port "
+ + dfs.getNameNodePort());
+
+ if (writeConfig != null) {
+ FileOutputStream fos = new FileOutputStream(new File(writeConfig));
+ conf.writeXml(fos);
+ fos.close();
+ }
+
+ if (writeDetails != null) {
+ Map<String, Object> map = new TreeMap<String, Object>();
+ if (dfs != null) {
+ map.put("namenode_port", dfs.getNameNodePort());
+ }
+
+ FileWriter fw = new FileWriter(new File(writeDetails));
+ fw.write(new JSON().toJSON(map));
+ fw.close();
+ }
+ }
+
+ /**
+ * Parses arguments and fills out the member variables.
+ * @param args Command-line arguments.
+ * @return true on successful parse; false to indicate that the
+ * program should exit.
+ */
+ private boolean parseArguments(String[] args) {
+ Options options = makeOptions();
+ CommandLine cli;
+ try {
+ CommandLineParser parser = new GnuParser();
+ cli = parser.parse(options, args);
+ } catch(ParseException e) {
+ LOG.warn("options parsing failed: "+e.getMessage());
+ new HelpFormatter().printHelp("...", options);
+ return false;
+ }
+
+ if (cli.hasOption("help")) {
+ new HelpFormatter().printHelp("...", options);
+ return false;
+ }
+
+ if (cli.getArgs().length > 0) {
+ for (String arg : cli.getArgs()) {
+ LOG.error("Unrecognized option: " + arg);
+ new HelpFormatter().printHelp("...", options);
+ return false;
+ }
+ }
+
+ // HDFS
+ numDataNodes = intArgument(cli, "datanodes", 1);
+ nameNodePort = intArgument(cli, "nnport", 0);
+ dfsOpts = cli.hasOption("format") ?
+ StartupOption.FORMAT : StartupOption.REGULAR;
+
+ // Runner
+ writeDetails = cli.getOptionValue("writeDetails");
+ writeConfig = cli.getOptionValue("writeConfig");
+
+ // General
+ conf = new HdfsConfiguration();
+ updateConfiguration(conf, cli.getOptionValues("D"));
+
+ return true;
+ }
+
+ /**
+ * Updates configuration based on what's given on the command line.
+ *
+ * @param conf2 The configuration object
+ * @param keyvalues An array of interleaved key value pairs.
+ */
+ private void updateConfiguration(Configuration conf2, String[] keyvalues) {
+ int num_confs_updated = 0;
+ if (keyvalues != null) {
+ for (String prop : keyvalues) {
+ String[] keyval = prop.split("=", 2);
+ if (keyval.length == 2) {
+ conf2.set(keyval[0], keyval[1]);
+ num_confs_updated++;
+ } else {
+ LOG.warn("Ignoring -D option " + prop);
+ }
+ }
+ }
+ LOG.info("Updated " + num_confs_updated +
+ " configuration settings from command line.");
+ }
+
+ /**
+ * Extracts an integer argument with specified default value.
+ */
+ private int intArgument(CommandLine cli, String argName, int defaultValue) {
+ String o = cli.getOptionValue(argName);
+ try {
+ if (o != null) {
+ return Integer.parseInt(o);
+ }
+ } catch (NumberFormatException ex) {
+ LOG.error("Couldn't parse value (" + o + ") for option "
+ + argName + ". Using default: " + defaultValue);
+ }
+
+ return defaultValue;
+ }
+
+ /**
+ * Starts a MiniDFSClusterManager with parameters drawn from the command line.
+ */
+ public static void main(String[] args) throws IOException {
+ new MiniDFSClusterManager().run(args);
+ }
+}
|
01ff1c8a77ed63405af637be35318ee693dcd1c5
|
restlet-framework-java
|
- Deprecated ServletConverter and added an- equivalent ServletAdapter class to prevent confusion with the - ConverterService reintroduced in Restlet 1.2. - Added root Helper class.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt
index 1a4dc4b5ff..3bdf989f0d 100644
--- a/build/tmpl/text/changes.txt
+++ b/build/tmpl/text/changes.txt
@@ -5,7 +5,9 @@ Changes log
- @version-full@ (@release-date@)
- Breaking changes
- -
+ - Deprecated ServletConverter and added an equivalent
+ ServletAdapter class to prevent confusion with the
+ ConverterService reintroduced in Restlet 1.2.
- Bugs fixed
- Fixed bug with a ServerResource when an annotated method does
not return a value.
diff --git a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java
index 4a32217c8d..6accbacefd 100644
--- a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java
+++ b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java
@@ -78,8 +78,8 @@
import org.restlet.data.Response;
import org.restlet.engine.http.ContentType;
import org.restlet.engine.http.HttpClientCall;
-import org.restlet.engine.http.HttpClientConverter;
-import org.restlet.engine.http.HttpServerConverter;
+import org.restlet.engine.http.HttpClientAdapter;
+import org.restlet.engine.http.HttpServerAdapter;
import org.restlet.engine.http.HttpUtils;
import org.restlet.engine.util.DateUtils;
import org.restlet.ext.jaxrs.internal.core.UnmodifiableMultivaluedMap;
@@ -306,7 +306,7 @@ public static void copyResponseHeaders(
restletResponse.setEntity(new EmptyRepresentation());
}
- HttpClientConverter.copyResponseTransportHeaders(headers,
+ HttpClientAdapter.copyResponseTransportHeaders(headers,
restletResponse);
HttpClientCall.copyResponseEntityHeaders(headers, restletResponse
.getEntity());
@@ -324,8 +324,8 @@ public static void copyResponseHeaders(
*/
public static Series<Parameter> copyResponseHeaders(Response restletResponse) {
final Series<Parameter> headers = new Form();
- HttpServerConverter.addResponseHeaders(restletResponse, headers);
- HttpServerConverter.addEntityHeaders(restletResponse.getEntity(),
+ HttpServerAdapter.addResponseHeaders(restletResponse, headers);
+ HttpServerAdapter.addEntityHeaders(restletResponse.getEntity(),
headers);
return headers;
}
diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java
new file mode 100644
index 0000000000..48ac006096
--- /dev/null
+++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java
@@ -0,0 +1,243 @@
+/**
+ * Copyright 2005-2009 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
+package org.restlet.ext.servlet;
+
+import java.io.IOException;
+import java.util.Enumeration;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.restlet.Context;
+import org.restlet.Restlet;
+import org.restlet.data.Reference;
+import org.restlet.engine.http.HttpRequest;
+import org.restlet.engine.http.HttpResponse;
+import org.restlet.engine.http.HttpServerAdapter;
+import org.restlet.ext.servlet.internal.ServletCall;
+import org.restlet.ext.servlet.internal.ServletLogger;
+
+/**
+ * HTTP adapter from Servlet calls to Restlet calls. This class can be used in
+ * any Servlet, just create a new instance and override the service() method in
+ * your Servlet to delegate all those calls to this class's service() method.
+ * Remember to set the target Restlet, for example using a Restlet Router
+ * instance. You can get the Restlet context directly on instances of this
+ * class, it will be based on the parent Servlet's context for logging purpose.<br>
+ * <br>
+ * This class is especially useful when directly integrating Restlets with
+ * Spring managed Web applications. Here is a simple usage example:
+ *
+ * <pre>
+ * public class TestServlet extends HttpServlet {
+ * private ServletAdapter adapter;
+ *
+ * public void init() throws ServletException {
+ * super.init();
+ * this.adapter = new ServletAdapter(getServletContext());
+ *
+ * Restlet trace = new Restlet(this.adapter.getContext()) {
+ * public void handle(Request req, Response res) {
+ * getLogger().info("Hello World");
+ * res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
+ * }
+ * };
+ *
+ * this.adapter.setTarget(trace);
+ * }
+ *
+ * protected void service(HttpServletRequest req, HttpServletResponse res)
+ * throws ServletException, IOException {
+ * this.adapter.service(req, res);
+ * }
+ * }
+ * </pre>
+ *
+ * @author Jerome Louvel
+ */
+public class ServletAdapter extends HttpServerAdapter {
+ /** The target Restlet. */
+ private volatile Restlet target;
+
+ /**
+ * Constructor. Remember to manually set the "target" property before
+ * invoking the service() method.
+ *
+ * @param context
+ * The Servlet context.
+ */
+ public ServletAdapter(ServletContext context) {
+ this(context, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param context
+ * The Servlet context.
+ * @param target
+ * The target Restlet.
+ */
+ public ServletAdapter(ServletContext context, Restlet target) {
+ super(new Context(new ServletLogger(context)));
+ this.target = target;
+ }
+
+ /**
+ * Returns the base reference of new Restlet requests.
+ *
+ * @param request
+ * The Servlet request.
+ * @return The base reference of new Restlet requests.
+ */
+ public Reference getBaseRef(HttpServletRequest request) {
+ Reference result = null;
+ final String basePath = request.getContextPath()
+ + request.getServletPath();
+ final String baseUri = request.getRequestURL().toString();
+ // Path starts at first slash after scheme://
+ final int pathStart = baseUri.indexOf("/",
+ request.getScheme().length() + 3);
+ if (basePath.length() == 0) {
+ // basePath is empty in case the webapp is mounted on root context
+ if (pathStart != -1) {
+ result = new Reference(baseUri.substring(0, pathStart));
+ } else {
+ result = new Reference(baseUri);
+ }
+ } else {
+ if (pathStart != -1) {
+ final int baseIndex = baseUri.indexOf(basePath, pathStart);
+ if (baseIndex != -1) {
+ result = new Reference(baseUri.substring(0, baseIndex
+ + basePath.length()));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the root reference of new Restlet requests. By default it returns
+ * the result of getBaseRef().
+ *
+ * @param request
+ * The Servlet request.
+ * @return The root reference of new Restlet requests.
+ */
+ public Reference getRootRef(HttpServletRequest request) {
+ return getBaseRef(request);
+ }
+
+ /**
+ * Returns the target Restlet.
+ *
+ * @return The target Restlet.
+ */
+ public Restlet getTarget() {
+ return this.target;
+ }
+
+ /**
+ * Services a HTTP Servlet request as a Restlet request handled by the
+ * "target" Restlet.
+ *
+ * @param request
+ * The HTTP Servlet request.
+ * @param response
+ * The HTTP Servlet response.
+ */
+ public void service(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ if (getTarget() != null) {
+ // Set the current context
+ Context.setCurrent(getContext());
+
+ // Convert the Servlet call to a Restlet call
+ final ServletCall servletCall = new ServletCall(request
+ .getLocalAddr(), request.getLocalPort(), request, response);
+ final HttpRequest httpRequest = toRequest(servletCall);
+ final HttpResponse httpResponse = new HttpResponse(servletCall,
+ httpRequest);
+
+ // Adjust the relative reference
+ httpRequest.getResourceRef().setBaseRef(getBaseRef(request));
+
+ // Adjust the root reference
+ httpRequest.setRootRef(getRootRef(request));
+
+ // Handle the request and commit the response
+ getTarget().handle(httpRequest, httpResponse);
+ commit(httpResponse);
+ } else {
+ getLogger().warning("Unable to find the Restlet target");
+ }
+ }
+
+ /**
+ * Sets the target Restlet.
+ *
+ * @param target
+ * The target Restlet.
+ */
+ public void setTarget(Restlet target) {
+ this.target = target;
+ }
+
+ /**
+ * Converts a low-level Servlet call into a high-level Restlet request. In
+ * addition to the parent {@link HttpServerAdapter}, it also copies the
+ * Servlet's request attributes into the Restlet's request attributes map.
+ *
+ * @param servletCall
+ * The low-level Servlet call.
+ * @return A new high-level uniform request.
+ */
+ @SuppressWarnings("unchecked")
+ public HttpRequest toRequest(ServletCall servletCall) {
+ final HttpRequest result = super.toRequest(servletCall);
+
+ // Copy all Servlet's request attributes
+ String attributeName;
+ for (final Enumeration<String> namesEnum = servletCall.getRequest()
+ .getAttributeNames(); namesEnum.hasMoreElements();) {
+ attributeName = namesEnum.nextElement();
+ result.getAttributes().put(attributeName,
+ servletCall.getRequest().getAttribute(attributeName));
+ }
+
+ return result;
+ }
+
+}
diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java
index 407e52a214..cf5c0a7918 100644
--- a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java
+++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java
@@ -43,7 +43,7 @@
import org.restlet.data.Reference;
import org.restlet.engine.http.HttpRequest;
import org.restlet.engine.http.HttpResponse;
-import org.restlet.engine.http.HttpServerConverter;
+import org.restlet.engine.http.HttpServerAdapter;
import org.restlet.ext.servlet.internal.ServletCall;
import org.restlet.ext.servlet.internal.ServletLogger;
@@ -60,184 +60,186 @@
*
* <pre>
* public class TestServlet extends HttpServlet {
- * private ServletConverter converter;
+ * private ServletConverter converter;
*
- * public void init() throws ServletException {
- * super.init();
- * this.converter = new ServletConverter(getServletContext());
+ * public void init() throws ServletException {
+ * super.init();
+ * this.converter = new ServletConverter(getServletContext());
*
- * Restlet trace = new Restlet(this.converter.getContext()) {
- * public void handle(Request req, Response res) {
- * getLogger().info("Hello World");
- * res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
- * }
- * };
+ * Restlet trace = new Restlet(this.converter.getContext()) {
+ * public void handle(Request req, Response res) {
+ * getLogger().info("Hello World");
+ * res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
+ * }
+ * };
*
- * this.converter.setTarget(trace);
- * }
+ * this.converter.setTarget(trace);
+ * }
*
- * protected void service(HttpServletRequest req, HttpServletResponse res)
- * throws ServletException, IOException {
- * this.converter.service(req, res);
- * }
+ * protected void service(HttpServletRequest req, HttpServletResponse res)
+ * throws ServletException, IOException {
+ * this.converter.service(req, res);
+ * }
* }
* </pre>
*
* @author Jerome Louvel
+ * @deprecated Use {@link ServletAdapter} instead.
*/
-public class ServletConverter extends HttpServerConverter {
- /** The target Restlet. */
- private volatile Restlet target;
-
- /**
- * Constructor. Remember to manually set the "target" property before
- * invoking the service() method.
- *
- * @param context
- * The Servlet context.
- */
- public ServletConverter(ServletContext context) {
- this(context, null);
- }
-
- /**
- * Constructor.
- *
- * @param context
- * The Servlet context.
- * @param target
- * The target Restlet.
- */
- public ServletConverter(ServletContext context, Restlet target) {
- super(new Context(new ServletLogger(context)));
- this.target = target;
- }
-
- /**
- * Returns the base reference of new Restlet requests.
- *
- * @param request
- * The Servlet request.
- * @return The base reference of new Restlet requests.
- */
- public Reference getBaseRef(HttpServletRequest request) {
- Reference result = null;
- final String basePath = request.getContextPath()
- + request.getServletPath();
- final String baseUri = request.getRequestURL().toString();
- // Path starts at first slash after scheme://
- final int pathStart = baseUri.indexOf("/",
- request.getScheme().length() + 3);
- if (basePath.length() == 0) {
- // basePath is empty in case the webapp is mounted on root context
- if (pathStart != -1) {
- result = new Reference(baseUri.substring(0, pathStart));
- } else {
- result = new Reference(baseUri);
- }
- } else {
- if (pathStart != -1) {
- final int baseIndex = baseUri.indexOf(basePath, pathStart);
- if (baseIndex != -1) {
- result = new Reference(baseUri.substring(0, baseIndex
- + basePath.length()));
- }
- }
- }
-
- return result;
- }
-
- /**
- * Returns the root reference of new Restlet requests. By default it returns
- * the result of getBaseRef().
- *
- * @param request
- * The Servlet request.
- * @return The root reference of new Restlet requests.
- */
- public Reference getRootRef(HttpServletRequest request) {
- return getBaseRef(request);
- }
-
- /**
- * Returns the target Restlet.
- *
- * @return The target Restlet.
- */
- public Restlet getTarget() {
- return this.target;
- }
-
- /**
- * Services a HTTP Servlet request as a Restlet request handled by the
- * "target" Restlet.
- *
- * @param request
- * The HTTP Servlet request.
- * @param response
- * The HTTP Servlet response.
- */
- public void service(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- if (getTarget() != null) {
- // Set the current context
- Context.setCurrent(getContext());
-
- // Convert the Servlet call to a Restlet call
- final ServletCall servletCall = new ServletCall(request
- .getLocalAddr(), request.getLocalPort(), request, response);
- final HttpRequest httpRequest = toRequest(servletCall);
- final HttpResponse httpResponse = new HttpResponse(servletCall,
- httpRequest);
-
- // Adjust the relative reference
- httpRequest.getResourceRef().setBaseRef(getBaseRef(request));
-
- // Adjust the root reference
- httpRequest.setRootRef(getRootRef(request));
-
- // Handle the request and commit the response
- getTarget().handle(httpRequest, httpResponse);
- commit(httpResponse);
- } else {
- getLogger().warning("Unable to find the Restlet target");
- }
- }
-
- /**
- * Sets the target Restlet.
- *
- * @param target
- * The target Restlet.
- */
- public void setTarget(Restlet target) {
- this.target = target;
- }
-
- /**
- * Converts a low-level Servlet call into a high-level Restlet request. In
- * addition to the parent HttpServerConverter class, it also copies the
- * Servlet's request attributes into the Restlet's request attributes map.
- *
- * @param servletCall
- * The low-level Servlet call.
- * @return A new high-level uniform request.
- */
- @SuppressWarnings("unchecked")
- public HttpRequest toRequest(ServletCall servletCall) {
- final HttpRequest result = super.toRequest(servletCall);
-
- // Copy all Servlet's request attributes
- String attributeName;
- for (final Enumeration<String> namesEnum = servletCall.getRequest()
- .getAttributeNames(); namesEnum.hasMoreElements();) {
- attributeName = namesEnum.nextElement();
- result.getAttributes().put(attributeName,
- servletCall.getRequest().getAttribute(attributeName));
- }
-
- return result;
- }
+@Deprecated
+public class ServletConverter extends HttpServerAdapter {
+ /** The target Restlet. */
+ private volatile Restlet target;
+
+ /**
+ * Constructor. Remember to manually set the "target" property before
+ * invoking the service() method.
+ *
+ * @param context
+ * The Servlet context.
+ */
+ public ServletConverter(ServletContext context) {
+ this(context, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param context
+ * The Servlet context.
+ * @param target
+ * The target Restlet.
+ */
+ public ServletConverter(ServletContext context, Restlet target) {
+ super(new Context(new ServletLogger(context)));
+ this.target = target;
+ }
+
+ /**
+ * Returns the base reference of new Restlet requests.
+ *
+ * @param request
+ * The Servlet request.
+ * @return The base reference of new Restlet requests.
+ */
+ public Reference getBaseRef(HttpServletRequest request) {
+ Reference result = null;
+ final String basePath = request.getContextPath()
+ + request.getServletPath();
+ final String baseUri = request.getRequestURL().toString();
+ // Path starts at first slash after scheme://
+ final int pathStart = baseUri.indexOf("/",
+ request.getScheme().length() + 3);
+ if (basePath.length() == 0) {
+ // basePath is empty in case the webapp is mounted on root context
+ if (pathStart != -1) {
+ result = new Reference(baseUri.substring(0, pathStart));
+ } else {
+ result = new Reference(baseUri);
+ }
+ } else {
+ if (pathStart != -1) {
+ final int baseIndex = baseUri.indexOf(basePath, pathStart);
+ if (baseIndex != -1) {
+ result = new Reference(baseUri.substring(0, baseIndex
+ + basePath.length()));
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the root reference of new Restlet requests. By default it returns
+ * the result of getBaseRef().
+ *
+ * @param request
+ * The Servlet request.
+ * @return The root reference of new Restlet requests.
+ */
+ public Reference getRootRef(HttpServletRequest request) {
+ return getBaseRef(request);
+ }
+
+ /**
+ * Returns the target Restlet.
+ *
+ * @return The target Restlet.
+ */
+ public Restlet getTarget() {
+ return this.target;
+ }
+
+ /**
+ * Services a HTTP Servlet request as a Restlet request handled by the
+ * "target" Restlet.
+ *
+ * @param request
+ * The HTTP Servlet request.
+ * @param response
+ * The HTTP Servlet response.
+ */
+ public void service(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+ if (getTarget() != null) {
+ // Set the current context
+ Context.setCurrent(getContext());
+
+ // Convert the Servlet call to a Restlet call
+ final ServletCall servletCall = new ServletCall(request
+ .getLocalAddr(), request.getLocalPort(), request, response);
+ final HttpRequest httpRequest = toRequest(servletCall);
+ final HttpResponse httpResponse = new HttpResponse(servletCall,
+ httpRequest);
+
+ // Adjust the relative reference
+ httpRequest.getResourceRef().setBaseRef(getBaseRef(request));
+
+ // Adjust the root reference
+ httpRequest.setRootRef(getRootRef(request));
+
+ // Handle the request and commit the response
+ getTarget().handle(httpRequest, httpResponse);
+ commit(httpResponse);
+ } else {
+ getLogger().warning("Unable to find the Restlet target");
+ }
+ }
+
+ /**
+ * Sets the target Restlet.
+ *
+ * @param target
+ * The target Restlet.
+ */
+ public void setTarget(Restlet target) {
+ this.target = target;
+ }
+
+ /**
+ * Converts a low-level Servlet call into a high-level Restlet request. In
+ * addition to the parent HttpServerConverter class, it also copies the
+ * Servlet's request attributes into the Restlet's request attributes map.
+ *
+ * @param servletCall
+ * The low-level Servlet call.
+ * @return A new high-level uniform request.
+ */
+ @SuppressWarnings("unchecked")
+ public HttpRequest toRequest(ServletCall servletCall) {
+ final HttpRequest result = super.toRequest(servletCall);
+
+ // Copy all Servlet's request attributes
+ String attributeName;
+ for (final Enumeration<String> namesEnum = servletCall.getRequest()
+ .getAttributeNames(); namesEnum.hasMoreElements();) {
+ attributeName = namesEnum.nextElement();
+ result.getAttributes().put(attributeName,
+ servletCall.getRequest().getAttribute(attributeName));
+ }
+
+ return result;
+ }
}
diff --git a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java
index c5647a2625..12824a3b0d 100644
--- a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java
+++ b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java
@@ -39,11 +39,10 @@
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
-import org.restlet.ext.servlet.ServletConverter;
+import org.restlet.ext.servlet.ServletAdapter;
import org.springframework.beans.BeansException;
import org.springframework.web.servlet.FrameworkServlet;
-
/**
* A Servlet which provides an automatic Restlet integration with an existing
* {@link org.springframework.web.context.WebApplicationContext}. The usage is
@@ -97,16 +96,53 @@ public class RestletFrameworkServlet extends FrameworkServlet {
private static final long serialVersionUID = 1L;
- /** The converter of Servlet calls into Restlet equivalents. */
- private volatile ServletConverter converter;
+ /** The adapter of Servlet calls into Restlet equivalents. */
+ private volatile ServletAdapter adapter;
/** The bean name of the target Restlet. */
private volatile String targetRestletBeanName;
+ /**
+ * Creates the Restlet {@link Context} to use if the target application does
+ * not already have a context associated, or if the target restlet is not an
+ * {@link Application} at all.
+ * <p>
+ * Uses a simple {@link Context} by default.
+ *
+ * @return A new instance of {@link Context}
+ */
+ protected Context createContext() {
+ return new Context();
+ }
+
@Override
protected void doService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
- getConverter().service(request, response);
+ getAdapter().service(request, response);
+ }
+
+ /**
+ * Provides access to the {@link ServletAdapter} used to handle requests.
+ * Exposed so that subclasses may do additional configuration, if necessary,
+ * by overriding {@link #initFrameworkServlet()}.
+ *
+ * @return The adapter of Servlet calls into Restlet equivalents.
+ */
+ protected ServletAdapter getAdapter() {
+ return this.adapter;
+ }
+
+ /**
+ * Provides access to the {@link ServletConverter} used to handle requests.
+ * Exposed so that subclasses may do additional configuration, if necessary,
+ * by overriding {@link #initFrameworkServlet()}.
+ *
+ * @return The converter of Servlet calls into Restlet equivalents.
+ * @deprecated Use {@link #getAdapter()} instead.
+ */
+ @Deprecated
+ protected ServletAdapter getConverter() {
+ return this.adapter;
}
/**
@@ -129,22 +165,11 @@ public String getTargetRestletBeanName() {
: this.targetRestletBeanName;
}
- /**
- * Provides access to the {@link ServletConverter} used to handle requests.
- * Exposed so that subclasses may do additional configuration, if necessary,
- * by overriding {@link #initFrameworkServlet()}.
- *
- * @return The converter of Servlet calls into Restlet equivalents.
- */
- protected ServletConverter getConverter() {
- return this.converter;
- }
-
@Override
protected void initFrameworkServlet() throws ServletException,
BeansException {
super.initFrameworkServlet();
- this.converter = new ServletConverter(getServletContext());
+ this.adapter = new ServletAdapter(getServletContext());
org.restlet.Application application;
if (getTargetRestlet() instanceof Application) {
@@ -156,20 +181,7 @@ protected void initFrameworkServlet() throws ServletException,
if (application.getContext() == null) {
application.setContext(createContext());
}
- this.converter.setTarget(application);
- }
-
- /**
- * Creates the Restlet {@link Context} to use if the target application does
- * not already have a context associated, or if the target restlet is not an
- * {@link Application} at all.
- * <p>
- * Uses a simple {@link Context} by default.
- *
- * @return A new instance of {@link Context}
- */
- protected Context createContext() {
- return new Context();
+ this.adapter.setTarget(application);
}
/**
diff --git a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java
index 66dd3da4c5..3c1f5cb406 100644
--- a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java
+++ b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java
@@ -47,7 +47,7 @@
import org.restlet.data.Reference;
import org.restlet.engine.http.HttpRequest;
import org.restlet.engine.http.HttpResponse;
-import org.restlet.engine.http.HttpServerConverter;
+import org.restlet.engine.http.HttpServerAdapter;
import org.restlet.ext.servlet.internal.ServletLogger;
@@ -89,7 +89,7 @@
*
* @author Marcelo F. Ochoa ([email protected])
*/
-public class XdbServletConverter extends HttpServerConverter {
+public class XdbServletConverter extends HttpServerAdapter {
/** The target Restlet. */
private volatile Restlet target;
diff --git a/modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java b/modules/org.restlet/src/org/restlet/engine/Helper.java
similarity index 56%
rename from modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java
rename to modules/org.restlet/src/org/restlet/engine/Helper.java
index ae2463059e..493f28593c 100644
--- a/modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java
+++ b/modules/org.restlet/src/org/restlet/engine/Helper.java
@@ -28,41 +28,13 @@
* Restlet is a registered trademark of Noelios Technologies.
*/
-package org.restlet.engine.converter;
-
-import java.util.List;
-
-import org.restlet.representation.Representation;
-import org.restlet.representation.Variant;
-import org.restlet.resource.UniformResource;
+package org.restlet.engine;
/**
- * Converter between the DOM API and Representation classes.
+ * Abstract marker class parent of all engine helpers.
*
* @author Jerome Louvel
*/
-public class RepresentationConverter extends ConverterHelper {
-
- @Override
- public List<Class<?>> getObjectClasses(Variant variant) {
- return null;
- }
-
- @Override
- public List<Variant> getVariants(Class<?> objectClass) {
- return null;
- }
-
- @Override
- public <T> T toObject(Representation representation, Class<T> targetClass,
- UniformResource resource) {
- return null;
- }
-
- @Override
- public Representation toRepresentation(Object object,
- Variant targetVariant, UniformResource resource) {
- return null;
- }
+public abstract class Helper {
}
diff --git a/modules/org.restlet/src/org/restlet/engine/RestletHelper.java b/modules/org.restlet/src/org/restlet/engine/RestletHelper.java
index 687905d4c6..b7946d1497 100644
--- a/modules/org.restlet/src/org/restlet/engine/RestletHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/RestletHelper.java
@@ -48,7 +48,7 @@
*
* @author Jerome Louvel
*/
-public abstract class RestletHelper<T extends Restlet> {
+public abstract class RestletHelper<T extends Restlet> extends Helper {
/**
* The map of attributes exchanged between the API and the Engine via this
diff --git a/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java b/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java
index 9713868eb3..425a80ebcb 100644
--- a/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java
@@ -34,6 +34,7 @@
import java.util.ArrayList;
import java.util.List;
+import org.restlet.engine.Helper;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.UniformResource;
@@ -43,7 +44,7 @@
*
* @author Jerome Louvel
*/
-public abstract class ConverterHelper {
+public abstract class ConverterHelper extends Helper {
/**
* Adds an object class to the given list. Creates a new list if necessary.
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
similarity index 99%
rename from modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java
rename to modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
index c9829e1a4e..77358036f4 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java
@@ -41,7 +41,7 @@
*
* @author Jerome Louvel
*/
-public class HttpConverter {
+public class HttpAdapter {
/** The context. */
private volatile Context context;
@@ -51,7 +51,7 @@ public class HttpConverter {
* @param context
* The context to use.
*/
- public HttpConverter(Context context) {
+ public HttpAdapter(Context context) {
this.context = context;
}
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java
similarity index 99%
rename from modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java
rename to modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java
index 734bbe09a8..9931682e53 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java
@@ -60,7 +60,7 @@
*
* @author Jerome Louvel
*/
-public class HttpClientConverter extends HttpConverter {
+public class HttpClientAdapter extends HttpAdapter {
/**
* Copies headers into a response.
*
@@ -150,7 +150,7 @@ public static void copyResponseTransportHeaders(
* @param context
* The context to use.
*/
- public HttpClientConverter(Context context) {
+ public HttpClientAdapter(Context context) {
super(context);
}
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java
index 06cf1278b3..7bf3df5ebd 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java
@@ -76,7 +76,7 @@ public abstract class HttpClientCall extends HttpCall {
* if no representation has been provided and the response has not
* sent any entity header.
* @throws NumberFormatException
- * @see HttpClientConverter#copyResponseTransportHeaders(Iterable, Response)
+ * @see HttpClientAdapter#copyResponseTransportHeaders(Iterable, Response)
*/
public static Representation copyResponseEntityHeaders(
Iterable<Parameter> responseHeaders, Representation representation)
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java
index 1e8d886ce5..24a6864a32 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java
@@ -52,7 +52,7 @@
* <tr>
* <td>converter</td>
* <td>String</td>
- * <td>org.restlet.engine.http.HttpClientConverter</td>
+ * <td>org.restlet.engine.http.HttpClientAdapter</td>
* <td>Class name of the converter of low-level HTTP calls into high level
* requests and responses.</td>
* </tr>
@@ -62,7 +62,7 @@
*/
public abstract class HttpClientHelper extends ClientHelper {
/** The converter from uniform calls to HTTP calls. */
- private volatile HttpClientConverter converter;
+ private volatile HttpClientAdapter converter;
/**
* Constructor.
@@ -89,13 +89,12 @@ public HttpClientHelper(Client client) {
*
* @return the converter from uniform calls to HTTP calls.
*/
- public HttpClientConverter getConverter() throws Exception {
+ public HttpClientAdapter getConverter() throws Exception {
if (this.converter == null) {
final String converterClass = getHelpedParameters().getFirstValue(
- "converter", "org.restlet.engine.http.HttpClientConverter");
- this.converter = (HttpClientConverter) Class
- .forName(converterClass).getConstructor(Context.class)
- .newInstance(getContext());
+ "converter", "org.restlet.engine.http.HttpClientAdapter");
+ this.converter = (HttpClientAdapter) Class.forName(converterClass)
+ .getConstructor(Context.class).newInstance(getContext());
}
return this.converter;
@@ -120,7 +119,7 @@ public void handle(Request request, Response response) {
* @param converter
* The converter to set.
*/
- public void setConverter(HttpClientConverter converter) {
+ public void setConverter(HttpClientAdapter converter) {
this.converter = converter;
}
}
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
similarity index 99%
rename from modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java
rename to modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
index 279f45bb48..7807170363 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java
@@ -59,7 +59,7 @@
*
* @author Jerome Louvel
*/
-public class HttpServerConverter extends HttpConverter {
+public class HttpServerAdapter extends HttpAdapter {
/**
* Copies the entity headers from the {@link Representation} to the
* {@link Series}.
@@ -267,7 +267,7 @@ public static void addResponseHeaders(Response response,
* @param context
* The client context.
*/
- public HttpServerConverter(Context context) {
+ public HttpServerAdapter(Context context) {
super(context);
}
diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java
index dbc15c966a..ad23a92851 100644
--- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java
@@ -61,7 +61,7 @@
* <tr>
* <td>converter</td>
* <td>String</td>
- * <td>org.restlet.engine.http.HttpServerConverter</td>
+ * <td>org.restlet.engine.http.HttpServerAdapter</td>
* <td>Class name of the converter of low-level HTTP calls into high level
* requests and responses.</td>
* </tr>
@@ -71,7 +71,7 @@
*/
public class HttpServerHelper extends ServerHelper {
/** The converter from HTTP calls to uniform calls. */
- private volatile HttpServerConverter converter;
+ private volatile HttpServerAdapter converter;
/**
* Default constructor. Note that many methods assume that a non-null server
@@ -98,13 +98,13 @@ public HttpServerHelper(Server server) {
*
* @return the converter from HTTP calls to uniform calls.
*/
- public HttpServerConverter getConverter() {
+ public HttpServerAdapter getConverter() {
if (this.converter == null) {
try {
final String converterClass = getHelpedParameters()
.getFirstValue("converter",
- "org.restlet.engine.http.HttpServerConverter");
- this.converter = (HttpServerConverter) Engine.loadClass(
+ "org.restlet.engine.http.HttpServerAdapter");
+ this.converter = (HttpServerAdapter) Engine.loadClass(
converterClass).getConstructor(Context.class)
.newInstance(getContext());
} catch (IllegalArgumentException e) {
@@ -163,7 +163,7 @@ public void handle(HttpServerCall httpCall) {
* @param converter
* The converter to set.
*/
- public void setConverter(HttpServerConverter converter) {
+ public void setConverter(HttpServerAdapter converter) {
this.converter = converter;
}
}
diff --git a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java
index 49cb48fddc..d0eb2c05df 100644
--- a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java
+++ b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java
@@ -40,6 +40,7 @@
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
+import org.restlet.engine.Helper;
import org.restlet.security.Guard;
import org.restlet.util.Series;
@@ -48,243 +49,243 @@
*
* @author Jerome Louvel
*/
-public abstract class AuthenticatorHelper {
+public abstract class AuthenticatorHelper extends Helper {
- /** The supported challenge scheme. */
- private volatile ChallengeScheme challengeScheme;
+ /** The supported challenge scheme. */
+ private volatile ChallengeScheme challengeScheme;
- /** Indicates if client side authentication is supported. */
- private volatile boolean clientSide;
+ /** Indicates if client side authentication is supported. */
+ private volatile boolean clientSide;
- /** Indicates if server side authentication is supported. */
- private volatile boolean serverSide;
+ /** Indicates if server side authentication is supported. */
+ private volatile boolean serverSide;
- /**
- * Constructor.
- *
- * @param challengeScheme
- * The supported challenge scheme.
- * @param clientSide
- * Indicates if client side authentication is supported.
- * @param serverSide
- * Indicates if server side authentication is supported.
- */
- public AuthenticatorHelper(ChallengeScheme challengeScheme,
- boolean clientSide, boolean serverSide) {
- this.challengeScheme = challengeScheme;
- this.clientSide = clientSide;
- this.serverSide = serverSide;
- }
+ /**
+ * Constructor.
+ *
+ * @param challengeScheme
+ * The supported challenge scheme.
+ * @param clientSide
+ * Indicates if client side authentication is supported.
+ * @param serverSide
+ * Indicates if server side authentication is supported.
+ */
+ public AuthenticatorHelper(ChallengeScheme challengeScheme,
+ boolean clientSide, boolean serverSide) {
+ this.challengeScheme = challengeScheme;
+ this.clientSide = clientSide;
+ this.serverSide = serverSide;
+ }
- /**
- * Indicates if the call is properly authenticated. You are guaranteed that
- * the request has a challenge response with a scheme matching the one
- * supported by the plugin.
- *
- * @param cr
- * The challenge response in the request.
- * @param request
- * The request to authenticate.
- * @param guard
- * The associated guard to callback.
- * @return -1 if the given credentials were invalid, 0 if no credentials
- * were found and 1 otherwise.
- * @see Guard#checkSecret(Request, String, char[])
- * @deprecated See new org.restlet.security package.
- */
- @Deprecated
- public int authenticate(ChallengeResponse cr, Request request, Guard guard) {
- int result = Guard.AUTHENTICATION_MISSING;
+ /**
+ * Indicates if the call is properly authenticated. You are guaranteed that
+ * the request has a challenge response with a scheme matching the one
+ * supported by the plugin.
+ *
+ * @param cr
+ * The challenge response in the request.
+ * @param request
+ * The request to authenticate.
+ * @param guard
+ * The associated guard to callback.
+ * @return -1 if the given credentials were invalid, 0 if no credentials
+ * were found and 1 otherwise.
+ * @see Guard#checkSecret(Request, String, char[])
+ * @deprecated See new org.restlet.security package.
+ */
+ @Deprecated
+ public int authenticate(ChallengeResponse cr, Request request, Guard guard) {
+ int result = Guard.AUTHENTICATION_MISSING;
- // The challenge schemes are compatible
- final String identifier = cr.getIdentifier();
- final char[] secret = cr.getSecret();
+ // The challenge schemes are compatible
+ final String identifier = cr.getIdentifier();
+ final char[] secret = cr.getSecret();
- // Check the credentials
- if ((identifier != null) && (secret != null)) {
- result = guard.checkSecret(request, identifier, secret) ? Guard.AUTHENTICATION_VALID
- : Guard.AUTHENTICATION_INVALID;
- }
+ // Check the credentials
+ if ((identifier != null) && (secret != null)) {
+ result = guard.checkSecret(request, identifier, secret) ? Guard.AUTHENTICATION_VALID
+ : Guard.AUTHENTICATION_INVALID;
+ }
- return result;
- }
+ return result;
+ }
- /**
- * Challenges the client by adding a challenge request to the response and
- * by setting the status to CLIENT_ERROR_UNAUTHORIZED.
- *
- * @param response
- * The response to update.
- * @param stale
- * Indicates if the new challenge is due to a stale response.
- * @param guard
- * The associated guard to callback.
- * @deprecated See new org.restlet.security package.
- */
- @Deprecated
- public void challenge(Response response, boolean stale, Guard guard) {
- response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
- response.setChallengeRequest(new ChallengeRequest(guard.getScheme(),
- guard.getRealm()));
- }
+ /**
+ * Challenges the client by adding a challenge request to the response and
+ * by setting the status to CLIENT_ERROR_UNAUTHORIZED.
+ *
+ * @param response
+ * The response to update.
+ * @param stale
+ * Indicates if the new challenge is due to a stale response.
+ * @param guard
+ * The associated guard to callback.
+ * @deprecated See new org.restlet.security package.
+ */
+ @Deprecated
+ public void challenge(Response response, boolean stale, Guard guard) {
+ response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
+ response.setChallengeRequest(new ChallengeRequest(guard.getScheme(),
+ guard.getRealm()));
+ }
- /**
- * Formats a challenge request as a HTTP header value.
- *
- * @param request
- * The challenge request to format.
- * @return The authenticate header value.
- */
- public String format(ChallengeRequest request) {
- final StringBuilder sb = new StringBuilder();
- sb.append(request.getScheme().getTechnicalName());
+ /**
+ * Formats a challenge request as a HTTP header value.
+ *
+ * @param request
+ * The challenge request to format.
+ * @return The authenticate header value.
+ */
+ public String format(ChallengeRequest request) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(request.getScheme().getTechnicalName());
- if (request.getRealm() != null) {
- sb.append(" realm=\"").append(request.getRealm()).append('"');
- }
+ if (request.getRealm() != null) {
+ sb.append(" realm=\"").append(request.getRealm()).append('"');
+ }
- formatParameters(sb, request.getParameters(), request);
- return sb.toString();
- }
+ formatParameters(sb, request.getParameters(), request);
+ return sb.toString();
+ }
- /**
- * Formats a challenge response as raw credentials.
- *
- * @param challenge
- * The challenge response to format.
- * @param request
- * The parent request.
- * @param httpHeaders
- * The current request HTTP headers.
- * @return The authorization header value.
- */
- public String format(ChallengeResponse challenge, Request request,
- Series<Parameter> httpHeaders) {
- final StringBuilder sb = new StringBuilder();
- sb.append(challenge.getScheme().getTechnicalName()).append(' ');
+ /**
+ * Formats a challenge response as raw credentials.
+ *
+ * @param challenge
+ * The challenge response to format.
+ * @param request
+ * The parent request.
+ * @param httpHeaders
+ * The current request HTTP headers.
+ * @return The authorization header value.
+ */
+ public String format(ChallengeResponse challenge, Request request,
+ Series<Parameter> httpHeaders) {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(challenge.getScheme().getTechnicalName()).append(' ');
- if (challenge.getCredentials() != null) {
- sb.append(challenge.getCredentials());
- } else {
- formatCredentials(sb, challenge, request, httpHeaders);
- }
+ if (challenge.getCredentials() != null) {
+ sb.append(challenge.getCredentials());
+ } else {
+ formatCredentials(sb, challenge, request, httpHeaders);
+ }
- return sb.toString();
- }
+ return sb.toString();
+ }
- /**
- * Formats a challenge response as raw credentials.
- *
- * @param sb
- * The String builder to update.
- * @param challenge
- * The challenge response to format.
- * @param request
- * The parent request.
- * @param httpHeaders
- * The current request HTTP headers.
- */
- public abstract void formatCredentials(StringBuilder sb,
- ChallengeResponse challenge, Request request,
- Series<Parameter> httpHeaders);
+ /**
+ * Formats a challenge response as raw credentials.
+ *
+ * @param sb
+ * The String builder to update.
+ * @param challenge
+ * The challenge response to format.
+ * @param request
+ * The parent request.
+ * @param httpHeaders
+ * The current request HTTP headers.
+ */
+ public abstract void formatCredentials(StringBuilder sb,
+ ChallengeResponse challenge, Request request,
+ Series<Parameter> httpHeaders);
- /**
- * Formats the parameters of a challenge request, to be appended to the
- * scheme technical name and realm.
- *
- * @param sb
- * The string builder to update.
- * @param parameters
- * The parameters to format.
- * @param request
- * The challenger request.
- */
- public void formatParameters(StringBuilder sb,
- Series<Parameter> parameters, ChallengeRequest request) {
- }
+ /**
+ * Formats the parameters of a challenge request, to be appended to the
+ * scheme technical name and realm.
+ *
+ * @param sb
+ * The string builder to update.
+ * @param parameters
+ * The parameters to format.
+ * @param request
+ * The challenger request.
+ */
+ public void formatParameters(StringBuilder sb,
+ Series<Parameter> parameters, ChallengeRequest request) {
+ }
- /**
- * Returns the supported challenge scheme.
- *
- * @return The supported challenge scheme.
- */
- public ChallengeScheme getChallengeScheme() {
- return this.challengeScheme;
- }
+ /**
+ * Returns the supported challenge scheme.
+ *
+ * @return The supported challenge scheme.
+ */
+ public ChallengeScheme getChallengeScheme() {
+ return this.challengeScheme;
+ }
- /**
- * Returns the context's logger.
- *
- * @return The context's logger.
- */
- public Logger getLogger() {
- return Context.getCurrentLogger();
- }
+ /**
+ * Returns the context's logger.
+ *
+ * @return The context's logger.
+ */
+ public Logger getLogger() {
+ return Context.getCurrentLogger();
+ }
- /**
- * Indicates if client side authentication is supported.
- *
- * @return True if client side authentication is supported.
- */
- public boolean isClientSide() {
- return this.clientSide;
- }
+ /**
+ * Indicates if client side authentication is supported.
+ *
+ * @return True if client side authentication is supported.
+ */
+ public boolean isClientSide() {
+ return this.clientSide;
+ }
- /**
- * Indicates if server side authentication is supported.
- *
- * @return True if server side authentication is supported.
- */
- public boolean isServerSide() {
- return this.serverSide;
- }
+ /**
+ * Indicates if server side authentication is supported.
+ *
+ * @return True if server side authentication is supported.
+ */
+ public boolean isServerSide() {
+ return this.serverSide;
+ }
- /**
- * Parses an authenticate header into a challenge request.
- *
- * @param header
- * The HTTP header value to parse.
- */
- public void parseRequest(ChallengeRequest cr, String header) {
- }
+ /**
+ * Parses an authenticate header into a challenge request.
+ *
+ * @param header
+ * The HTTP header value to parse.
+ */
+ public void parseRequest(ChallengeRequest cr, String header) {
+ }
- /**
- * Parses an authorization header into a challenge response.
- *
- * @param request
- * The request.
- */
- public void parseResponse(ChallengeResponse cr, Request request) {
- }
+ /**
+ * Parses an authorization header into a challenge response.
+ *
+ * @param request
+ * The request.
+ */
+ public void parseResponse(ChallengeResponse cr, Request request) {
+ }
- /**
- * Sets the supported challenge scheme.
- *
- * @param challengeScheme
- * The supported challenge scheme.
- */
- public void setChallengeScheme(ChallengeScheme challengeScheme) {
- this.challengeScheme = challengeScheme;
- }
+ /**
+ * Sets the supported challenge scheme.
+ *
+ * @param challengeScheme
+ * The supported challenge scheme.
+ */
+ public void setChallengeScheme(ChallengeScheme challengeScheme) {
+ this.challengeScheme = challengeScheme;
+ }
- /**
- * Indicates if client side authentication is supported.
- *
- * @param clientSide
- * True if client side authentication is supported.
- */
- public void setClientSide(boolean clientSide) {
- this.clientSide = clientSide;
- }
+ /**
+ * Indicates if client side authentication is supported.
+ *
+ * @param clientSide
+ * True if client side authentication is supported.
+ */
+ public void setClientSide(boolean clientSide) {
+ this.clientSide = clientSide;
+ }
- /**
- * Indicates if server side authentication is supported.
- *
- * @param serverSide
- * True if server side authentication is supported.
- */
- public void setServerSide(boolean serverSide) {
- this.serverSide = serverSide;
- }
+ /**
+ * Indicates if server side authentication is supported.
+ *
+ * @param serverSide
+ * True if server side authentication is supported.
+ */
+ public void setServerSide(boolean serverSide) {
+ this.serverSide = serverSide;
+ }
}
|
e0f983040c7680fce1b2c3b662ebad63a01e8d31
|
drools
|
[BZ-980385] fix comparison of 2 timer nodes--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
index 44a10b5a584..9cbb49c0720 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java
@@ -2170,4 +2170,39 @@ public void testAddSameResourceTwice() {
assertTrue(kbuilder.hasResults(ResultSeverity.INFO, ResultSeverity.WARNING, ResultSeverity.ERROR));
}
+ @Test
+ public void testTwoTimers() {
+ // BZ-980385
+ String str =
+ "import java.util.Date\n" +
+ "import java.util.List\n" +
+ "\n" +
+ "global List dates\n" +
+ "\n" +
+ "rule \"intervalRule\"\n" +
+ " timer(int: 200ms 100ms)\n" +
+ "when\n" +
+ " String(this == \"intervalRule\")\n" +
+ "then\n" +
+ " Date date = new Date();\n" +
+ " dates.add(date);\n" +
+ "end\n" +
+ "\n" +
+ "\n" +
+ "// this rule stops timer\n" +
+ "rule \"stopIntervalRule\"\n" +
+ " timer(int: 320ms)\n" +
+ "when\n" +
+ " $s : String(this == \"intervalRule\")\n" +
+ "then\n" +
+ " retract($s);\n" +
+ "end\n";
+
+ KieServices ks = KieServices.Factory.get();
+
+ KieFileSystem kfs = ks.newKieFileSystem().write( "src/main/resources/r1.drl", str );
+ assertEquals(0, ks.newKieBuilder( kfs ).buildAll().getResults().getMessages().size());
+
+ KieSession ksession = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();
+ }
}
\ No newline at end of file
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 7259b924e9c..cab2d915de6 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
@@ -149,11 +149,12 @@ public String toString() {
public int hashCode() {
int hash = this.leftInput.hashCode() ^ this.timer.hashCode();
- for (int i = 0; i < calendarNames.length; i++) {
- hash = hash ^ calendarNames[i].hashCode();
+ if (calendarNames != null) {
+ for (int i = 0; i < calendarNames.length; i++) {
+ hash = hash ^ calendarNames[i].hashCode();
+ }
}
return hash;
-
}
public boolean equals(final Object object) {
@@ -167,14 +168,16 @@ public boolean equals(final Object object) {
final TimerNode other = (TimerNode) object;
- if (other.getCalendarNames().length != calendarNames.length) {
- return false;
- }
-
- for (int i = 0; i < calendarNames.length; i++) {
- if (!other.getCalendarNames()[i].equals(calendarNames[i])) {
+ if (calendarNames != null) {
+ if (other.getCalendarNames() == null || other.getCalendarNames().length != calendarNames.length) {
return false;
}
+
+ for (int i = 0; i < calendarNames.length; i++) {
+ if (!other.getCalendarNames()[i].equals(calendarNames[i])) {
+ return false;
+ }
+ }
}
if ( declarations != null ) {
|
cf75df69f253669574263f69b1ec7b1554ea5701
|
hadoop
|
YARN-1497. Fix comment and remove accidental- println--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1567491 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java
index 80e548d26e632..4332f5beeafdc 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/ApplicationCLI.java
@@ -382,11 +382,7 @@ private void killApplication(String applicationId) throws YarnException,
}
/**
- * Kills the application with the application id as appId
- *
- * @param applicationId
- * @throws YarnException
- * @throws IOException
+ * Moves the application with the given ID to the given queue.
*/
private void moveApplicationAcrossQueues(String applicationId, String queue)
throws YarnException, IOException {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java
index 12bc6be731640..97721864968db 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java
@@ -675,7 +675,6 @@ public void testAppsHelpCommand() throws Exception {
int result = spyCli.run(new String[] { "-help" });
Assert.assertTrue(result == 0);
verify(spyCli).printUsage(any(Options.class));
- System.err.println(sysOutStream.toString()); //todo sandyt remove this hejfkdsl
Assert.assertEquals(createApplicationCLIHelpMessage(),
sysOutStream.toString());
|
630620ee581f7fbe07b95ec8cce030e56108cbdf
|
restlet-framework-java
|
- Continued SIP transaction support--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
index 89e7bcb763..8518e34707 100644
--- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
+++ b/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/internal/SipClientOutboundWay.java
@@ -36,6 +36,7 @@
import org.restlet.engine.connector.Connection;
import org.restlet.engine.header.HeaderConstants;
import org.restlet.engine.header.TagWriter;
+import org.restlet.engine.io.IoState;
import org.restlet.ext.sip.SipRecipientInfo;
import org.restlet.ext.sip.SipRequest;
import org.restlet.util.Series;
@@ -212,8 +213,16 @@ protected void addRequestHeaders(Series<Parameter> headers) {
@Override
protected void handle(Response response) {
- // TODO Auto-generated method stub
+ setMessage(response);
+ }
+
+ @Override
+ public void updateState() {
+ if (getMessage() != null) {
+ setIoState(IoState.INTEREST);
+ }
+ super.updateState();
}
}
|
bd1b559d47603748f6d57a0ff21f68505258ace5
|
spring-framework
|
MockHttpServletResponse supports multiple- includes (SPR- )--
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
index 6256bbe51632..6d220572665d 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.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.
@@ -98,7 +98,7 @@ public class MockHttpServletResponse implements HttpServletResponse {
private String forwardedUrl;
- private String includedUrl;
+ private final List<String> includedUrls = new ArrayList<String>();
//---------------------------------------------------------------------
@@ -443,11 +443,28 @@ public String getForwardedUrl() {
}
public void setIncludedUrl(String includedUrl) {
- this.includedUrl = includedUrl;
+ this.includedUrls.clear();
+ if (includedUrl != null) {
+ this.includedUrls.add(includedUrl);
+ }
}
public String getIncludedUrl() {
- return this.includedUrl;
+ int count = this.includedUrls.size();
+ if (count > 1) {
+ throw new IllegalStateException(
+ "More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
+ }
+ return (count == 1 ? this.includedUrls.get(0) : null);
+ }
+
+ public void addIncludedUrl(String includedUrl) {
+ Assert.notNull(includedUrl, "Included URL must not be null");
+ this.includedUrls.add(includedUrl);
+ }
+
+ public List<String> getIncludedUrls() {
+ return this.includedUrls;
}
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
index 17485d21f381..a87bea43c91c 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.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.
@@ -68,7 +68,7 @@ public void forward(ServletRequest request, ServletResponse response) {
public void include(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
- getMockHttpServletResponse(response).setIncludedUrl(this.url);
+ getMockHttpServletResponse(response).addIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
}
|
5ed43d241a1786f41c97af3fc31de3a6f7d1f3ef
|
restlet-framework-java
|
- More optimizations for internal connectors.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/InputEntityStream.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/InputEntityStream.java
index 7031d94564..c524720246 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/InputEntityStream.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/InputEntityStream.java
@@ -27,7 +27,6 @@
package com.noelios.restlet.http;
-import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -51,10 +50,6 @@ public class InputEntityStream extends InputStream {
* The total size that should be read from the source stream.
*/
public InputEntityStream(InputStream source, long size) {
- if (!(source instanceof BufferedInputStream)) {
- source = new BufferedInputStream(source);
- }
-
this.source = source;
this.availableSize = size;
}
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamClientCall.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamClientCall.java
index 1d2c538a77..48e5796745 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamClientCall.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamClientCall.java
@@ -27,6 +27,8 @@
package com.noelios.restlet.http;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -289,8 +291,10 @@ public Status sendRequest(Request request) {
// Create the client socket
this.socket = createSocket(hostDomain, hostPort);
- this.requestStream = this.socket.getOutputStream();
- this.responseStream = this.socket.getInputStream();
+ this.requestStream = new BufferedOutputStream(this.socket
+ .getOutputStream());
+ this.responseStream = new BufferedInputStream(this.socket
+ .getInputStream());
// Write the request line
getRequestHeadStream().write(getMethod().getBytes());
@@ -323,6 +327,7 @@ public Status sendRequest(Request request) {
// Write the end of the headers section
HttpUtils.writeCRLF(getRequestHeadStream());
+ getRequestHeadStream().flush();
// Write the request body
result = super.sendRequest(request);
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java
index 0b030a7981..735a4329c7 100644
--- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java
+++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/StreamServerHelper.java
@@ -27,6 +27,8 @@
package com.noelios.restlet.http;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
@@ -81,9 +83,12 @@ private ConnectionHandler(StreamServerHelper helper, Socket socket) {
*/
public void run() {
try {
- this.helper.handle(new StreamServerCall(
- this.helper.getHelped(), this.socket.getInputStream(),
- this.socket.getOutputStream(), this.socket));
+ this.helper
+ .handle(new StreamServerCall(this.helper.getHelped(),
+ new BufferedInputStream(this.socket
+ .getInputStream()),
+ new BufferedOutputStream(this.socket
+ .getOutputStream()), this.socket));
} catch (final IOException ex) {
this.helper.getLogger().log(Level.WARNING,
"Unexpected error while handling a call", ex);
|
988192ad2245343da0fbf89277746833256d0109
|
intellij-community
|
Added code completion test.--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/ComlpetionActionTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/ComlpetionActionTest.java
index ce9b85cd97eaf..8fca979db7358 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/ComlpetionActionTest.java
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/ComlpetionActionTest.java
@@ -83,12 +83,13 @@ public void run() {
result = myEditor.getDocument().getText();
result = result.substring(0, offset) + CARET_MARKER + result.substring(offset);
- if (items.length > 0) {
- result = result + "\n#####";
+ if (items.length > 1) {
Arrays.sort(items);
+ result = "";
for (LookupItem item : items) {
result = result + "\n" + item.getLookupString();
}
+ result = result.trim();
}
} finally {
@@ -109,18 +110,17 @@ protected LookupItem[] getAcceptableItems(CompletionData completionData) {
final Set<LookupItem> lookupSet = new LinkedHashSet<LookupItem>();
final PsiElement elem = myFile.findElementAt(myOffset);
- String whitePrefix = "";
- for (int i = 0; i < myOffset; i++) {
- whitePrefix += " ";
- }
-
+ /**
+ * Create fake file with dummy element
+ */
String newFileText = myFile.getText().substring(0, myOffset + 1) + "IntellijIdeaRulezzz" +
myFile.getText().substring(myOffset + 1);
try {
- PsiFile newFile = createGroovyFile(newFileText);
+ /**
+ * Hack for IDEA completion
+ */
+ PsiFile newFile = TestUtils.createPseudoPhysicalFile(project, newFileText);
PsiElement insertedElement = newFile.findElementAt(myOffset + 1);
-
-
final int offset1 =
myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionStart() : myEditor.getCaretModel().getOffset();
final int offset2 = myEditor.getSelectionModel().hasSelection() ? myEditor.getSelectionModel().getSelectionEnd() : offset1;
@@ -148,20 +148,6 @@ protected LookupItem[] getAcceptableItems(CompletionData completionData) {
}
}
- private PsiElement createIdentifierFromText(String idText) {
- PsiFile file = null;
- try {
- file = createGroovyFile(idText);
- } catch (IncorrectOperationException e) {
- e.printStackTrace();
- }
- return ((GrReferenceExpression) ((GroovyFile) file).getTopStatements()[0]).getReferenceNameElement();
- }
-
- private PsiFile createGroovyFile(String idText) throws IncorrectOperationException {
- return TestUtils.createPseudoPhysicalFile(project, idText);
- }
-
public String transform(String testName, String[] data) throws Exception {
setSettings();
String fileText = data[0];
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/instanceof/ins1.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/instanceof/ins1.test
deleted file mode 100644
index 75627b97c1354..0000000000000
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/instanceof/ins1.test
+++ /dev/null
@@ -1,5 +0,0 @@
-return a i<caret> b
------
-return a instanceof <caret>b
-#####
-instanceof
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class2.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class2.test
new file mode 100644
index 0000000000000..eefa814c2e41e
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class2.test
@@ -0,0 +1,3 @@
+class A extends B <caret> C {}
+-----
+class A extends B implements <caret>C {}
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class3.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class3.test
new file mode 100644
index 0000000000000..0c2dd701fecba
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/class/class3.test
@@ -0,0 +1,4 @@
+cl<caret>
+-----
+class <caret>
+
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp1.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp1.test
index 8d649d7c03414..4002f2587aa85 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp1.test
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp1.test
@@ -1,5 +1,3 @@
im<caret>
-----
-import <caret>
-#####
-import
\ No newline at end of file
+import <caret>
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp2.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp2.test
index c47a164707171..d84d67abbfcf3 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp2.test
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/import/imp2.test
@@ -1,6 +1,4 @@
i<caret>
-----
-i<caret>
-#####
import
interface
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/instanceof/ins1.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/instanceof/ins1.test
new file mode 100644
index 0000000000000..78e6dd647b547
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/instanceof/ins1.test
@@ -0,0 +1,3 @@
+return a i<caret> b
+-----
+return a instanceof <caret>b
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/package/pack1.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/package/pack1.test
index d1d943081e039..d0f9510a93f88 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/package/pack1.test
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/package/pack1.test
@@ -1,5 +1,3 @@
pa<caret>
-----
-package <caret>
-#####
-package
\ No newline at end of file
+package <caret>
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit1.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit1.test
similarity index 53%
rename from plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit1.test
rename to plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit1.test
index 99b262b739939..3e0787084872f 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit1.test
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit1.test
@@ -6,13 +6,5 @@ class A{
}
}
-----
-class A{
- def foo(){
- switch (x){
- <caret>
- }
- }
-}
-#####
case
default
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit2.test b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit2.test
similarity index 92%
rename from plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit2.test
rename to plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit2.test
index 5bcc55a6b1533..ef6dbfa57cbd4 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/switch/swit2.test
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/data/keyword/switch/swit2.test
@@ -12,6 +12,4 @@ class A {
case <caret>
}
}
-}
-#####
-case
\ No newline at end of file
+}
\ No newline at end of file
|
788d431d98df0087a4ea7be7b3c82c4c5d2a8209
|
ReactiveX-RxJava
|
Implemented periodic scheduling, too. Needs testing- now.--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java b/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java
index e7883c69a1..ffa731a85e 100644
--- a/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java
+++ b/rxjava-core/src/main/java/rx/concurrency/SwingScheduler.java
@@ -31,6 +31,7 @@
import rx.Scheduler;
import rx.Subscription;
+import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;
import rx.util.functions.Action0;
import rx.util.functions.Func2;
@@ -73,11 +74,7 @@ public void call() {
public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long dueTime, TimeUnit unit) {
final AtomicReference<Subscription> sub = new AtomicReference<Subscription>();
long delay = unit.toMillis(dueTime);
-
- if (delay > Integer.MAX_VALUE) {
- throw new IllegalArgumentException(String.format(
- "The swing timer only accepts delays up to %d milliseconds.", Integer.MAX_VALUE));
- }
+ assertThatTheDelayIsValidForTheSwingTimer(delay);
class ExecuteOnceAction implements ActionListener {
private Timer timer;
@@ -110,6 +107,52 @@ public void call() {
}
});
}
+
+ @Override
+ public <T> Subscription schedulePeriodically(T state, final Func2<Scheduler, T, Subscription> action, long initialDelay, long period, TimeUnit unit) {
+ // FIXME test this!
+ final AtomicReference<Timer> timer = new AtomicReference<Timer>();
+
+ final long delay = unit.toMillis(period);
+ assertThatTheDelayIsValidForTheSwingTimer(delay);
+
+ final CompositeSubscription subscriptions = new CompositeSubscription();
+ final Func2<Scheduler, T, Subscription> initialAction = new Func2<Scheduler, T, Subscription>() {
+ @Override
+ public Subscription call(final Scheduler scheduler, final T state) {
+ // call the action once initially
+ subscriptions.add(action.call(scheduler, state));
+
+ // start timer for periodic execution, collect subscriptions
+ timer.set(new Timer((int) delay, new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ subscriptions.add(action.call(scheduler, state));
+ }
+ }));
+ timer.get().start();
+
+ return action.call(scheduler, state);
+ }
+ };
+ subscriptions.add(schedule(state, initialAction, initialDelay, unit));
+
+ subscriptions.add(Subscriptions.create(new Action0() {
+ @Override
+ public void call() {
+ // in addition to all the individual unsubscriptions, stop the timer on unsubscribing
+ timer.get().stop();
+ }
+ }));
+
+ return subscriptions;
+ }
+
+ private static void assertThatTheDelayIsValidForTheSwingTimer(long delay) {
+ if (delay > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException(String.format("The swing timer only accepts delays up to %d milliseconds.", Integer.MAX_VALUE));
+ }
+ }
public static class UnitTest {
@Test
|
e449fb139b70db15ffae182355d5306d90389adb
|
ReactiveX-RxJava
|
Fixed javadoc and comments, cleaned up a bit, and- tried to fix synchronization.--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
index 3cf2a410c4..87d0cbe0c9 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
@@ -43,6 +43,14 @@
public class OperationCombineLatest {
+ /**
+ * Combines the two given observables, emitting an event containing an aggregation of the latest values of each of the source observables
+ * each time an event is received from one of the source observables, where the aggregation is defined by the given function.
+ * @param w0 The first source observable.
+ * @param w1 The second source observable.
+ * @param combineLatestFunction The aggregation function used to combine the source observable values.
+ * @return A function from an observer to a subscription. This can be used to create an observable from.
+ */
public static <T0, T1, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -50,6 +58,9 @@ public static <T0, T1, R> Func1<Observer<R>, Subscription> combineLatest(Observa
return a;
}
+ /**
+ * @see #combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction)
+ */
public static <T0, T1, T2, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Func3<T0, T1, T2, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -58,6 +69,9 @@ public static <T0, T1, T2, R> Func1<Observer<R>, Subscription> combineLatest(Obs
return a;
}
+ /**
+ * @see #combineLatest(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> combineLatestFunction)
+ */
public static <T0, T1, T2, T3, R> Func1<Observer<R>, Subscription> combineLatest(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<T0, T1, T2, T3, R> combineLatestFunction) {
Aggregator<R> a = new Aggregator<R>(Functions.fromFunc(combineLatestFunction));
a.addObserver(new CombineObserver<R, T0>(a, w0));
@@ -91,7 +105,7 @@ public void onCompleted() {
@Override
public void onError(Exception e) {
- a.error(this, e);
+ a.error(e);
}
@Override
@@ -101,32 +115,46 @@ public void onNext(T args) {
}
/**
- * Receive notifications from each of the Observables we are reducing and execute the combineLatestFunction whenever we have received events from all Observables.
- *
- * @param <R>
+ * Receive notifications from each of the observables we are reducing and execute the combineLatestFunction
+ * whenever we have received an event from one of the observables, as soon as each Observable has received
+ * at least one event.
*/
private static class Aggregator<R> implements Func1<Observer<R>, Subscription> {
+ private Observer<R> observer;
+
private final FuncN<R> combineLatestFunction;
- private Observer<R> Observer;
- private AtomicBoolean running = new AtomicBoolean(true);
+ private final AtomicBoolean running = new AtomicBoolean(true);
+ // used as an internal lock for handling the latest values and the completed state of each observer
+ private final Object lockObject = new Object();
+
/**
- * store when a Observer completes
+ * Store when an observer completes.
* <p>
- * Note that access to this set MUST BE SYNCHRONIZED
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
* */
- private Set<CombineObserver<R, ?>> completed = new HashSet<CombineObserver<R, ?>>();
+ private final Set<CombineObserver<R, ?>> completed = new HashSet<CombineObserver<R, ?>>();
/**
- * The last value from a Observer
+ * The latest value from each observer
* <p>
- * Note that access to this set MUST BE SYNCHRONIZED
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
* */
- private Map<CombineObserver<R, ?>, Object> lastValue = new HashMap<CombineObserver<R, ?>, Object>();
+ private final Map<CombineObserver<R, ?>, Object> latestValue = new HashMap<CombineObserver<R, ?>, Object>();
- private Set<CombineObserver<R, ?>> hasLastValue = new HashSet<CombineObserver<R, ?>>();
- private List<CombineObserver<R, ?>> observers = new LinkedList<CombineObserver<R, ?>>();
+ /**
+ * Whether each observer has a latest value at all.
+ * <p>
+ * Note that access to this set MUST BE SYNCHRONIZED via 'lockObject' above.
+ * */
+ private final Set<CombineObserver<R, ?>> hasLatestValue = new HashSet<CombineObserver<R, ?>>();
+
+ /**
+ * Ordered list of observers to combine.
+ * No synchronization is necessary as these can not be added or changed asynchronously.
+ */
+ private final List<CombineObserver<R, ?>> observers = new LinkedList<CombineObserver<R, ?>>();
public Aggregator(FuncN<R> combineLatestFunction) {
this.combineLatestFunction = combineLatestFunction;
@@ -135,55 +163,53 @@ public Aggregator(FuncN<R> combineLatestFunction) {
/**
* Receive notification of a Observer starting (meaning we should require it for aggregation)
*
- * @param w
+ * @param w The observer to add.
*/
- synchronized <T> void addObserver(CombineObserver<R, T> w) {
- observers.add(w);
+ <T> void addObserver(CombineObserver<R, T> w) {
+ observers.add(w);
}
/**
* Receive notification of a Observer completing its iterations.
*
- * @param w
+ * @param w The observer that has completed.
*/
- synchronized <T> void complete(CombineObserver<R, T> w) {
- // store that this CombineLatestObserver is completed
- completed.add(w);
- // if all CombineObservers are completed, we mark the whole thing as completed
- if (completed.size() == observers.size()) {
- if (running.get()) {
- // mark ourselves as done
- Observer.onCompleted();
- // just to ensure we stop processing in case we receive more onNext/complete/error calls after this
- running.set(false);
+ <T> void complete(CombineObserver<R, T> w) {
+ synchronized(lockObject) {
+ // store that this CombineLatestObserver is completed
+ completed.add(w);
+ // if all CombineObservers are completed, we mark the whole thing as completed
+ if (completed.size() == observers.size()) {
+ if (running.get()) {
+ // mark ourselves as done
+ observer.onCompleted();
+ // just to ensure we stop processing in case we receive more onNext/complete/error calls after this
+ running.set(false);
+ }
}
}
}
/**
* Receive error for a Observer. Throw the error up the chain and stop processing.
- *
- * @param w
*/
- synchronized <T> void error(CombineObserver<R, T> w, Exception e) {
- Observer.onError(e);
- /* tell ourselves to stop processing onNext events, event if the Observers don't obey the unsubscribe we're about to send */
- running.set(false);
- /* tell all Observers to unsubscribe since we had an error */
+ void error(Exception e) {
+ observer.onError(e);
+ /* tell all observers to unsubscribe since we had an error */
stop();
}
/**
- * Receive the next value from a Observer.
+ * Receive the next value from an observer.
* <p>
- * If we have received values from all Observers, trigger the combineLatest function, otherwise store the value and keep waiting.
+ * If we have received values from all observers, trigger the combineLatest function, otherwise store the value and keep waiting.
*
* @param w
* @param arg
*/
<T> void next(CombineObserver<R, T> w, T arg) {
- if (Observer == null) {
- throw new RuntimeException("This shouldn't be running if a Observer isn't registered");
+ if (observer == null) {
+ throw new RuntimeException("This shouldn't be running if an Observer isn't registered");
}
/* if we've been 'unsubscribed' don't process anything further even if the things we're watching keep sending (likely because they are not responding to the unsubscribe call) */
@@ -194,15 +220,17 @@ <T> void next(CombineObserver<R, T> w, T arg) {
// define here so the variable is out of the synchronized scope
Object[] argsToCombineLatest = new Object[observers.size()];
- // we synchronize everything that touches receivedValues and the internal LinkedList objects
- synchronized (this) {
- // remember this as the last value for this Observer
- lastValue.put(w, arg);
- hasLastValue.add(w);
+ // we synchronize everything that touches latest values
+ synchronized (lockObject) {
+ // remember this as the latest value for this observer
+ latestValue.put(w, arg);
+
+ // remember that this observer now has a latest value set
+ hasLatestValue.add(w);
- // if all CombineLatestObservers in 'receivedValues' map have a value, invoke the combineLatestFunction
+ // if all observers in the 'observers' list have a value, invoke the combineLatestFunction
for (CombineObserver<R, ?> rw : observers) {
- if (!hasLastValue.contains(rw)) {
+ if (!hasLatestValue.contains(rw)) {
// we don't have a value yet for each observer to combine, so we don't have a combined value yet either
return;
}
@@ -210,48 +238,45 @@ <T> void next(CombineObserver<R, T> w, T arg) {
// if we get to here this means all the queues have data
int i = 0;
for (CombineObserver<R, ?> _w : observers) {
- argsToCombineLatest[i++] = lastValue.get(_w);
+ argsToCombineLatest[i++] = latestValue.get(_w);
}
}
// if we did not return above from the synchronized block we can now invoke the combineLatestFunction with all of the args
// we do this outside the synchronized block as it is now safe to call this concurrently and don't need to block other threads from calling
// this 'next' method while another thread finishes calling this combineLatestFunction
- Observer.onNext(combineLatestFunction.call(argsToCombineLatest));
+ observer.onNext(combineLatestFunction.call(argsToCombineLatest));
}
@Override
- public Subscription call(Observer<R> Observer) {
- if (this.Observer != null) {
+ public Subscription call(Observer<R> observer) {
+ if (this.observer != null) {
throw new IllegalStateException("Only one Observer can subscribe to this Observable.");
}
- this.Observer = Observer;
+ this.observer = observer;
- /* start the Observers */
+ /* start the observers */
for (CombineObserver<R, ?> rw : observers) {
rw.startWatching();
}
return new Subscription() {
-
@Override
public void unsubscribe() {
stop();
}
-
};
}
private void stop() {
/* tell ourselves to stop processing onNext events */
running.set(false);
- /* propogate to all Observers to unsubscribe */
+ /* propogate to all observers to unsubscribe */
for (CombineObserver<R, ?> rw : observers) {
if (rw.subscription != null) {
rw.subscription.unsubscribe();
}
}
}
-
}
public static class UnitTest {
@@ -597,7 +622,7 @@ public void testAggregatorError() {
verify(aObserver, never()).onCompleted();
verify(aObserver, times(1)).onNext("helloworld");
- a.error(r1, new RuntimeException(""));
+ a.error(new RuntimeException(""));
a.next(r1, "hello");
a.next(r2, "again");
|
e6a03e2fc037b48f3989ef899310e007bb3d16a9
|
hadoop
|
Merge r1601491 from trunk. YARN-2030. Augmented- RMStateStore with state machine. Contributed by Binglin Chang--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1601492 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 553f378ceee6e..29add5e139352 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -134,6 +134,8 @@ Release 2.5.0 - UNRELEASED
YARN-2132. ZKRMStateStore.ZKAction#runWithRetries doesn't log the exception
it encounters. (Vamsee Yarlagadda via kasha)
+ YARN-2030. Augmented RMStateStore with state machine. (Binglin Chang 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/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
index 1f6e175ced108..7f4dad83fe92a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java
@@ -47,6 +47,8 @@
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMStateVersionProto;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
@@ -314,7 +316,7 @@ private void loadRMDTSecretManagerState(RMState rmState) throws Exception {
@Override
public synchronized void storeApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateDataPB) throws Exception {
+ ApplicationStateData appStateDataPB) throws Exception {
String appIdStr = appId.toString();
Path appDirPath = getAppDir(rmAppRoot, appIdStr);
fs.mkdirs(appDirPath);
@@ -334,7 +336,7 @@ public synchronized void storeApplicationStateInternal(ApplicationId appId,
@Override
public synchronized void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateDataPB) throws Exception {
+ ApplicationStateData appStateDataPB) throws Exception {
String appIdStr = appId.toString();
Path appDirPath = getAppDir(rmAppRoot, appIdStr);
Path nodeCreatePath = getNodePath(appDirPath, appIdStr);
@@ -354,7 +356,7 @@ public synchronized void updateApplicationStateInternal(ApplicationId appId,
@Override
public synchronized void storeApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateDataPB)
+ ApplicationAttemptStateData attemptStateDataPB)
throws Exception {
Path appDirPath =
getAppDir(rmAppRoot, appAttemptId.getApplicationId().toString());
@@ -375,7 +377,7 @@ public synchronized void storeApplicationAttemptStateInternal(
@Override
public synchronized void updateApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateDataPB)
+ ApplicationAttemptStateData attemptStateDataPB)
throws Exception {
Path appDirPath =
getAppDir(rmAppRoot, appAttemptId.getApplicationId().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/recovery/MemoryRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java
index c9f3541f53542..a43b20da39256 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java
@@ -32,9 +32,9 @@
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
import com.google.common.annotations.VisibleForTesting;
@@ -80,7 +80,7 @@ protected synchronized void closeInternal() throws Exception {
@Override
public void storeApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData)
+ ApplicationStateData appStateData)
throws Exception {
ApplicationState appState =
new ApplicationState(appStateData.getSubmitTime(),
@@ -92,7 +92,7 @@ public void storeApplicationStateInternal(ApplicationId appId,
@Override
public void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception {
+ ApplicationStateData appStateData) throws Exception {
ApplicationState updatedAppState =
new ApplicationState(appStateData.getSubmitTime(),
appStateData.getStartTime(),
@@ -112,7 +112,7 @@ public void updateApplicationStateInternal(ApplicationId appId,
@Override
public synchronized void storeApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData)
+ ApplicationAttemptStateData attemptStateData)
throws Exception {
Credentials credentials = null;
if(attemptStateData.getAppAttemptTokens() != null){
@@ -137,7 +137,7 @@ public synchronized void storeApplicationAttemptStateInternal(
@Override
public synchronized void updateApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData)
+ ApplicationAttemptStateData attemptStateData)
throws Exception {
Credentials credentials = null;
if (attemptStateData.getAppAttemptTokens() != null) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java
index a12099f46f3e2..6a0426c0e8ca2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java
@@ -25,9 +25,9 @@
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
@Unstable
public class NullRMStateStore extends RMStateStore {
@@ -54,13 +54,13 @@ public RMState loadState() throws Exception {
@Override
protected void storeApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception {
+ ApplicationStateData appStateData) throws Exception {
// Do nothing
}
@Override
protected void storeApplicationAttemptStateInternal(ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception {
+ ApplicationAttemptStateData attemptStateData) throws Exception {
// Do nothing
}
@@ -102,13 +102,13 @@ public void removeRMDTMasterKeyState(DelegationKey delegationKey) throws Excepti
@Override
protected void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception {
+ ApplicationStateData appStateData) throws Exception {
// Do nothing
}
@Override
protected void updateApplicationAttemptStateInternal(ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception {
+ ApplicationAttemptStateData attemptStateData) throws Exception {
}
@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/recovery/RMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
index fc4537c793f71..affc6f9d86567 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java
@@ -18,7 +18,6 @@
package org.apache.hadoop.yarn.server.resourcemanager.recovery;
-import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -31,7 +30,6 @@
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
@@ -50,6 +48,8 @@
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEvent;
import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEventType;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
@@ -61,6 +61,10 @@
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptNewSavedEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptUpdateSavedEvent;
+import org.apache.hadoop.yarn.state.InvalidStateTransitonException;
+import org.apache.hadoop.yarn.state.SingleArcTransition;
+import org.apache.hadoop.yarn.state.StateMachine;
+import org.apache.hadoop.yarn.state.StateMachineFactory;
@Private
@Unstable
@@ -83,8 +87,163 @@ public abstract class RMStateStore extends AbstractService {
public static final Log LOG = LogFactory.getLog(RMStateStore.class);
+ private enum RMStateStoreState {
+ DEFAULT
+ };
+
+ private static final StateMachineFactory<RMStateStore,
+ RMStateStoreState,
+ RMStateStoreEventType,
+ RMStateStoreEvent>
+ stateMachineFactory = new StateMachineFactory<RMStateStore,
+ RMStateStoreState,
+ RMStateStoreEventType,
+ RMStateStoreEvent>(
+ RMStateStoreState.DEFAULT)
+ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT,
+ RMStateStoreEventType.STORE_APP, new StoreAppTransition())
+ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT,
+ RMStateStoreEventType.UPDATE_APP, new UpdateAppTransition())
+ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT,
+ RMStateStoreEventType.REMOVE_APP, new RemoveAppTransition())
+ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT,
+ RMStateStoreEventType.STORE_APP_ATTEMPT, new StoreAppAttemptTransition())
+ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT,
+ RMStateStoreEventType.UPDATE_APP_ATTEMPT, new UpdateAppAttemptTransition());
+
+ private final StateMachine<RMStateStoreState,
+ RMStateStoreEventType,
+ RMStateStoreEvent> stateMachine;
+
+ private static class StoreAppTransition
+ implements SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ @Override
+ public void transition(RMStateStore store, RMStateStoreEvent event) {
+ if (!(event instanceof RMStateStoreAppEvent)) {
+ // should never happen
+ LOG.error("Illegal event type: " + event.getClass());
+ return;
+ }
+ ApplicationState appState = ((RMStateStoreAppEvent) event).getAppState();
+ ApplicationId appId = appState.getAppId();
+ ApplicationStateData appStateData = ApplicationStateData
+ .newInstance(appState);
+ LOG.info("Storing info for app: " + appId);
+ try {
+ store.storeApplicationStateInternal(appId, appStateData);
+ store.notifyDoneStoringApplication(appId, null);
+ } catch (Exception e) {
+ LOG.error("Error storing app: " + appId, e);
+ store.notifyStoreOperationFailed(e);
+ }
+ };
+ }
+
+ private static class UpdateAppTransition implements
+ SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ @Override
+ public void transition(RMStateStore store, RMStateStoreEvent event) {
+ if (!(event instanceof RMStateUpdateAppEvent)) {
+ // should never happen
+ LOG.error("Illegal event type: " + event.getClass());
+ return;
+ }
+ ApplicationState appState = ((RMStateUpdateAppEvent) event).getAppState();
+ ApplicationId appId = appState.getAppId();
+ ApplicationStateData appStateData = ApplicationStateData
+ .newInstance(appState);
+ LOG.info("Updating info for app: " + appId);
+ try {
+ store.updateApplicationStateInternal(appId, appStateData);
+ store.notifyDoneUpdatingApplication(appId, null);
+ } catch (Exception e) {
+ LOG.error("Error updating app: " + appId, e);
+ store.notifyStoreOperationFailed(e);
+ }
+ };
+ }
+
+ private static class RemoveAppTransition implements
+ SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ @Override
+ public void transition(RMStateStore store, RMStateStoreEvent event) {
+ if (!(event instanceof RMStateStoreRemoveAppEvent)) {
+ // should never happen
+ LOG.error("Illegal event type: " + event.getClass());
+ return;
+ }
+ ApplicationState appState = ((RMStateStoreRemoveAppEvent) event)
+ .getAppState();
+ ApplicationId appId = appState.getAppId();
+ LOG.info("Removing info for app: " + appId);
+ try {
+ store.removeApplicationStateInternal(appState);
+ } catch (Exception e) {
+ LOG.error("Error removing app: " + appId, e);
+ store.notifyStoreOperationFailed(e);
+ }
+ };
+ }
+
+ private static class StoreAppAttemptTransition implements
+ SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ @Override
+ public void transition(RMStateStore store, RMStateStoreEvent event) {
+ if (!(event instanceof RMStateStoreAppAttemptEvent)) {
+ // should never happen
+ LOG.error("Illegal event type: " + event.getClass());
+ return;
+ }
+ ApplicationAttemptState attemptState =
+ ((RMStateStoreAppAttemptEvent) event).getAppAttemptState();
+ try {
+ ApplicationAttemptStateData attemptStateData =
+ ApplicationAttemptStateData.newInstance(attemptState);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Storing info for attempt: " + attemptState.getAttemptId());
+ }
+ store.storeApplicationAttemptStateInternal(attemptState.getAttemptId(),
+ attemptStateData);
+ store.notifyDoneStoringApplicationAttempt(attemptState.getAttemptId(),
+ null);
+ } catch (Exception e) {
+ LOG.error("Error storing appAttempt: " + attemptState.getAttemptId(), e);
+ store.notifyStoreOperationFailed(e);
+ }
+ };
+ }
+
+ private static class UpdateAppAttemptTransition implements
+ SingleArcTransition<RMStateStore, RMStateStoreEvent> {
+ @Override
+ public void transition(RMStateStore store, RMStateStoreEvent event) {
+ if (!(event instanceof RMStateUpdateAppAttemptEvent)) {
+ // should never happen
+ LOG.error("Illegal event type: " + event.getClass());
+ return;
+ }
+ ApplicationAttemptState attemptState =
+ ((RMStateUpdateAppAttemptEvent) event).getAppAttemptState();
+ try {
+ ApplicationAttemptStateData attemptStateData = ApplicationAttemptStateData
+ .newInstance(attemptState);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Updating info for attempt: " + attemptState.getAttemptId());
+ }
+ store.updateApplicationAttemptStateInternal(attemptState.getAttemptId(),
+ attemptStateData);
+ store.notifyDoneUpdatingApplicationAttempt(attemptState.getAttemptId(),
+ null);
+ } catch (Exception e) {
+ LOG.error("Error updating appAttempt: " + attemptState.getAttemptId(), e);
+ store.notifyStoreOperationFailed(e);
+ }
+ };
+ }
+
public RMStateStore() {
super(RMStateStore.class.getName());
+ stateMachine = stateMachineFactory.make(this);
}
/**
@@ -390,10 +549,10 @@ public synchronized void updateApplicationState(ApplicationState appState) {
* application.
*/
protected abstract void storeApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception;
+ ApplicationStateData appStateData) throws Exception;
protected abstract void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception;
+ ApplicationStateData appStateData) throws Exception;
@SuppressWarnings("unchecked")
/**
@@ -428,11 +587,11 @@ public synchronized void updateApplicationAttemptState(
*/
protected abstract void storeApplicationAttemptStateInternal(
ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception;
+ ApplicationAttemptStateData attemptStateData) throws Exception;
protected abstract void updateApplicationAttemptStateInternal(
ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception;
+ ApplicationAttemptStateData attemptStateData) throws Exception;
/**
* RMDTSecretManager call this to store the state of a delegation token
@@ -596,105 +755,10 @@ public Credentials getCredentialsFromAppAttempt(RMAppAttempt appAttempt) {
// Dispatcher related code
protected void handleStoreEvent(RMStateStoreEvent event) {
- if (event.getType().equals(RMStateStoreEventType.STORE_APP)
- || event.getType().equals(RMStateStoreEventType.UPDATE_APP)) {
- ApplicationState appState = null;
- if (event.getType().equals(RMStateStoreEventType.STORE_APP)) {
- appState = ((RMStateStoreAppEvent) event).getAppState();
- } else {
- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP);
- appState = ((RMStateUpdateAppEvent) event).getAppState();
- }
-
- Exception storedException = null;
- ApplicationStateDataPBImpl appStateData =
- (ApplicationStateDataPBImpl) ApplicationStateDataPBImpl
- .newApplicationStateData(appState.getSubmitTime(),
- appState.getStartTime(), appState.getUser(),
- appState.getApplicationSubmissionContext(), appState.getState(),
- appState.getDiagnostics(), appState.getFinishTime());
-
- ApplicationId appId =
- appState.getApplicationSubmissionContext().getApplicationId();
-
- LOG.info("Storing info for app: " + appId);
- try {
- if (event.getType().equals(RMStateStoreEventType.STORE_APP)) {
- storeApplicationStateInternal(appId, appStateData);
- notifyDoneStoringApplication(appId, storedException);
- } else {
- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP);
- updateApplicationStateInternal(appId, appStateData);
- notifyDoneUpdatingApplication(appId, storedException);
- }
- } catch (Exception e) {
- LOG.error("Error storing/updating app: " + appId, e);
- notifyStoreOperationFailed(e);
- }
- } else if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT)
- || event.getType().equals(RMStateStoreEventType.UPDATE_APP_ATTEMPT)) {
-
- ApplicationAttemptState attemptState = null;
- if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT)) {
- attemptState =
- ((RMStateStoreAppAttemptEvent) event).getAppAttemptState();
- } else {
- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP_ATTEMPT);
- attemptState =
- ((RMStateUpdateAppAttemptEvent) event).getAppAttemptState();
- }
-
- Exception storedException = null;
- Credentials credentials = attemptState.getAppAttemptCredentials();
- ByteBuffer appAttemptTokens = null;
- try {
- if (credentials != null) {
- DataOutputBuffer dob = new DataOutputBuffer();
- credentials.writeTokenStorageToStream(dob);
- appAttemptTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
- }
- ApplicationAttemptStateDataPBImpl attemptStateData =
- (ApplicationAttemptStateDataPBImpl) ApplicationAttemptStateDataPBImpl
- .newApplicationAttemptStateData(attemptState.getAttemptId(),
- attemptState.getMasterContainer(), appAttemptTokens,
- attemptState.getStartTime(), attemptState.getState(),
- attemptState.getFinalTrackingUrl(),
- attemptState.getDiagnostics(),
- attemptState.getFinalApplicationStatus());
- if (LOG.isDebugEnabled()) {
- LOG.debug("Storing info for attempt: " + attemptState.getAttemptId());
- }
- if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT)) {
- storeApplicationAttemptStateInternal(attemptState.getAttemptId(),
- attemptStateData);
- notifyDoneStoringApplicationAttempt(attemptState.getAttemptId(),
- storedException);
- } else {
- assert event.getType().equals(
- RMStateStoreEventType.UPDATE_APP_ATTEMPT);
- updateApplicationAttemptStateInternal(attemptState.getAttemptId(),
- attemptStateData);
- notifyDoneUpdatingApplicationAttempt(attemptState.getAttemptId(),
- storedException);
- }
- } catch (Exception e) {
- LOG.error(
- "Error storing/updating appAttempt: " + attemptState.getAttemptId(), e);
- notifyStoreOperationFailed(e);
- }
- } else if (event.getType().equals(RMStateStoreEventType.REMOVE_APP)) {
- ApplicationState appState =
- ((RMStateStoreRemoveAppEvent) event).getAppState();
- ApplicationId appId = appState.getAppId();
- LOG.info("Removing info for app: " + appId);
- try {
- removeApplicationStateInternal(appState);
- } catch (Exception e) {
- LOG.error("Error removing app: " + appId, e);
- notifyStoreOperationFailed(e);
- }
- } else {
- LOG.error("Unknown RMStateStoreEvent type: " + event.getType());
+ try {
+ this.stateMachine.doTransition(event.getType(), event);
+ } catch (InvalidStateTransitonException e) {
+ LOG.error("Can't handle this event at current state", e);
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java
index 31c8885d4f2c9..63ae990732c24 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java
@@ -49,6 +49,8 @@
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMStateVersionProto;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
import org.apache.hadoop.yarn.server.resourcemanager.RMZKUtils;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
@@ -551,7 +553,7 @@ private void loadApplicationAttemptState(ApplicationState appState,
@Override
public synchronized void storeApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateDataPB) throws Exception {
+ ApplicationStateData appStateDataPB) throws Exception {
String nodeCreatePath = getNodePath(rmAppRoot, appId.toString());
if (LOG.isDebugEnabled()) {
@@ -565,7 +567,7 @@ public synchronized void storeApplicationStateInternal(ApplicationId appId,
@Override
public synchronized void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateDataPB) throws Exception {
+ ApplicationStateData appStateDataPB) throws Exception {
String nodeUpdatePath = getNodePath(rmAppRoot, appId.toString());
if (LOG.isDebugEnabled()) {
@@ -587,7 +589,7 @@ public synchronized void updateApplicationStateInternal(ApplicationId appId,
@Override
public synchronized void storeApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateDataPB)
+ ApplicationAttemptStateData attemptStateDataPB)
throws Exception {
String appDirPath = getNodePath(rmAppRoot,
appAttemptId.getApplicationId().toString());
@@ -605,7 +607,7 @@ public synchronized void storeApplicationAttemptStateInternal(
@Override
public synchronized void updateApplicationAttemptStateInternal(
ApplicationAttemptId appAttemptId,
- ApplicationAttemptStateDataPBImpl attemptStateDataPB)
+ ApplicationAttemptStateData attemptStateDataPB)
throws Exception {
String appIdStr = appAttemptId.getApplicationId().toString();
String appAttemptIdStr = appAttemptId.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/recovery/records/ApplicationAttemptStateData.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java
index 255800e86b2d9..6af048b2e3d2a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java
@@ -18,31 +18,73 @@
package org.apache.hadoop.yarn.server.resourcemanager.recovery.records;
+import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
+import org.apache.hadoop.io.DataOutputBuffer;
+import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
+import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProto;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
+import org.apache.hadoop.yarn.util.Records;
/*
* Contains the state data that needs to be persisted for an ApplicationAttempt
*/
@Public
@Unstable
-public interface ApplicationAttemptStateData {
-
+public abstract class ApplicationAttemptStateData {
+ public static ApplicationAttemptStateData newInstance(
+ ApplicationAttemptId attemptId, Container container,
+ ByteBuffer attemptTokens, long startTime, RMAppAttemptState finalState,
+ String finalTrackingUrl, String diagnostics,
+ FinalApplicationStatus amUnregisteredFinalStatus) {
+ ApplicationAttemptStateData attemptStateData =
+ Records.newRecord(ApplicationAttemptStateData.class);
+ attemptStateData.setAttemptId(attemptId);
+ attemptStateData.setMasterContainer(container);
+ attemptStateData.setAppAttemptTokens(attemptTokens);
+ attemptStateData.setState(finalState);
+ attemptStateData.setFinalTrackingUrl(finalTrackingUrl);
+ attemptStateData.setDiagnostics(diagnostics);
+ attemptStateData.setStartTime(startTime);
+ attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus);
+ return attemptStateData;
+ }
+
+ public static ApplicationAttemptStateData newInstance(
+ ApplicationAttemptState attemptState) throws IOException {
+ Credentials credentials = attemptState.getAppAttemptCredentials();
+ ByteBuffer appAttemptTokens = null;
+ if (credentials != null) {
+ DataOutputBuffer dob = new DataOutputBuffer();
+ credentials.writeTokenStorageToStream(dob);
+ appAttemptTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
+ }
+ return newInstance(attemptState.getAttemptId(),
+ attemptState.getMasterContainer(), appAttemptTokens,
+ attemptState.getStartTime(), attemptState.getState(),
+ attemptState.getFinalTrackingUrl(),
+ attemptState.getDiagnostics(),
+ attemptState.getFinalApplicationStatus());
+ }
+
+ public abstract ApplicationAttemptStateDataProto getProto();
+
/**
* The ApplicationAttemptId for the application attempt
* @return ApplicationAttemptId for the application attempt
*/
@Public
@Unstable
- public ApplicationAttemptId getAttemptId();
+ public abstract ApplicationAttemptId getAttemptId();
- public void setAttemptId(ApplicationAttemptId attemptId);
+ public abstract void setAttemptId(ApplicationAttemptId attemptId);
/*
* The master container running the application attempt
@@ -50,9 +92,9 @@ public interface ApplicationAttemptStateData {
*/
@Public
@Unstable
- public Container getMasterContainer();
+ public abstract Container getMasterContainer();
- public void setMasterContainer(Container container);
+ public abstract void setMasterContainer(Container container);
/**
* The application attempt tokens that belong to this attempt
@@ -60,17 +102,17 @@ public interface ApplicationAttemptStateData {
*/
@Public
@Unstable
- public ByteBuffer getAppAttemptTokens();
+ public abstract ByteBuffer getAppAttemptTokens();
- public void setAppAttemptTokens(ByteBuffer attemptTokens);
+ public abstract void setAppAttemptTokens(ByteBuffer attemptTokens);
/**
* Get the final state of the application attempt.
* @return the final state of the application attempt.
*/
- public RMAppAttemptState getState();
+ public abstract RMAppAttemptState getState();
- public void setState(RMAppAttemptState state);
+ public abstract void setState(RMAppAttemptState state);
/**
* Get the original not-proxied <em>final tracking url</em> for the
@@ -79,34 +121,34 @@ public interface ApplicationAttemptStateData {
* @return the original not-proxied <em>final tracking url</em> for the
* application
*/
- public String getFinalTrackingUrl();
+ public abstract String getFinalTrackingUrl();
/**
* Set the final tracking Url of the AM.
* @param url
*/
- public void setFinalTrackingUrl(String url);
+ public abstract void setFinalTrackingUrl(String url);
/**
* Get the <em>diagnositic information</em> of the attempt
* @return <em>diagnositic information</em> of the attempt
*/
- public String getDiagnostics();
+ public abstract String getDiagnostics();
- public void setDiagnostics(String diagnostics);
+ public abstract void setDiagnostics(String diagnostics);
/**
* Get the <em>start time</em> of the application.
* @return <em>start time</em> of the application
*/
- public long getStartTime();
+ public abstract long getStartTime();
- public void setStartTime(long startTime);
+ public abstract void setStartTime(long startTime);
/**
* Get the <em>final finish status</em> of the application.
* @return <em>final finish status</em> of the application
*/
- public FinalApplicationStatus getFinalApplicationStatus();
+ public abstract FinalApplicationStatus getFinalApplicationStatus();
- public void setFinalApplicationStatus(FinalApplicationStatus finishState);
+ public abstract void setFinalApplicationStatus(FinalApplicationStatus finishState);
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java
index 9fce6cf12d068..55b726ffd0da8 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java
@@ -24,7 +24,10 @@
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
+import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
+import org.apache.hadoop.yarn.util.Records;
/**
* Contains all the state data that needs to be stored persistently
@@ -32,19 +35,43 @@
*/
@Public
@Unstable
-public interface ApplicationStateData {
-
+public abstract class ApplicationStateData {
+ public static ApplicationStateData newInstance(long submitTime,
+ long startTime, String user,
+ ApplicationSubmissionContext submissionContext,
+ RMAppState state, String diagnostics, long finishTime) {
+ ApplicationStateData appState = Records.newRecord(ApplicationStateData.class);
+ appState.setSubmitTime(submitTime);
+ appState.setStartTime(startTime);
+ appState.setUser(user);
+ appState.setApplicationSubmissionContext(submissionContext);
+ appState.setState(state);
+ appState.setDiagnostics(diagnostics);
+ appState.setFinishTime(finishTime);
+ return appState;
+ }
+
+ public static ApplicationStateData newInstance(
+ ApplicationState appState) {
+ return newInstance(appState.getSubmitTime(), appState.getStartTime(),
+ appState.getUser(), appState.getApplicationSubmissionContext(),
+ appState.getState(), appState.getDiagnostics(),
+ appState.getFinishTime());
+ }
+
+ public abstract ApplicationStateDataProto getProto();
+
/**
* The time at which the application was received by the Resource Manager
* @return submitTime
*/
@Public
@Unstable
- public long getSubmitTime();
+ public abstract long getSubmitTime();
@Public
@Unstable
- public void setSubmitTime(long submitTime);
+ public abstract void setSubmitTime(long submitTime);
/**
* Get the <em>start time</em> of the application.
@@ -63,11 +90,11 @@ public interface ApplicationStateData {
*/
@Public
@Unstable
- public void setUser(String user);
+ public abstract void setUser(String user);
@Public
@Unstable
- public String getUser();
+ public abstract String getUser();
/**
* The {@link ApplicationSubmissionContext} for the application
@@ -76,34 +103,34 @@ public interface ApplicationStateData {
*/
@Public
@Unstable
- public ApplicationSubmissionContext getApplicationSubmissionContext();
+ public abstract ApplicationSubmissionContext getApplicationSubmissionContext();
@Public
@Unstable
- public void setApplicationSubmissionContext(
+ public abstract void setApplicationSubmissionContext(
ApplicationSubmissionContext context);
/**
* Get the final state of the application.
* @return the final state of the application.
*/
- public RMAppState getState();
+ public abstract RMAppState getState();
- public void setState(RMAppState state);
+ public abstract void setState(RMAppState state);
/**
* Get the diagnostics information for the application master.
* @return the diagnostics information for the application master.
*/
- public String getDiagnostics();
+ public abstract String getDiagnostics();
- public void setDiagnostics(String diagnostics);
+ public abstract void setDiagnostics(String diagnostics);
/**
* The finish time of the application.
* @return the finish time of the application.,
*/
- public long getFinishTime();
+ public abstract long getFinishTime();
- public void setFinishTime(long finishTime);
+ public abstract void setFinishTime(long finishTime);
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java
index 75ac2eef9a737..e3ebe5e08936c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java
@@ -25,10 +25,7 @@
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationAttemptIdPBImpl;
import org.apache.hadoop.yarn.api.records.impl.pb.ContainerPBImpl;
-import org.apache.hadoop.yarn.api.records.impl.pb.ProtoBase;
import org.apache.hadoop.yarn.api.records.impl.pb.ProtoUtils;
-import org.apache.hadoop.yarn.factories.RecordFactory;
-import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.proto.YarnProtos.FinalApplicationStatusProto;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProto;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProtoOrBuilder;
@@ -36,12 +33,10 @@
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
-public class ApplicationAttemptStateDataPBImpl
-extends ProtoBase<ApplicationAttemptStateDataProto>
-implements ApplicationAttemptStateData {
- private static final RecordFactory recordFactory = RecordFactoryProvider
- .getRecordFactory(null);
+import com.google.protobuf.TextFormat;
+public class ApplicationAttemptStateDataPBImpl extends
+ ApplicationAttemptStateData {
ApplicationAttemptStateDataProto proto =
ApplicationAttemptStateDataProto.getDefaultInstance();
ApplicationAttemptStateDataProto.Builder builder = null;
@@ -60,7 +55,8 @@ public ApplicationAttemptStateDataPBImpl(
this.proto = proto;
viaProto = true;
}
-
+
+ @Override
public ApplicationAttemptStateDataProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
@@ -76,7 +72,8 @@ private void mergeLocalToBuilder() {
builder.setMasterContainer(((ContainerPBImpl)masterContainer).getProto());
}
if(this.appAttemptTokens != null) {
- builder.setAppAttemptTokens(convertToProtoFormat(this.appAttemptTokens));
+ builder.setAppAttemptTokens(ProtoUtils.convertToProtoFormat(
+ this.appAttemptTokens));
}
}
@@ -148,7 +145,8 @@ public ByteBuffer getAppAttemptTokens() {
if(!p.hasAppAttemptTokens()) {
return null;
}
- this.appAttemptTokens = convertFromProtoFormat(p.getAppAttemptTokens());
+ this.appAttemptTokens = ProtoUtils.convertFromProtoFormat(
+ p.getAppAttemptTokens());
return appAttemptTokens;
}
@@ -249,24 +247,26 @@ public void setFinalApplicationStatus(FinalApplicationStatus finishState) {
builder.setFinalApplicationStatus(convertToProtoFormat(finishState));
}
- public static ApplicationAttemptStateData newApplicationAttemptStateData(
- ApplicationAttemptId attemptId, Container container,
- ByteBuffer attemptTokens, long startTime, RMAppAttemptState finalState,
- String finalTrackingUrl, String diagnostics,
- FinalApplicationStatus amUnregisteredFinalStatus) {
- ApplicationAttemptStateData attemptStateData =
- recordFactory.newRecordInstance(ApplicationAttemptStateData.class);
- attemptStateData.setAttemptId(attemptId);
- attemptStateData.setMasterContainer(container);
- attemptStateData.setAppAttemptTokens(attemptTokens);
- attemptStateData.setState(finalState);
- attemptStateData.setFinalTrackingUrl(finalTrackingUrl);
- attemptStateData.setDiagnostics(diagnostics);
- attemptStateData.setStartTime(startTime);
- attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus);
- return attemptStateData;
+ @Override
+ public int hashCode() {
+ return getProto().hashCode();
}
+ @Override
+ public boolean equals(Object other) {
+ if (other == null)
+ return false;
+ if (other.getClass().isAssignableFrom(this.getClass())) {
+ return this.getProto().equals(this.getClass().cast(other).getProto());
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return TextFormat.shortDebugString(getProto());
+ }
+
private static String RM_APP_ATTEMPT_PREFIX = "RMATTEMPT_";
public static RMAppAttemptStateProto convertToProtoFormat(RMAppAttemptState e) {
return RMAppAttemptStateProto.valueOf(RM_APP_ATTEMPT_PREFIX + e.name());
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java
index ede8ca7c46155..8aaf1a4a7caf6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java
@@ -20,21 +20,15 @@
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl;
-import org.apache.hadoop.yarn.api.records.impl.pb.ProtoBase;
-import org.apache.hadoop.yarn.factories.RecordFactory;
-import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProtoOrBuilder;
import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMAppStateProto;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
-public class ApplicationStateDataPBImpl
-extends ProtoBase<ApplicationStateDataProto>
-implements ApplicationStateData {
- private static final RecordFactory recordFactory = RecordFactoryProvider
- .getRecordFactory(null);
+import com.google.protobuf.TextFormat;
+public class ApplicationStateDataPBImpl extends ApplicationStateData {
ApplicationStateDataProto proto =
ApplicationStateDataProto.getDefaultInstance();
ApplicationStateDataProto.Builder builder = null;
@@ -51,7 +45,8 @@ public ApplicationStateDataPBImpl(
this.proto = proto;
viaProto = true;
}
-
+
+ @Override
public ApplicationStateDataProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
@@ -136,7 +131,7 @@ public ApplicationSubmissionContext getApplicationSubmissionContext() {
}
applicationSubmissionContext =
new ApplicationSubmissionContextPBImpl(
- p.getApplicationSubmissionContext());
+ p.getApplicationSubmissionContext());
return applicationSubmissionContext;
}
@@ -200,21 +195,24 @@ public void setFinishTime(long finishTime) {
builder.setFinishTime(finishTime);
}
- public static ApplicationStateData newApplicationStateData(long submitTime,
- long startTime, String user,
- ApplicationSubmissionContext submissionContext, RMAppState state,
- String diagnostics, long finishTime) {
-
- ApplicationStateData appState =
- recordFactory.newRecordInstance(ApplicationStateData.class);
- appState.setSubmitTime(submitTime);
- appState.setStartTime(startTime);
- appState.setUser(user);
- appState.setApplicationSubmissionContext(submissionContext);
- appState.setState(state);
- appState.setDiagnostics(diagnostics);
- appState.setFinishTime(finishTime);
- return appState;
+ @Override
+ public int hashCode() {
+ return getProto().hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == null)
+ return false;
+ if (other.getClass().isAssignableFrom(this.getClass())) {
+ return this.getProto().equals(this.getClass().cast(other).getProto());
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return TextFormat.shortDebugString(getProto());
}
private static String RM_APP_PREFIX = "RMAPP_";
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java
index 3bdb66c4b407c..9c2d87e444250 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java
@@ -84,8 +84,8 @@
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationState;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreEvent;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl;
-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
@@ -612,7 +612,7 @@ public void testRMRestartWaitForPreviousSucceededAttempt() throws Exception {
@Override
public void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception {
+ ApplicationStateData appStateData) throws Exception {
if (count == 0) {
// do nothing; simulate app final state is not saved.
LOG.info(appId + " final state is not saved.");
@@ -760,14 +760,14 @@ public void testRMRestartKilledAppWithNoAttempts() throws Exception {
@Override
public synchronized void storeApplicationAttemptStateInternal(
ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception {
+ ApplicationAttemptStateData attemptStateData) throws Exception {
// ignore attempt saving request.
}
@Override
public synchronized void updateApplicationAttemptStateInternal(
ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception {
+ ApplicationAttemptStateData attemptStateData) throws Exception {
// ignore attempt saving request.
}
};
@@ -1862,7 +1862,7 @@ public class TestMemoryRMStateStore extends MemoryRMStateStore {
@Override
public void updateApplicationStateInternal(ApplicationId appId,
- ApplicationStateDataPBImpl appStateData) throws Exception {
+ ApplicationStateData appStateData) throws Exception {
updateApp = ++count;
super.updateApplicationStateInternal(appId, appStateData);
}
@@ -1871,7 +1871,7 @@ public void updateApplicationStateInternal(ApplicationId appId,
public synchronized void
updateApplicationAttemptStateInternal(
ApplicationAttemptId attemptId,
- ApplicationAttemptStateDataPBImpl attemptStateData)
+ ApplicationAttemptStateData attemptStateData)
throws Exception {
updateAttempt = ++count;
super.updateApplicationAttemptStateInternal(attemptId,
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java
index 792b73e5a6648..da25c5beda6ad 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java
@@ -24,7 +24,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Assert;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
@@ -37,6 +36,7 @@
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.RMStateVersionPBImpl;
@@ -213,9 +213,8 @@ public void run() {
try {
store.storeApplicationStateInternal(
ApplicationId.newInstance(100L, 1),
- (ApplicationStateDataPBImpl) ApplicationStateDataPBImpl
- .newApplicationStateData(111, 111, "user", null,
- RMAppState.ACCEPTED, "diagnostics", 333));
+ ApplicationStateData.newInstance(111, 111, "user", null,
+ RMAppState.ACCEPTED, "diagnostics", 333));
} catch (Exception e) {
// TODO 0 datanode exception will not be retried by dfs client, fix
// that separately.
|
c5b22e0f974d267b11ba5b3d0b9a1f1ce73fc465
|
intellij-community
|
Improved align behavior to align only- subsequent assignments or hashes--
|
p
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/formatting/alignment/AlignmentStrategy.java b/platform/lang-impl/src/com/intellij/formatting/alignment/AlignmentStrategy.java
index 10186d5c11c12..7d18afe45ff8b 100644
--- a/platform/lang-impl/src/com/intellij/formatting/alignment/AlignmentStrategy.java
+++ b/platform/lang-impl/src/com/intellij/formatting/alignment/AlignmentStrategy.java
@@ -71,7 +71,7 @@ public static AlignmentStrategy wrap(Alignment alignment, IElementType ... types
* of <code>'int finish = 1'</code> statement)
* @return alignment retrieval strategy that follows the rules described above
*/
- public static AlignmentStrategy createAlignmentPerTypeStrategy(Collection<IElementType> targetTypes, boolean allowBackwardShift) {
+ public static AlignmentPerTypeStrategy createAlignmentPerTypeStrategy(Collection<IElementType> targetTypes, boolean allowBackwardShift) {
return new AlignmentPerTypeStrategy(targetTypes, allowBackwardShift);
}
@@ -102,13 +102,15 @@ public Alignment getAlignment(IElementType elementType) {
* Alignment strategy that creates and caches alignments for target element types and returns them for elements with the
* same types.
*/
- private static class AlignmentPerTypeStrategy extends AlignmentStrategy {
+ public static class AlignmentPerTypeStrategy extends AlignmentStrategy {
private final Map<IElementType, Alignment> myAlignments = new HashMap<IElementType, Alignment>();
+ private final boolean myAllowBackwardShift;
AlignmentPerTypeStrategy(Collection<IElementType> targetElementTypes, boolean allowBackwardShift) {
+ myAllowBackwardShift = allowBackwardShift;
for (IElementType elementType : targetElementTypes) {
- myAlignments.put(elementType, Alignment.createAlignment(allowBackwardShift));
+ myAlignments.put(elementType, Alignment.createAlignment(myAllowBackwardShift));
}
}
@@ -116,5 +118,9 @@ private static class AlignmentPerTypeStrategy extends AlignmentStrategy {
public Alignment getAlignment(IElementType elementType) {
return myAlignments.get(elementType);
}
+
+ public void renewAlignment(IElementType elementType) {
+ myAlignments.put(elementType, Alignment.createAlignment(myAllowBackwardShift));
+ }
}
}
\ No newline at end of file
|
3a1f3532a00319879013c4b219255da0991c7959
|
kotlin
|
Reporting real source file paths from K2JS- compiler--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
index f3b7f649ecf75..163ab77d5a05e 100644
--- a/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
+++ b/compiler/cli/src/org/jetbrains/jet/cli/js/K2JSCompiler.java
@@ -23,6 +23,7 @@
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import jet.Function0;
import org.jetbrains.annotations.NotNull;
@@ -109,12 +110,11 @@ private static void reportCompiledSourcesList(@NotNull PrintingMessageCollector
@Override
public String apply(@Nullable JetFile file) {
assert file != null;
- String packageName = file.getPackageName();
- if (packageName != null && packageName.length() > 0) {
- return packageName + "." + file.getName();
- } else {
- return file.getName();
+ VirtualFile virtualFile = file.getVirtualFile();
+ if (virtualFile != null) {
+ return virtualFile.getPath();
}
+ return file.getName() + "(no virtual file)";
}
});
messageCollector.report(CompilerMessageSeverity.LOGGING, "Compiling source files: " + Joiner.on(", ").join(fileNames),
|
52c58115d2a0b97908bacdd7fb6a78a6b6cf3e83
|
hadoop
|
YARN-2798. Fixed YarnClient to populate the renewer- correctly for Timeline delegation tokens. Contributed by Zhijie Shen.--(cherry picked from commit 71fbb474f531f60c5d908cf724f18f90dfd5fa9f)-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 56359e5b00736..5e2a1c2b1ae3b 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -812,6 +812,9 @@ Release 2.6.0 - UNRELEASED
YARN-2730. DefaultContainerExecutor runs only one localizer at a time
(Siqi Li via jlowe)
+ YARN-2798. Fixed YarnClient to populate the renewer correctly for Timeline
+ delegation tokens. (Zhijie Shen via vinodkv)
+
Release 2.5.1 - 2014-09-05
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java
index 1193cb4c8b49e..e4f31f20d848c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java
@@ -36,7 +36,7 @@
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.security.Credentials;
-import org.apache.hadoop.security.HadoopKerberosName;
+import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
@@ -51,7 +51,6 @@
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsRequest;
-import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodeLabelsResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesResponse;
import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest;
@@ -124,6 +123,8 @@ public class YarnClientImpl extends YarnClient {
protected TimelineClient timelineClient;
@VisibleForTesting
Text timelineService;
+ @VisibleForTesting
+ String timelineDTRenewer;
protected boolean timelineServiceEnabled;
private static final String ROOT = "root";
@@ -161,6 +162,7 @@ protected void serviceInit(Configuration conf) throws Exception {
timelineServiceEnabled = true;
timelineClient = TimelineClient.createTimelineClient();
timelineClient.init(conf);
+ timelineDTRenewer = getTimelineDelegationTokenRenewer(conf);
timelineService = TimelineUtils.buildTimelineTokenService(conf);
}
super.serviceInit(conf);
@@ -320,14 +322,22 @@ private void addTimelineDelegationToken(
@VisibleForTesting
org.apache.hadoop.security.token.Token<TimelineDelegationTokenIdentifier>
getTimelineDelegationToken() throws IOException, YarnException {
+ return timelineClient.getDelegationToken(timelineDTRenewer);
+ }
+
+ private static String getTimelineDelegationTokenRenewer(Configuration conf)
+ throws IOException, YarnException {
// Parse the RM daemon user if it exists in the config
- String rmPrincipal = getConfig().get(YarnConfiguration.RM_PRINCIPAL);
+ String rmPrincipal = conf.get(YarnConfiguration.RM_PRINCIPAL);
String renewer = null;
if (rmPrincipal != null && rmPrincipal.length() > 0) {
- HadoopKerberosName renewerKrbName = new HadoopKerberosName(rmPrincipal);
- renewer = renewerKrbName.getShortName();
+ String rmHost = conf.getSocketAddr(
+ YarnConfiguration.RM_ADDRESS,
+ YarnConfiguration.DEFAULT_RM_ADDRESS,
+ YarnConfiguration.DEFAULT_RM_PORT).getHostName();
+ renewer = SecurityUtil.getServerPrincipal(rmPrincipal, rmHost);
}
- return timelineClient.getDelegationToken(renewer);
+ return renewer;
}
@Private
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java
index d7bea7a8d0a7a..ca7c50a1270af 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java
@@ -852,7 +852,25 @@ public boolean isSecurityEnabled() {
client.stop();
}
}
-
+
+ @Test
+ public void testParseTimelineDelegationTokenRenewer() throws Exception {
+ // Client side
+ YarnClientImpl client = (YarnClientImpl) YarnClient.createYarnClient();
+ Configuration conf = new YarnConfiguration();
+ conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
+ conf.set(YarnConfiguration.RM_PRINCIPAL, "rm/[email protected]");
+ conf.set(
+ YarnConfiguration.RM_ADDRESS, "localhost:8188");
+ try {
+ client.init(conf);
+ client.start();
+ Assert.assertEquals("rm/[email protected]", client.timelineDTRenewer);
+ } finally {
+ client.stop();
+ }
+ }
+
@Test
public void testReservationAPIs() {
// initialize
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/security/TestYARNTokenIdentifier.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/security/TestYARNTokenIdentifier.java
index 2052c23159827..dc4f9e2a41dd8 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/security/TestYARNTokenIdentifier.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/security/TestYARNTokenIdentifier.java
@@ -19,14 +19,18 @@
import java.io.IOException;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.Text;
+import org.apache.hadoop.security.HadoopKerberosName;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier;
import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier;
import org.apache.hadoop.yarn.security.client.TimelineDelegationTokenIdentifier;
@@ -299,4 +303,19 @@ public void testTimelineDelegationTokenIdentifier() throws IOException {
anotherToken.getMasterKeyId(), masterKeyId);
}
+ @Test
+ public void testParseTimelineDelegationTokenIdentifierRenewer() throws IOException {
+ // Server side when generation a timeline DT
+ Configuration conf = new YarnConfiguration();
+ conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTH_TO_LOCAL,
+ "RULE:[2:$1@$0]([nr]m@.*EXAMPLE.COM)s/.*/yarn/");
+ HadoopKerberosName.setConfiguration(conf);
+ Text owner = new Text("owner");
+ Text renewer = new Text("rm/[email protected]");
+ Text realUser = new Text("realUser");
+ TimelineDelegationTokenIdentifier token =
+ new TimelineDelegationTokenIdentifier(owner, renewer, realUser);
+ Assert.assertEquals(new Text("yarn"), token.getRenewer());
+ }
+
}
|
304215665eb630a9c3e722d789e882bf9f59ab21
|
orientdb
|
Fixed issue 800 closing the socket on timeout--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
index adf2bc9ebcf..819195b2761 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
@@ -56,6 +56,10 @@ public void run() {
if (socket == null || socket.isClosed() || socket.isInputShutdown()) {
OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)",
entry.getKey(), socket);
+ try {
+ entry.getValue().close();
+ } catch (Exception e) {
+ }
connections.remove(entry.getKey());
}
}
|
f537b8cceefa694e895dfaa43722ce6b4283948a
|
elasticsearch
|
Change default operator to "or" for- "low_freq_operator" and "high_freq_operator" parameters for "common" queries--Closes -3178-
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/index/query/CommonTermsQueryParser.java b/src/main/java/org/elasticsearch/index/query/CommonTermsQueryParser.java
index 94334f3652278..621f39aaf9ccf 100644
--- a/src/main/java/org/elasticsearch/index/query/CommonTermsQueryParser.java
+++ b/src/main/java/org/elasticsearch/index/query/CommonTermsQueryParser.java
@@ -51,9 +51,9 @@ public class CommonTermsQueryParser implements QueryParser {
static final float DEFAULT_MAX_TERM_DOC_FREQ = 0.01f;
- static final Occur DEFAULT_HIGH_FREQ_OCCUR = Occur.MUST;
+ static final Occur DEFAULT_HIGH_FREQ_OCCUR = Occur.SHOULD;
- static final Occur DEFAULT_LOW_FREQ_OCCUR = Occur.MUST;
+ static final Occur DEFAULT_LOW_FREQ_OCCUR = Occur.SHOULD;
static final boolean DEFAULT_DISABLE_COORDS = true;
@@ -81,7 +81,7 @@ public Query parse(QueryParseContext parseContext) throws IOException, QueryPars
String minimumShouldMatch = null;
boolean disableCoords = DEFAULT_DISABLE_COORDS;
Occur highFreqOccur = DEFAULT_HIGH_FREQ_OCCUR;
- Occur lowFreqOccur = DEFAULT_HIGH_FREQ_OCCUR;
+ Occur lowFreqOccur = DEFAULT_LOW_FREQ_OCCUR;
float maxTermFrequency = DEFAULT_MAX_TERM_DOC_FREQ;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
@@ -202,4 +202,4 @@ private final Query parseQueryString(ExtendedCommonTermsQuery query, String quer
query.setMinimumNumberShouldMatch(minimumShouldMatch);
return wrapSmartNameQuery(query, smartNameFieldMappers, parseContext);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/org/elasticsearch/test/integration/search/query/SimpleQueryTests.java b/src/test/java/org/elasticsearch/test/integration/search/query/SimpleQueryTests.java
index 13eec4906c733..0f306cbfe7aff 100644
--- a/src/test/java/org/elasticsearch/test/integration/search/query/SimpleQueryTests.java
+++ b/src/test/java/org/elasticsearch/test/integration/search/query/SimpleQueryTests.java
@@ -127,13 +127,19 @@ public void testCommonTermsQuery() throws Exception {
client().prepareIndex("test", "type1", "2").setSource("field1", "the quick lazy huge brown fox jumps over the tree").execute().actionGet();
client().prepareIndex("test", "type1", "3").setSource("field1", "quick lazy huge brown", "field2", "the quick lazy huge brown fox jumps over the tree").setRefresh(true).execute().actionGet();
- SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3)).execute().actionGet();
- assertThat(searchResponse.getHits().totalHits(), equalTo(2l));
+ SearchResponse searchResponse = client().prepareSearch().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.OR)).execute().actionGet();
+ assertThat(searchResponse.getHits().totalHits(), equalTo(3l));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
+ assertThat(searchResponse.getHits().getHits()[2].getId(), equalTo("3"));
+ searchResponse = client().prepareSearch().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.AND)).execute().actionGet();
+ assertThat(searchResponse.getHits().totalHits(), equalTo(2l));
+ assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
+ assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
- searchResponse = client().prepareSearch().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3).lowFreqOperator(Operator.OR)).execute().actionGet();
+ // Default
+ searchResponse = client().prepareSearch().setQuery(QueryBuilders.commonTerms("field1", "the quick brown").cutoffFrequency(3)).execute().actionGet();
assertThat(searchResponse.getHits().totalHits(), equalTo(3l));
assertThat(searchResponse.getHits().getHits()[0].getId(), equalTo("1"));
assertThat(searchResponse.getHits().getHits()[1].getId(), equalTo("2"));
|
87498b148f1a29f9538dbdb3728cdc95af7dd1a1
|
restlet-framework-java
|
Allowed custom parsing of Atom documents.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF b/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF
index dc50b71c86..97a60d74b3 100644
--- a/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF
+++ b/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF
@@ -4,8 +4,15 @@ Bundle-Name: Restlet Extension - Atom
Bundle-SymbolicName: org.restlet.ext.atom
Bundle-Version: 2.0
Bundle-Vendor: Noelios Technologies
-Export-Package: org.restlet.ext.atom,
- org.restlet.ext.atom.internal
+Export-Package: org.restlet.ext.atom;
+ uses:="org.restlet.data,
+ org.restlet.resource,
+ org.restlet.ext.xml,
+ org.restlet.engine.converter,
+ org.restlet.representation,
+ org.restlet.ext.atom.contentHandler,
+ org.restlet",
+ org.restlet.ext.atom.contentHandler;uses:="org.restlet.ext.atom,org.xml.sax.helpers,org.xml.sax"
Import-Package: org.restlet,
org.restlet.data,
org.restlet.engine.converter,
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java
index cf79d995ca..508c3a54d8 100644
--- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java
@@ -43,6 +43,7 @@
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.engine.util.DateUtils;
+import org.restlet.ext.atom.contentHandler.EntryReader;
import org.restlet.ext.atom.internal.EntryContentReader;
import org.restlet.ext.xml.SaxRepresentation;
import org.restlet.ext.xml.XmlWriter;
@@ -72,9 +73,6 @@ public class Entry extends SaxRepresentation {
/** Permanent, universally unique identifier for the entry. */
private volatile String id;
- /** Representation for inline content. */
- private volatile Representation inlineContent;
-
/** The references from the entry to Web resources. */
private volatile List<Link> links;
@@ -95,7 +93,7 @@ public class Entry extends SaxRepresentation {
/** Most recent moment when the entry was modified in a significant way. */
private volatile Date updated;
-
+
/**
* Constructor.
*/
@@ -114,6 +112,7 @@ public Entry() {
this.title = null;
this.updated = null;
}
+
/**
* Constructor.
*
@@ -126,6 +125,7 @@ public Entry() {
public Entry(Client clientDispatcher, String entryUri) throws IOException {
this(clientDispatcher.get(entryUri).getEntity());
}
+
/**
* Constructor.
*
@@ -152,6 +152,21 @@ public Entry(Representation xmlEntry) throws IOException {
parse(new EntryContentReader(this));
}
+ /**
+ * Constructor.
+ *
+ * @param xmlEntry
+ * The XML entry document.
+ * @param entryReader
+ * Custom entry reader.
+ * @throws IOException
+ */
+ public Entry(Representation xmlEntry, EntryReader entryReader)
+ throws IOException {
+ super(xmlEntry);
+ parse(new EntryContentReader(this, entryReader));
+ }
+
/**
* Constructor.
*
@@ -238,15 +253,6 @@ public String getId() {
return this.id;
}
- /**
- * Returns the representation for inline content.
- *
- * @return The representation for inline content.
- */
- public Representation getInlineContent() {
- return this.inlineContent;
- }
-
/**
* Returns the first available link with a given relation type.
*
@@ -369,16 +375,6 @@ public void setId(String id) {
this.id = id;
}
- /**
- * Sets the representation for inline content.
- *
- * @param inlineContent
- * The representation for inline content.
- */
- public void setInlineContent(Representation inlineContent) {
- this.inlineContent = inlineContent;
- }
-
/**
* Sets the moment associated with an event early in the life cycle of the
* entry.
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java
index 6d1f6af47f..de7d592b52 100644
--- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java
@@ -40,13 +40,13 @@
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.engine.util.DateUtils;
+import org.restlet.ext.atom.contentHandler.FeedReader;
import org.restlet.ext.atom.internal.FeedContentReader;
import org.restlet.ext.xml.SaxRepresentation;
import org.restlet.ext.xml.XmlWriter;
import org.restlet.representation.Representation;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
-import org.xml.sax.helpers.DefaultHandler;
/**
* Atom Feed Document, acting as a component for metadata and data associated
@@ -173,12 +173,14 @@ public Feed(Representation xmlFeed) throws IOException {
*
* @param xmlFeed
* The XML feed document.
+ * @param feedReader
+ * Custom feed reader.
* @throws IOException
*/
- public Feed(Representation xmlFeed, DefaultHandler extraFeedHandler,
- DefaultHandler extraEntryHandler) throws IOException {
+ public Feed(Representation xmlFeed, FeedReader feedReader)
+ throws IOException {
super(xmlFeed);
- parse(new FeedContentReader(this, extraFeedHandler, extraEntryHandler));
+ parse(new FeedContentReader(this, feedReader));
}
/**
@@ -374,18 +376,6 @@ public Date getUpdated() {
return this.updated;
}
- /**
- * Sets the base URI used to resolve relative references found within the
- * scope of the xml:base attribute.
- *
- * @param baseUri
- * The base URI used to resolve relative references found within
- * the scope of the xml:base attribute.
- */
- public void setBaseReference(String baseUri) {
- setBaseReference(new Reference(baseUri));
- }
-
/**
* Sets the base reference used to resolve relative references found within
* the scope of the xml:base attribute.
@@ -398,6 +388,18 @@ public void setBaseReference(Reference baseReference) {
this.baseReference = baseReference;
}
+ /**
+ * Sets the base URI used to resolve relative references found within the
+ * scope of the xml:base attribute.
+ *
+ * @param baseUri
+ * The base URI used to resolve relative references found within
+ * the scope of the xml:base attribute.
+ */
+ public void setBaseReference(String baseUri) {
+ setBaseReference(new Reference(baseUri));
+ }
+
/**
* Sets the agent used to generate a feed.
*
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java
new file mode 100644
index 0000000000..d89a38f852
--- /dev/null
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java
@@ -0,0 +1,299 @@
+/**
+ * Copyright 2005-2010 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or CDL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
+package org.restlet.ext.atom.contentHandler;
+
+import java.io.IOException;
+
+import org.restlet.ext.atom.Content;
+import org.restlet.ext.atom.Entry;
+import org.restlet.ext.atom.Link;
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * Content reader for entries that is able to transmit events to another
+ * EntryReader.
+ *
+ * @author Thierry Boileau
+ */
+public class EntryReader extends DefaultHandler {
+
+ /** Extra entry reader. */
+ private EntryReader entryReader;
+
+ /**
+ * Constructor.
+ */
+ public EntryReader() {
+ super();
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param entryReader
+ * Additional feed reader that will receive all events.
+ */
+ public EntryReader(EntryReader entryReader) {
+ super();
+ this.entryReader = entryReader;
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.characters(ch, start, length);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given content
+ * element. By default, it relays the event to the extra handler.
+ *
+ * @param content
+ * The current content element.
+ */
+ public void endContent(Content content) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endContent(content);
+ }
+ }
+
+ @Override
+ public void endDocument() throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endDocument();
+ }
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endElement(uri, localName, qName);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given entry.
+ *
+ * @param entry
+ * The current entry.
+ */
+ public void endEntry(Entry entry) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endEntry(entry);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given link.
+ *
+ * @param link
+ * The current link.
+ */
+ public void endLink(Link link) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endLink(link);
+ }
+ }
+
+ @Override
+ public void endPrefixMapping(String prefix) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.endPrefixMapping(prefix);
+ }
+ }
+
+ @Override
+ public void error(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.error(e);
+ }
+ }
+
+ @Override
+ public void fatalError(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.fatalError(e);
+ }
+ }
+
+ @Override
+ public void ignorableWhitespace(char[] ch, int start, int length)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.ignorableWhitespace(ch, start, length);
+ }
+ }
+
+ @Override
+ public void notationDecl(String name, String publicId, String systemId)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.notationDecl(name, publicId, systemId);
+ }
+ }
+
+ @Override
+ public void processingInstruction(String target, String data)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.processingInstruction(target, data);
+ }
+ }
+
+ @Override
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws IOException, SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ return this.entryReader.resolveEntity(publicId, systemId);
+ }
+ return null;
+ }
+
+ @Override
+ public void setDocumentLocator(Locator locator) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.setDocumentLocator(locator);
+ }
+ }
+
+ @Override
+ public void skippedEntity(String name) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.skippedEntity(name);
+ }
+ }
+
+ /**
+ * Called when a new content element has been detected in the Atom document.
+ *
+ * @param content
+ * The current content element.
+ */
+ public void startContent(Content content) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startContent(content);
+ }
+ }
+
+ @Override
+ public void startDocument() throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startDocument();
+ }
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startElement(uri, localName, qName, attributes);
+ }
+ }
+
+ /**
+ * Called when a new entry has been detected in the Atom document.
+ *
+ * @param entry
+ * The current entry.
+ */
+ public void startEntry(Entry entry) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startEntry(entry);
+ }
+ }
+
+ /**
+ * Called when a new link has been detected in the Atom document.
+ *
+ * @param link
+ * The current link.
+ */
+ public void startLink(Link link) {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startLink(link);
+ }
+ }
+
+ @Override
+ public void startPrefixMapping(String prefix, String uri)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.startPrefixMapping(prefix, uri);
+ }
+ }
+
+ @Override
+ public void unparsedEntityDecl(String name, String publicId,
+ String systemId, String notationName) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.unparsedEntityDecl(name, publicId, systemId,
+ notationName);
+ }
+ }
+
+ @Override
+ public void warning(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.entryReader != null) {
+ this.entryReader.warning(e);
+ }
+ }
+}
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java
new file mode 100644
index 0000000000..3e59c101a1
--- /dev/null
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java
@@ -0,0 +1,326 @@
+/**
+ * Copyright 2005-2010 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or CDL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
+package org.restlet.ext.atom.contentHandler;
+
+import java.io.IOException;
+
+import org.restlet.ext.atom.Content;
+import org.restlet.ext.atom.Entry;
+import org.restlet.ext.atom.Feed;
+import org.restlet.ext.atom.Link;
+import org.xml.sax.Attributes;
+import org.xml.sax.InputSource;
+import org.xml.sax.Locator;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * Content reader for feeds that is able to transmit events to another
+ * FeedReader.
+ *
+ * @author Thierry Boileau
+ */
+public class FeedReader extends DefaultHandler {
+
+ /** Extra feed reader. */
+ private FeedReader feedReader;
+
+ /**
+ * Constructor.
+ */
+ public FeedReader() {
+ super();
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param feedReader
+ * Additional feed reader that will receive all events.
+ */
+ public FeedReader(FeedReader feedReader) {
+ super();
+ this.feedReader = feedReader;
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.characters(ch, start, length);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given content
+ * element. By default, it relays the event to the extra handler.
+ *
+ * @param content
+ * The current content element.
+ */
+ public void endContent(Content content) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endContent(content);
+ }
+ }
+
+ @Override
+ public void endDocument() throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endDocument();
+ }
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String qName)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endElement(uri, localName, qName);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given entry.
+ *
+ * @param entry
+ * The current entry.
+ */
+ public void endEntry(Entry entry) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endEntry(entry);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given feed.
+ *
+ * @param feed
+ * The current feed.
+ */
+ public void endFeed(Feed feed) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endFeed(feed);
+ }
+ }
+
+ /**
+ * Called at the end of the XML block that defines the given link.
+ *
+ * @param link
+ * The current link.
+ */
+ public void endLink(Link link) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endLink(link);
+ }
+ }
+
+ @Override
+ public void endPrefixMapping(String prefix) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.endPrefixMapping(prefix);
+ }
+ }
+
+ @Override
+ public void error(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.error(e);
+ }
+ }
+
+ @Override
+ public void fatalError(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.fatalError(e);
+ }
+ }
+
+ @Override
+ public void ignorableWhitespace(char[] ch, int start, int length)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.ignorableWhitespace(ch, start, length);
+ }
+ }
+
+ @Override
+ public void notationDecl(String name, String publicId, String systemId)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.notationDecl(name, publicId, systemId);
+ }
+ }
+
+ @Override
+ public void processingInstruction(String target, String data)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.processingInstruction(target, data);
+ }
+ }
+
+ @Override
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws IOException, SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ return this.feedReader.resolveEntity(publicId, systemId);
+ }
+ return null;
+ }
+
+ @Override
+ public void setDocumentLocator(Locator locator) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.setDocumentLocator(locator);
+ }
+ }
+
+ @Override
+ public void skippedEntity(String name) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.skippedEntity(name);
+ }
+ }
+
+ /**
+ * Called when a new content element has been detected in the Atom document.
+ *
+ * @param content
+ * The current content element.
+ */
+ public void startContent(Content content) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startContent(content);
+ }
+ }
+
+ @Override
+ public void startDocument() throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startDocument();
+ }
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startElement(uri, localName, qName, attributes);
+ }
+ }
+
+ /**
+ * Called when a new entry has been detected in the Atom document.
+ *
+ * @param entry
+ * The current entry.
+ */
+ public void startEntry(Entry entry) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startEntry(entry);
+ }
+ }
+
+ /**
+ * Called when a new feed has been detected in the Atom document.
+ *
+ * @param feed
+ * The current feed.
+ */
+ public void startFeed(Feed feed) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startFeed(feed);
+ }
+ }
+
+ /**
+ * Called when a new link has been detected in the Atom document.
+ *
+ * @param link
+ * The current link.
+ */
+ public void startLink(Link link) {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startLink(link);
+ }
+ }
+
+ @Override
+ public void startPrefixMapping(String prefix, String uri)
+ throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.startPrefixMapping(prefix, uri);
+ }
+ }
+
+ @Override
+ public void unparsedEntityDecl(String name, String publicId,
+ String systemId, String notationName) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.unparsedEntityDecl(name, publicId, systemId, notationName);
+ }
+ }
+
+ @Override
+ public void warning(SAXParseException e) throws SAXException {
+ // Send the event to the extra handler.
+ if (this.feedReader != null) {
+ this.feedReader.warning(e);
+ }
+ }
+
+}
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java
index 9a0eddb853..fb257a4f05 100644
--- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java
@@ -47,18 +47,18 @@
import org.restlet.ext.atom.Person;
import org.restlet.ext.atom.Relation;
import org.restlet.ext.atom.Text;
+import org.restlet.ext.atom.contentHandler.EntryReader;
import org.restlet.ext.xml.XmlWriter;
import org.restlet.representation.StringRepresentation;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
/**
* Content reader for entries.
*
* @author Jerome Louvel
*/
-public class EntryContentReader extends DefaultHandler {
+public class EntryContentReader extends EntryReader {
private enum State {
FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, NONE
}
@@ -106,6 +106,16 @@ private enum State {
* The entry object to update during the parsing.
*/
public EntryContentReader(Entry entry) {
+ this(entry, null);
+ }
+
+ /**
+ * Constructor.
+ * @param entry The entry object to update during the parsing.
+ * @param extraEntryHandler Custom handler of all events.
+ */
+ public EntryContentReader(Entry entry, EntryReader extraEntryHandler) {
+ super(extraEntryHandler);
this.state = State.NONE;
this.contentDepth = -1;
this.currentEntry = entry;
@@ -130,12 +140,16 @@ public void characters(char[] ch, int start, int length)
} else {
this.contentBuffer.append(ch, start, length);
}
+
+ super.characters(ch, start, length);
}
@Override
public void endDocument() throws SAXException {
this.state = State.NONE;
this.contentBuffer = null;
+
+ super.endDocument();
}
@Override
@@ -243,6 +257,10 @@ public void endElement(String uri, String localName, String qName)
}
this.currentContentWriter = null;
}
+ endLink(this.currentLink);
+ } else if (localName.equalsIgnoreCase("entry")) {
+ this.state = State.NONE;
+ endEntry(this.currentEntry);
} else if (localName.equals("category")) {
if (this.state == State.FEED_ENTRY_CATEGORY) {
this.currentEntry.getCategories().add(this.currentCategory);
@@ -270,45 +288,19 @@ public void endElement(String uri, String localName, String qName)
this.state = State.FEED_ENTRY;
}
this.currentContentWriter = null;
- }
- } else if (this.state == State.FEED_ENTRY) {
- // Set the inline content, if any
- if (this.currentContentWriter != null) {
- this.currentContentWriter.endElement(uri, localName, qName);
- String content = this.currentContentWriter.getWriter()
- .toString().trim();
- contentDepth = -1;
- if ("".equals(content)) {
- this.currentEntry.setInlineContent(null);
- } else {
- this.currentEntry
- .setInlineContent(new StringRepresentation(content));
- }
- this.currentContentWriter = null;
+ endContent(this.currentContent);
}
}
this.currentText = null;
this.currentDate = null;
- }
-
- /**
- * Initiates the parsing of a mixed content part of the current document.
- */
- private void initiateInlineMixedContent() {
- this.contentDepth = 0;
- StringWriter sw = new StringWriter();
- currentContentWriter = new XmlWriter(sw);
-
- for (String prefix : this.prefixMappings.keySet()) {
- currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix),
- prefix);
- }
+ super.endElement(uri, localName, qName);
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
this.prefixMappings.remove(prefix);
+ super.endPrefixMapping(prefix);
}
/**
@@ -336,9 +328,24 @@ private MediaType getMediaType(String type) {
return result;
}
+ /**
+ * Initiates the parsing of a mixed content part of the current document.
+ */
+ private void initiateInlineMixedContent() {
+ this.contentDepth = 0;
+ StringWriter sw = new StringWriter();
+ currentContentWriter = new XmlWriter(sw);
+
+ for (String prefix : this.prefixMappings.keySet()) {
+ currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix),
+ prefix);
+ }
+ }
+
@Override
public void startDocument() throws SAXException {
this.contentBuffer = new StringBuilder();
+ super.startDocument();
}
@Override
@@ -423,8 +430,10 @@ public void startElement(String uri, String localName, String qName,
// Content available inline
initiateInlineMixedContent();
this.currentLink.setContent(currentContent);
+ startLink(this.currentLink);
} else if (localName.equalsIgnoreCase("entry")) {
this.state = State.FEED_ENTRY;
+ startEntry(this.currentEntry);
} else if (localName.equals("category")) {
this.currentCategory = new Category();
this.currentCategory.setTerm(attrs.getValue("", "term"));
@@ -457,19 +466,19 @@ public void startElement(String uri, String localName, String qName,
this.currentEntry.setContent(currentContent);
this.state = State.FEED_ENTRY_CONTENT;
}
+ startContent(this.currentContent);
}
- } else if (this.state == State.FEED_ENTRY) {
- // Content available inline
- initiateInlineMixedContent();
- this.currentContentWriter
- .startElement(uri, localName, qName, attrs);
}
+
+ super.startElement(uri, localName, qName, attrs);
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
this.prefixMappings.put(prefix, uri);
+
+ super.startPrefixMapping(prefix, uri);
}
/**
diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java
index 588f58fe23..93a61e5610 100644
--- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java
+++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java
@@ -47,18 +47,18 @@
import org.restlet.ext.atom.Person;
import org.restlet.ext.atom.Relation;
import org.restlet.ext.atom.Text;
+import org.restlet.ext.atom.contentHandler.FeedReader;
import org.restlet.ext.xml.XmlWriter;
import org.restlet.representation.StringRepresentation;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
/**
* Content reader for feeds.
*
* @author Thierry Boileau
*/
-public class FeedContentReader extends DefaultHandler {
+public class FeedContentReader extends FeedReader {
private enum State {
FEED, FEED_AUTHOR, FEED_AUTHOR_EMAIL, FEED_AUTHOR_NAME, FEED_AUTHOR_URI, FEED_CATEGORY, FEED_CONTRIBUTOR, FEED_CONTRIBUTOR_EMAIL, FEED_CONTRIBUTOR_NAME, FEED_CONTRIBUTOR_URI, FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, FEED_GENERATOR, FEED_ICON, FEED_ID, FEED_LINK, FEED_LOGO, FEED_RIGHTS, FEED_SUBTITLE, FEED_TITLE, FEED_UPDATED, NONE
}
@@ -96,15 +96,6 @@ private enum State {
/** The currently parsed Text. */
private Text currentText;
- /** Extra content handler that will be notified of Entry events. */
- private DefaultHandler extraEntryHandler;
-
- /** Extra content handler that will be notified of Feed events. */
- private DefaultHandler extraFeedHandler;
-
- /** Indicates if the current event is dedicated to an entry or a feed. */
- private boolean parsingEntry = false;
-
/** The current list of prefix mappings. */
private Map<String, String> prefixMappings;
@@ -118,6 +109,19 @@ private enum State {
* The feed object to update during the parsing.
*/
public FeedContentReader(Feed feed) {
+ this(feed, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param feed
+ * The feed object to update during the parsing.
+ * @param extraFeedReader
+ * Custom handler of all events.
+ */
+ public FeedContentReader(Feed feed, FeedReader extraFeedReader) {
+ super(extraFeedReader);
this.state = State.NONE;
this.currentFeed = feed;
this.currentEntry = null;
@@ -132,19 +136,6 @@ public FeedContentReader(Feed feed) {
this.contentDepth = -1;
}
- /**
- * Constructor.
- *
- * @param feed
- * The feed object to update during the parsing.
- */
- public FeedContentReader(Feed feed, DefaultHandler extraFeedHandler,
- DefaultHandler extraEntryHandler) {
- this(feed);
- this.extraFeedHandler = extraFeedHandler;
- this.extraEntryHandler = extraEntryHandler;
- }
-
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
@@ -156,17 +147,7 @@ public void characters(char[] ch, int start, int length)
} else {
this.contentBuffer.append(ch, start, length);
}
-
- // Send the event to the right extra handler.
- if (parsingEntry) {
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.characters(ch, start, length);
- }
- } else {
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.characters(ch, start, length);
- }
- }
+ super.characters(ch, start, length);
}
@Override
@@ -175,13 +156,7 @@ public void endDocument() throws SAXException {
this.currentEntry = null;
this.contentBuffer = null;
- // Send the event to the extra handlers.
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.endDocument();
- }
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.endDocument();
- }
+ super.endDocument();
}
@Override
@@ -212,6 +187,7 @@ public void endElement(String uri, String localName, String qName)
} else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) {
if (localName.equals("feed")) {
this.state = State.NONE;
+ endFeed(this.currentFeed);
} else if (localName.equals("title")) {
if (this.state == State.FEED_TITLE) {
this.currentFeed.setTitle(this.currentText);
@@ -305,12 +281,13 @@ public void endElement(String uri, String localName, String qName)
}
this.currentContentWriter = null;
}
+ endLink(this.currentLink);
} else if (localName.equalsIgnoreCase("entry")) {
if (this.state == State.FEED_ENTRY) {
this.currentFeed.getEntries().add(this.currentEntry);
this.state = State.FEED;
- this.parsingEntry = false;
}
+ endEntry(this.currentEntry);
} else if (localName.equals("category")) {
if (this.state == State.FEED_CATEGORY) {
this.currentFeed.getCategories().add(this.currentCategory);
@@ -341,37 +318,13 @@ public void endElement(String uri, String localName, String qName)
this.state = State.FEED_ENTRY;
}
this.currentContentWriter = null;
- }
- } else if (this.state == State.FEED_ENTRY) {
- // Set the inline content, if any
- if (this.currentContentWriter != null) {
- this.currentContentWriter.endElement(uri, localName, qName);
- String content = this.currentContentWriter.getWriter()
- .toString().trim();
- contentDepth = -1;
- if ("".equals(content)) {
- this.currentEntry.setInlineContent(null);
- } else {
- this.currentEntry
- .setInlineContent(new StringRepresentation(content));
- }
- this.currentContentWriter = null;
+ endContent(this.currentContent);
}
}
this.currentText = null;
this.currentDate = null;
-
- // Send the event to the right extra handler.
- if (parsingEntry) {
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.endElement(uri, localName, qName);
- }
- } else {
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.endElement(uri, localName, qName);
- }
- }
+ super.endElement(uri, localName, qName);
}
@Override
@@ -379,15 +332,7 @@ public void endPrefixMapping(String prefix) throws SAXException {
this.prefixMappings.remove(prefix);
// Send the event to the right extra handler.
- if (parsingEntry) {
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.endPrefixMapping(prefix);
- }
- } else {
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.endPrefixMapping(prefix);
- }
- }
+ super.endPrefixMapping(prefix);
}
/**
@@ -432,14 +377,7 @@ private void initiateInlineMixedContent() {
@Override
public void startDocument() throws SAXException {
this.contentBuffer = new StringBuilder();
-
- // Send the event to the extra handlers.
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.startDocument();
- }
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.startDocument();
- }
+ super.startDocument();
}
@Override
@@ -461,6 +399,7 @@ public void startElement(String uri, String localName, String qName,
this.currentFeed.setBaseReference(new Reference(attr));
}
this.state = State.FEED;
+ startFeed(this.currentFeed);
} else if (localName.equals("title")) {
startTextElement(attrs);
@@ -543,12 +482,13 @@ public void startElement(String uri, String localName, String qName,
// Content available inline
initiateInlineMixedContent();
this.currentLink.setContent(currentContent);
+ startLink(this.currentLink);
} else if (localName.equalsIgnoreCase("entry")) {
if (this.state == State.FEED) {
this.currentEntry = new Entry();
this.state = State.FEED_ENTRY;
- this.parsingEntry = true;
}
+ startEntry(this.currentEntry);
} else if (localName.equals("category")) {
this.currentCategory = new Category();
this.currentCategory.setTerm(attrs.getValue("", "term"));
@@ -583,26 +523,11 @@ public void startElement(String uri, String localName, String qName,
this.currentEntry.setContent(currentContent);
this.state = State.FEED_ENTRY_CONTENT;
}
+ startContent(this.currentContent);
}
- } else if (this.state == State.FEED_ENTRY) {
- // Content available inline
- initiateInlineMixedContent();
- this.currentContentWriter
- .startElement(uri, localName, qName, attrs);
}
- // Send the event to the right extra handler.
- if (parsingEntry) {
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.startElement(uri, localName, qName,
- attrs);
- }
- } else {
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler
- .startElement(uri, localName, qName, attrs);
- }
- }
+ super.startElement(uri, localName, qName, attrs);
}
@Override
@@ -610,16 +535,7 @@ public void startPrefixMapping(String prefix, String uri)
throws SAXException {
this.prefixMappings.put(prefix, uri);
- // Send the event to the right extra handler.
- if (parsingEntry) {
- if (this.extraEntryHandler != null) {
- this.extraEntryHandler.startPrefixMapping(prefix, uri);
- }
- } else {
- if (this.extraFeedHandler != null) {
- this.extraFeedHandler.startPrefixMapping(prefix, uri);
- }
- }
+ super.startPrefixMapping(prefix, uri);
}
/**
@@ -631,4 +547,5 @@ public void startPrefixMapping(String prefix, String uri)
public void startTextElement(Attributes attrs) {
this.currentText = new Text(getMediaType(attrs.getValue("", "type")));
}
+
}
\ No newline at end of file
|
45afeb9fb5ce49a9f0e4d931057ebaf6990111ab
|
ReactiveX-RxJava
|
Forward subscription of wrapped subscriber--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorWeakBinding.java b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorWeakBinding.java
index 986341396f..3cc8258302 100644
--- a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorWeakBinding.java
+++ b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorWeakBinding.java
@@ -47,6 +47,7 @@ final class WeakSubscriber extends Subscriber<T> {
final WeakReference<Subscriber<? super T>> subscriberRef;
private WeakSubscriber(Subscriber<? super T> source) {
+ super(source);
subscriberRef = new WeakReference<Subscriber<? super T>>(source);
}
diff --git a/rxjava-contrib/rxjava-android/src/test/java/rx/operators/OperatorWeakBindingTest.java b/rxjava-contrib/rxjava-android/src/test/java/rx/operators/OperatorWeakBindingTest.java
index e5445ce228..6dd72c606d 100644
--- a/rxjava-contrib/rxjava-android/src/test/java/rx/operators/OperatorWeakBindingTest.java
+++ b/rxjava-contrib/rxjava-android/src/test/java/rx/operators/OperatorWeakBindingTest.java
@@ -1,24 +1,21 @@
package rx.operators;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
-import rx.Subscriber;
import rx.functions.Functions;
+import rx.observers.TestSubscriber;
+
+import java.util.Arrays;
@RunWith(RobolectricTestRunner.class)
public class OperatorWeakBindingTest {
- @Mock
- private Subscriber<String> subscriber;
+ private TestSubscriber<String> subscriber = new TestSubscriber<String>();
@Before
public void setUp() throws Exception {
@@ -34,10 +31,9 @@ public void shouldForwardAllNotificationsWhenSubscriberAndTargetAlive() {
weakSub.onCompleted();
weakSub.onError(new Exception());
- verify(subscriber).onNext("one");
- verify(subscriber).onNext("two");
- verify(subscriber).onCompleted();
- verify(subscriber).onError(any(Exception.class));
+ subscriber.assertReceivedOnNext(Arrays.asList("one", "two"));
+ assertEquals(1, subscriber.getOnCompletedEvents().size());
+ assertEquals(1, subscriber.getOnErrorEvents().size());
}
@Test
@@ -51,8 +47,9 @@ public void shouldUnsubscribeFromSourceSequenceWhenSubscriberReleased() {
weakSub.onCompleted();
weakSub.onError(new Exception());
- verify(subscriber).onNext("one");
- verifyNoMoreInteractions(subscriber);
+ subscriber.assertReceivedOnNext(Arrays.asList("one"));
+ assertEquals(0, subscriber.getOnCompletedEvents().size());
+ assertEquals(0, subscriber.getOnErrorEvents().size());
}
@Test
@@ -66,8 +63,9 @@ public void shouldUnsubscribeFromSourceSequenceWhenTargetObjectReleased() {
weakSub.onCompleted();
weakSub.onError(new Exception());
- verify(subscriber).onNext("one");
- verifyNoMoreInteractions(subscriber);
+ subscriber.assertReceivedOnNext(Arrays.asList("one"));
+ assertEquals(0, subscriber.getOnCompletedEvents().size());
+ assertEquals(0, subscriber.getOnErrorEvents().size());
}
@Test
@@ -81,6 +79,16 @@ public void shouldUnsubscribeFromSourceSequenceWhenPredicateFailsToPass() {
weakSub.onCompleted();
weakSub.onError(new Exception());
- verifyZeroInteractions(subscriber);
+ assertEquals(0, subscriber.getOnNextEvents().size());
+ assertEquals(0, subscriber.getOnCompletedEvents().size());
+ assertEquals(0, subscriber.getOnErrorEvents().size());
+ }
+
+ @Test
+ public void unsubscribeWillUnsubscribeFromWrappedSubscriber() {
+ OperatorWeakBinding<String, Object> op = new OperatorWeakBinding<String, Object>(new Object());
+
+ op.call(subscriber).unsubscribe();
+ subscriber.assertUnsubscribed();
}
}
|
7db99eb0da29b8106532a863da32a6bb39ae0a3b
|
camel
|
Camel fails if onCompletion has been mis- configured from Java DSL.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1040143 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java b/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
index cfe9ad0507d62..e1fe00927f504 100644
--- a/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
+++ b/camel-core/src/main/java/org/apache/camel/model/OnCompletionDefinition.java
@@ -141,6 +141,9 @@ public ProcessorDefinition end() {
* @return the builder
*/
public OnCompletionDefinition onCompleteOnly() {
+ if (onFailureOnly) {
+ throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
+ }
// must define return type as OutputDefinition and not this type to avoid end user being able
// to invoke onFailureOnly/onCompleteOnly more than once
setOnCompleteOnly(Boolean.TRUE);
@@ -154,6 +157,9 @@ public OnCompletionDefinition onCompleteOnly() {
* @return the builder
*/
public OnCompletionDefinition onFailureOnly() {
+ if (onCompleteOnly) {
+ throw new IllegalArgumentException("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: " + this);
+ }
// must define return type as OutputDefinition and not this type to avoid end user being able
// to invoke onFailureOnly/onCompleteOnly more than once
setOnCompleteOnly(Boolean.FALSE);
diff --git a/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.java b/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.java
new file mode 100644
index 0000000000000..e432f0e9ea1d2
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/processor/OnCompletionInvalidConfiguredTest.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.processor;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+
+/**
+ * @version $Revision$
+ */
+public class OnCompletionInvalidConfiguredTest extends ContextTestSupport {
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ public void testInvalidConfigured() throws Exception {
+ try {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ onCompletion().onFailureOnly().onCompleteOnly().to("mock:foo");
+
+ from("direct:start").to("mock:result");
+ }
+ });
+ fail("Should throw exception");
+ } catch (IllegalArgumentException e) {
+ assertEquals("Both onCompleteOnly and onFailureOnly cannot be true. Only one of them can be true. On node: onCompletion[[]]", e.getMessage());
+ }
+ }
+}
|
077278fa9e61890e3ebb9f833ecee0e3c4655202
|
hadoop
|
YARN-2158. Improved assertion messages of- TestRMWebServicesAppsModification. Contributed by Varun Vasudev. svn merge- --ignore-ancestry -c 1608667 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1608668 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 f0317eda28be0..34ab9db165b2e 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -340,6 +340,9 @@ Release 2.5.0 - UNRELEASED
YARN-2250. FairScheduler.findLowestCommonAncestorQueue returns null when
queues not identical (Krisztian Horvath via Sandy Ryza)
+ YARN-2158. Improved assertion messages of TestRMWebServicesAppsModification.
+ (Varun Vasudev via zjshen)
+
Release 2.4.1 - 2014-06-23
INCOMPATIBLE CHANGES
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/TestRMWebServicesAppsModification.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesAppsModification.java
index 4c8eeb306b8ea..12c5686e3eefd 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesAppsModification.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesAppsModification.java
@@ -411,13 +411,15 @@ protected static void verifyAppStateJson(ClientResponse response,
assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
JSONObject json = response.getEntity(JSONObject.class);
assertEquals("incorrect number of elements", 1, json.length());
+ String responseState = json.getString("state");
boolean valid = false;
for (RMAppState state : states) {
- if (state.toString().equals(json.getString("state"))) {
+ if (state.toString().equals(responseState)) {
valid = true;
}
}
- assertTrue("app state incorrect", valid);
+ String msg = "app state incorrect, got " + responseState;
+ assertTrue(msg, valid);
return;
}
@@ -441,7 +443,8 @@ protected static void verifyAppStateXML(ClientResponse response,
valid = true;
}
}
- assertTrue("app state incorrect", valid);
+ String msg = "app state incorrect, got " + state;
+ assertTrue(msg, valid);
return;
}
|
e1bbd8cbc538aae9acc0eb24b1f0751d88f05365
|
hbase
|
HBASE-1552 provide version running on cluster via- getClusterStatus--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@786666 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index ff1bde63facf..ee9fe6fe412c 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -196,8 +196,8 @@ Release 0.20.0 - Unreleased
HBASE-1447 Take last version of the hbase-1249 design doc. and make
documentation out of it
HBASE-1206 Scanner spins when there are concurrent inserts to column family
- HBASE-1536 Controlled crash of regionserver not hosting meta/root leaves master
- in spinning state, regions not reassigned
+ HBASE-1536 Controlled crash of regionserver not hosting meta/root leaves
+ master in spinning state, regions not reassigned
HBASE-1543 Unnecessary toString during scanning costs us some CPU
HBASE-1544 Cleanup HTable (Jonathan Gray via Stack)
HBASE-1488 After 1304 goes in, fix and reenable test of thrift, mr indexer,
@@ -367,6 +367,7 @@ Release 0.20.0 - Unreleased
families results in bad scans
HBASE-1540 Client delete unit test, define behavior
(Jonathan Gray via Stack)
+ HBASE-1552 provide version running on cluster via getClusterStatus
OPTIMIZATIONS
HBASE-1412 Change values for delete column and column family in KeyValue
diff --git a/bin/HBase.rb b/bin/HBase.rb
index 8cf97c589dfc..f982a2ae8b20 100644
--- a/bin/HBase.rb
+++ b/bin/HBase.rb
@@ -262,6 +262,7 @@ def shutdown()
def status(format)
status = @admin.getClusterStatus()
if format != nil and format == "detailed"
+ puts("version %s" % [ status.getHBaseVersion() ])
puts("%d live servers" % [ status.getServers() ])
for server in status.getServerInfo()
puts(" %s:%d %d" % \
diff --git a/src/java/org/apache/hadoop/hbase/ClusterStatus.java b/src/java/org/apache/hadoop/hbase/ClusterStatus.java
index cd241697a5dd..19a8f7b8dc6d 100644
--- a/src/java/org/apache/hadoop/hbase/ClusterStatus.java
+++ b/src/java/org/apache/hadoop/hbase/ClusterStatus.java
@@ -45,6 +45,8 @@
*/
public class ClusterStatus extends VersionedWritable {
private static final byte VERSION = 0;
+
+ private String hbaseVersion;
private Collection<HServerInfo> liveServerInfo;
private Collection<String> deadServers;
@@ -119,6 +121,20 @@ public int getRequestsCount() {
return count;
}
+ /**
+ * @return the HBase version string as reported by the HMaster
+ */
+ public String getHBaseVersion() {
+ return hbaseVersion;
+ }
+
+ /**
+ * @param version the HBase version string
+ */
+ public void setHBaseVersion(String version) {
+ hbaseVersion = version;
+ }
+
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@@ -130,6 +146,7 @@ public boolean equals(Object o) {
return false;
}
return (getVersion() == ((ClusterStatus)o).getVersion()) &&
+ getHBaseVersion().equals(((ClusterStatus)o).getHBaseVersion()) &&
liveServerInfo.equals(((ClusterStatus)o).liveServerInfo) &&
deadServers.equals(((ClusterStatus)o).deadServers);
}
@@ -138,7 +155,8 @@ public boolean equals(Object o) {
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
- return VERSION + liveServerInfo.hashCode() + deadServers.hashCode();
+ return VERSION + hbaseVersion.hashCode() + liveServerInfo.hashCode() +
+ deadServers.hashCode();
}
/** @return the object version number */
@@ -179,6 +197,7 @@ public void setDeadServers(Collection<String> deadServers) {
public void write(DataOutput out) throws IOException {
super.write(out);
+ out.writeUTF(hbaseVersion);
out.writeInt(liveServerInfo.size());
for (HServerInfo server: liveServerInfo) {
server.write(out);
@@ -191,6 +210,7 @@ public void write(DataOutput out) throws IOException {
public void readFields(DataInput in) throws IOException {
super.readFields(in);
+ hbaseVersion = in.readUTF();
int count = in.readInt();
liveServerInfo = new ArrayList<HServerInfo>(count);
for (int i = 0; i < count; i++) {
diff --git a/src/java/org/apache/hadoop/hbase/master/HMaster.java b/src/java/org/apache/hadoop/hbase/master/HMaster.java
index d5b6838c4bf7..ac523e1a7440 100644
--- a/src/java/org/apache/hadoop/hbase/master/HMaster.java
+++ b/src/java/org/apache/hadoop/hbase/master/HMaster.java
@@ -78,6 +78,7 @@
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.util.Sleeper;
import org.apache.hadoop.hbase.util.Writables;
+import org.apache.hadoop.hbase.util.VersionInfo;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.protocol.FSConstants;
@@ -985,6 +986,7 @@ public void modifyTable(final byte[] tableName, HConstants.Modify op,
*/
public ClusterStatus getClusterStatus() {
ClusterStatus status = new ClusterStatus();
+ status.setHBaseVersion(VersionInfo.getVersion());
status.setServerInfo(serverManager.serversToServerInfo.values());
status.setDeadServers(serverManager.deadServers);
return status;
|
7d10c7e49521bfcab46fc07b134c933a2f054282
|
ReactiveX-RxJava
|
fix sticky intent duplication, add tests for- OperatorBroadcast--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java
index c448f9cb42..7e06a1c0aa 100644
--- a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java
+++ b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java
@@ -58,10 +58,7 @@ public void call() {
});
subscriber.add(subscription);
- Intent stickyIntent = context.registerReceiver(broadcastReceiver, intentFilter, broadcastPermission, schedulerHandler);
- if (stickyIntent != null) {
- subscriber.onNext(stickyIntent);
- }
+ context.registerReceiver(broadcastReceiver, intentFilter, broadcastPermission, schedulerHandler);
}
}
diff --git a/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorBroadcastRegisterTest.java b/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorBroadcastRegisterTest.java
new file mode 100644
index 0000000000..28e6c80338
--- /dev/null
+++ b/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorBroadcastRegisterTest.java
@@ -0,0 +1,127 @@
+/**
+ * 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.android.operators;
+
+import android.app.Application;
+import android.content.Intent;
+import android.content.IntentFilter;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InOrder;
+import org.robolectric.Robolectric;
+import org.robolectric.RobolectricTestRunner;
+
+import rx.Observable;
+import rx.Observer;
+import rx.Subscription;
+import rx.android.observables.AndroidObservable;
+import rx.observers.TestObserver;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+
+@RunWith(RobolectricTestRunner.class)
+public class OperatorBroadcastRegisterTest {
+
+ @Test
+ public void testBroadcast() {
+ String action = "TEST_ACTION";
+ IntentFilter intentFilter = new IntentFilter(action);
+ Application application = Robolectric.application;
+ Observable<Intent> observable = AndroidObservable.fromBroadcast(application, intentFilter);
+ final Observer<Intent> observer = mock(Observer.class);
+ final Subscription subscription = observable.subscribe(new TestObserver<Intent>(observer));
+
+ final InOrder inOrder = inOrder(observer);
+
+ inOrder.verify(observer, never()).onNext(any(Intent.class));
+
+ Intent intent = new Intent(action);
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, times(1)).onNext(intent);
+
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, times(1)).onNext(intent);
+
+ subscription.unsubscribe();
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, never()).onNext(any(Intent.class));
+
+ inOrder.verify(observer, never()).onError(any(Throwable.class));
+ inOrder.verify(observer, never()).onCompleted();
+ }
+
+ @Test
+ public void testStickyBroadcast() {
+ String action = "TEST_STICKY_ACTION";
+ IntentFilter intentFilter = new IntentFilter(action);
+ Application application = Robolectric.application;
+ Intent intent = new Intent(action);
+ application.sendStickyBroadcast(intent);
+ Observable<Intent> observable = AndroidObservable.fromBroadcast(application, intentFilter);
+ final Observer<Intent> observer = mock(Observer.class);
+ final Subscription subscription = observable.subscribe(new TestObserver<Intent>(observer));
+
+ final InOrder inOrder = inOrder(observer);
+
+ inOrder.verify(observer, times(1)).onNext(intent);
+
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, times(1)).onNext(intent);
+
+ subscription.unsubscribe();
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, never()).onNext(any(Intent.class));
+
+ inOrder.verify(observer, never()).onError(any(Throwable.class));
+ inOrder.verify(observer, never()).onCompleted();
+ }
+
+ @Test
+ public void testPermissionBroadcast() {
+ String action = "TEST_ACTION";
+ String permission = "test_permission";
+ IntentFilter intentFilter = new IntentFilter(action);
+ Application application = Robolectric.application;
+ Observable<Intent> observable = AndroidObservable.fromBroadcast(application, intentFilter, permission, null);
+ final Observer<Intent> observer = mock(Observer.class);
+ final Subscription subscription = observable.subscribe(new TestObserver<Intent>(observer));
+
+ final InOrder inOrder = inOrder(observer);
+
+ inOrder.verify(observer, never()).onNext(any(Intent.class));
+
+ Intent intent = new Intent(action);
+ application.sendBroadcast(intent);
+ inOrder.verify(observer, never()).onNext(intent);
+
+ application.sendBroadcast(intent, permission);
+ inOrder.verify(observer, times(1)).onNext(intent);
+
+ subscription.unsubscribe();
+ application.sendBroadcast(intent);
+ application.sendBroadcast(intent, permission);
+ inOrder.verify(observer, never()).onNext(any(Intent.class));
+
+ inOrder.verify(observer, never()).onError(any(Throwable.class));
+ inOrder.verify(observer, never()).onCompleted();
+ }
+
+}
|
208f53a0626a814616470d39d8a7032aac23eb7b
|
camel
|
Fixed compiler issue on JDK 1.5--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1056650 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/test/java/org/apache/camel/processor/SplitterParallelBigFileTest.java b/camel-core/src/test/java/org/apache/camel/processor/SplitterParallelBigFileTest.java
index 08e597a1cc865..ef6404c7f63d2 100644
--- a/camel-core/src/test/java/org/apache/camel/processor/SplitterParallelBigFileTest.java
+++ b/camel-core/src/test/java/org/apache/camel/processor/SplitterParallelBigFileTest.java
@@ -62,12 +62,12 @@ public void xxxtestSplitParallelBigFile() throws Exception {
StopWatch watch = new StopWatch();
NotifyBuilder builder = new NotifyBuilder(context).whenDone(lines + 1).create();
- boolean done = builder.matches(5, TimeUnit.MINUTES);
+ boolean done = builder.matches(120, TimeUnit.SECONDS);
log.info("Took " + TimeUtils.printDuration(watch.stop()));
if (!done) {
- throw new CamelException("Could not split file in 5 minutes");
+ throw new CamelException("Could not split file in 2 minutes");
}
// need a little sleep for capturing memory profiling
@@ -83,7 +83,7 @@ public void configure() throws Exception {
//context.getExecutorServiceStrategy().getDefaultThreadPoolProfile().setMaxPoolSize(10);
from("file:target/split")
- .split(body().tokenize("\n")).parallelProcessing()
+ .split(body().tokenize("\n")).streaming().parallelProcessing()
.to("log:split?groupSize=1000");
}
};
|
f28bcd1a6c78ad80316885c50ec77661184b390e
|
intellij-community
|
JUnit UI redesign, part 4: "rerun failed tests"- button moved to proper place--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/python/src/com/jetbrains/python/run/PythonCommandLineState.java b/python/src/com/jetbrains/python/run/PythonCommandLineState.java
index 82a5c9f123144..9ccf7ec13a805 100644
--- a/python/src/com/jetbrains/python/run/PythonCommandLineState.java
+++ b/python/src/com/jetbrains/python/run/PythonCommandLineState.java
@@ -44,7 +44,7 @@ public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunne
final ConsoleView console = createAndAttachConsole(getConfig().getProject(), processHandler);
return new DefaultExecutionResult(console, processHandler,
- createActions(console, processHandler));
+ createActions(console, processHandler, executor));
}
@NotNull
diff --git a/python/src/com/jetbrains/python/testing/PythonUnitTestCommandLineState.java b/python/src/com/jetbrains/python/testing/PythonUnitTestCommandLineState.java
index 57b3c88a064a5..efbc542c9eda4 100644
--- a/python/src/com/jetbrains/python/testing/PythonUnitTestCommandLineState.java
+++ b/python/src/com/jetbrains/python/testing/PythonUnitTestCommandLineState.java
@@ -54,7 +54,7 @@ public ExecutionResult execute(@NotNull Executor executor, @NotNull ProgramRunne
final ProcessHandler processHandler = startProcess();
final ConsoleView console = createAndAttachConsole(getConfig().getProject(), processHandler);
- return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler));
+ return new DefaultExecutionResult(console, processHandler, createActions(console, processHandler, executor));
}
protected OSProcessHandler startProcess() throws ExecutionException {
|
5ac8276168694053d9fc5357793651f139e9390b
|
hadoop
|
MAPREDUCE-3392. Fixed Cluster's- getDelegationToken's API to return null when there isn't a supported token.- Contributed by John George. svn merge -c r1200484 --ignore-ancestry- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1200485 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index 535024c007377..8f8e3ec50df53 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -57,6 +57,9 @@ Release 0.23.1 - Unreleased
which per-container connections to NodeManager were lingering long enough
to hit the ulimits on number of processes. (vinodkv)
+ MAPREDUCE-3392. Fixed Cluster's getDelegationToken's API to return null
+ when there isn't a supported token. (John George via vinodkv)
+
Release 0.23.0 - 2011-11-01
INCOMPATIBLE CHANGES
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java
index 460202167ddcd..4828ebacaa014 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java
@@ -390,6 +390,11 @@ public long getTaskTrackerExpiryInterval() throws IOException,
getDelegationToken(Text renewer) throws IOException, InterruptedException{
Token<DelegationTokenIdentifier> result =
client.getDelegationToken(renewer);
+
+ if (result == null) {
+ return result;
+ }
+
InetSocketAddress addr = Master.getMasterAddress(conf);
StringBuilder service = new StringBuilder();
service.append(NetUtils.normalizeHostName(addr.getAddress().
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java
index 2bc9030bf85ea..490b7a546e684 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java
@@ -25,6 +25,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.YARNRunner;
import org.apache.hadoop.mapreduce.protocol.ClientProtocol;
+import org.apache.hadoop.io.Text;
import org.junit.Test;
public class TestYarnClientProtocolProvider extends TestCase {
@@ -56,4 +57,23 @@ public void testClusterWithYarnClientProtocolProvider() throws Exception {
}
}
}
+
+
+ @Test
+ public void testClusterGetDelegationToken() throws Exception {
+
+ Configuration conf = new Configuration(false);
+ Cluster cluster = null;
+ try {
+ conf = new Configuration();
+ conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME);
+ cluster = new Cluster(conf);
+ cluster.getDelegationToken(new Text(" "));
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
+
}
|
0c9cd2f936f77ccf22dcf98df1c9679cdafa791f
|
drools
|
JBRULES-2353: Update HumanTask to the new grid inf- and CommandExecutor - fix unsupported setError methods--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@30808 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java b/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java
index 2877f0f0349..92182ae97a8 100644
--- a/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java
+++ b/drools-vsm/src/main/java/org/drools/vsm/remote/ServiceManagerRemoteClient.java
@@ -85,11 +85,12 @@ public boolean connect() {
}
}
// Connecting with services
- if (this.services!=null) {
+ if (this.services != null) {
for (GenericConnector connector : services){
boolean serviceConnected = connector.connect();
- if ( serviceConnected )
+ if ( serviceConnected ){
System.out.println("Service Connected");
+ }
}
}
@@ -98,9 +99,11 @@ public boolean connect() {
public void disconnect() {
this.client.disconnect();
- if (this.services!=null)
- for (GenericConnector connector : this.services)
+ if (this.services != null){
+ for (GenericConnector connector : this.services){
connector.disconnect();
+ }
+ }
}
public KnowledgeBuilderProvider getKnowledgeBuilderFactory() {
diff --git a/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java b/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java
index dca0e7fa17f..9219f952c0c 100644
--- a/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java
+++ b/drools-vsm/src/main/java/org/drools/vsm/task/CommandBasedVSMWSHumanTaskHandler.java
@@ -41,6 +41,7 @@
import org.drools.task.service.Command;
import org.drools.task.service.ContentData;
import org.drools.task.service.HumanTaskServiceImpl;
+import org.drools.task.service.responsehandlers.AbstractBaseResponseHandler;
import org.drools.vsm.GenericConnector;
import org.drools.vsm.Message;
import org.drools.vsm.mina.MinaConnector;
@@ -208,7 +209,7 @@ public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
}
}
- public class TaskWorkItemAddTaskMessageResponseHandler implements AddTaskMessageResponseHandler {
+ public class TaskWorkItemAddTaskMessageResponseHandler extends AbstractBaseResponseHandler implements AddTaskMessageResponseHandler {
private Map<Long, WorkItemManager> managers;
private Map<Long, Long> idMapping;
@@ -249,13 +250,11 @@ public void receive(Message message) {
client.registerForEvent( key, true, eventResponseHandler );
}
- public void setError(RuntimeException error) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
+
}
- private class TaskCompletedMessageHandler implements EventMessageResponseHandler {
+ private class TaskCompletedMessageHandler extends AbstractBaseResponseHandler implements EventMessageResponseHandler {
private long workItemId;
private long taskId;
private final Map<Long, WorkItemManager> managers;
@@ -266,13 +265,9 @@ public TaskCompletedMessageHandler(long workItemId, long taskId, Map<Long, WorkI
this.managers = managers;
}
- public void execute(Payload payload) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
+
- public void setError(RuntimeException error) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
+
public void receive(Message message) {
Command cmd = (Command) message.getPayload();
@@ -299,9 +294,13 @@ public void receive(Message message) {
}
}
}
+
+ public void execute(Payload payload) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
}
- private class GetCompletedTaskMessageResponseHandler implements GetTaskMessageResponseHandler {
+ private class GetCompletedTaskMessageResponseHandler extends AbstractBaseResponseHandler implements GetTaskMessageResponseHandler {
private WorkItemManager manager;
@@ -309,9 +308,7 @@ public GetCompletedTaskMessageResponseHandler(WorkItemManager manager) {
this.manager = manager;
}
- public void setError(RuntimeException error) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
+
public void receive(Message message) {
Command cmd = (Command) message.getPayload();
@@ -333,9 +330,11 @@ public void receive(Message message) {
public void execute(Task task) {
throw new UnsupportedOperationException("Not supported yet.");
}
+
+
}
- private class GetResultContentMessageResponseHandler implements GetContentMessageResponseHandler {
+ private class GetResultContentMessageResponseHandler extends AbstractBaseResponseHandler implements GetContentMessageResponseHandler {
private Task task;
private final WorkItemManager manager;
@@ -347,9 +346,7 @@ public GetResultContentMessageResponseHandler(WorkItemManager manager, Task task
this.results = results;
}
- public void setError(RuntimeException error) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
+
public void receive(Message message) {
Command cmd = (Command)message.getPayload();
diff --git a/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java b/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java
index 8ad421caff1..fcbd508b84f 100644
--- a/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java
+++ b/drools-vsm/src/test/java/org/drools/task/CommandBasedVSMWSHumanTaskHandlerTest.java
@@ -132,6 +132,7 @@ public void testTask() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
@@ -169,6 +170,7 @@ public void testTaskMultipleActors() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
@@ -214,6 +216,7 @@ public void testTaskGroupActors() throws Exception {
List<String> groupIds = new ArrayList<String>();
groupIds.add("Crusaders");
humanTaskClient.getTasksAssignedAsPotentialOwner(null, groupIds, "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary taskSummary = tasks.get(0);
@@ -271,6 +274,7 @@ public void testTaskSingleAndGroupActors() throws Exception {
List<String> groupIds = new ArrayList<String>();
groupIds.add("Crusaders");
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", groupIds, "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(2, tasks.size());
}
@@ -289,6 +293,7 @@ public void testTaskFail() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
@@ -327,6 +332,7 @@ public void testTaskSkip() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
@@ -363,6 +369,7 @@ public void testTaskAbortSkippable() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(0, tasks.size());
}
@@ -382,6 +389,7 @@ public void testTaskAbortNotSkippable() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
@@ -410,6 +418,7 @@ public void testTaskData() throws Exception {
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary taskSummary = tasks.get(0);
@@ -480,6 +489,7 @@ public void testOnAllSubTasksEndParentEndStrategy() throws Exception {
//Test if the task is succesfully created
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
@@ -625,6 +635,7 @@ public void testOnParentAbortAllSubTasksEndStrategy() throws Exception {
//Test if the task is succesfully created
BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
humanTaskClient.getTasksAssignedAsPotentialOwner("Darth Vader", "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
List<TaskSummary> tasks = responseHandler.getResults();
assertEquals(1, tasks.size());
TaskSummary task = tasks.get(0);
diff --git a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java
index 25c4ec4e956..ed5eaa2106b 100644
--- a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java
+++ b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerHumanTaskMinaRemoteTest.java
@@ -12,26 +12,42 @@
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
+import junit.framework.TestCase;
import org.apache.commons.collections.map.HashedMap;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
+import org.drools.KnowledgeBase;
+import org.drools.KnowledgeBaseProvider;
import org.drools.SystemEventListenerFactory;
+import org.drools.builder.KnowledgeBuilder;
+import org.drools.builder.KnowledgeBuilderProvider;
+import org.drools.builder.ResourceType;
+import org.drools.io.impl.ClassPathResource;
+import org.drools.runtime.StatefulKnowledgeSession;
+import org.drools.runtime.process.ProcessInstance;
import org.drools.task.Group;
import org.drools.task.User;
+import org.drools.task.query.TaskSummary;
+import org.drools.task.service.ContentData;
+import org.drools.task.service.HumanTaskServiceImpl;
import org.drools.task.service.TaskService;
import org.drools.task.service.TaskServiceSession;
import org.drools.vsm.mina.MinaAcceptor;
import org.drools.vsm.mina.MinaConnector;
import org.drools.vsm.mina.MinaIoHandler;
import org.drools.vsm.remote.ServiceManagerRemoteClient;
+import org.drools.vsm.remote.StatefulKnowledgeSessionRemoteClient;
import org.drools.vsm.task.TaskServerMessageHandlerImpl;
+import org.drools.vsm.task.responseHandlers.BlockingTaskOperationMessageResponseHandler;
+import org.drools.vsm.task.responseHandlers.BlockingTaskSummaryMessageResponseHandler;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.compiler.ExpressionCompiler;
-public class ServiceManagerHumanTaskMinaRemoteTest extends ServiceManagerTestBase {
+public class ServiceManagerHumanTaskMinaRemoteTest extends TestCase {
+ //extends ServiceManagerTestBase {
AcceptorService server;
AcceptorService humanTaskServer;
@@ -40,7 +56,10 @@ public class ServiceManagerHumanTaskMinaRemoteTest extends ServiceManagerTestBas
protected TaskServiceSession taskSession;
protected Map<String, User> users;
protected Map<String, Group> groups;
-
+ private HumanTaskService htClient;
+ private static final int DEFAULT_WAIT_TIME = 5000;
+ protected ServiceManager client;
+
protected void setUp() throws Exception {
// Configure persistence to be used inside the WSHT Service
// Use persistence.xml configuration
@@ -134,6 +153,7 @@ protected void tearDown() throws Exception {
((ServiceManagerRemoteClient) client).disconnect();
this.server.stop();
this.humanTaskServer.stop();
+
}
public Object eval(Reader reader, Map<String, Object> vars) {
@@ -164,4 +184,69 @@ public String toString(Reader reader) throws IOException {
sb.append((char) charValue);
return sb.toString();
}
+ public void testHumanTasks() throws Exception {
+
+ KnowledgeBuilderProvider kbuilderFactory = this.client.getKnowledgeBuilderFactory();
+ KnowledgeBuilder kbuilder = kbuilderFactory.newKnowledgeBuilder();
+ kbuilder.add( new ClassPathResource("rules/humanTasks.rf"),
+ ResourceType.DRF );
+
+ if ( kbuilder.hasErrors() ) {
+ System.out.println( "Errors: " + kbuilder.getErrors() );
+ }
+
+ KnowledgeBaseProvider kbaseFactory = this.client.getKnowledgeBaseFactory();
+ KnowledgeBase kbase = kbaseFactory.newKnowledgeBase();
+
+ kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
+ StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+
+ ((StatefulKnowledgeSessionRemoteClient)ksession).registerWorkItemHandler("Human Task", "org.drools.vsm.task.CommandBasedVSMWSHumanTaskHandler");
+ ProcessInstance processInstance = ksession.startProcess("org.drools.test.humanTasks");
+ HumanTaskServiceProvider humanTaskServiceFactory = this.client.getHumanTaskService();
+ htClient = humanTaskServiceFactory.newHumanTaskServiceClient();
+
+ Thread.sleep(1000);
+
+ ksession.fireAllRules();
+
+ System.out.println("First Task Execution");
+ assertEquals(true , executeNextTask("lucaz"));
+ Thread.sleep(8000);
+ System.out.println("Second Task Execution");
+ assertEquals(true , executeNextTask("lucaz"));
+ System.out.println("Inexistent Task Execution");
+ Thread.sleep(8000);
+ assertEquals(false, executeNextTask("lucaz"));
+
+ }
+
+ private boolean executeNextTask(String user) {
+
+ BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
+ ((HumanTaskServiceImpl)htClient).getTasksAssignedAsPotentialOwner(user, "en-UK", responseHandler);
+ responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
+
+ if (responseHandler.getResults().size()==0)
+ return false;
+
+ TaskSummary task = responseHandler.getResults().get(0);
+ ContentData data = new ContentData();
+ data.setContent("next step".getBytes());
+
+ BlockingTaskOperationMessageResponseHandler startResponseHandler = new BlockingTaskOperationMessageResponseHandler();
+ ((HumanTaskServiceImpl)htClient).start(task.getId(), user, startResponseHandler );
+ startResponseHandler.waitTillDone(DEFAULT_WAIT_TIME);
+
+ System.out.println("Started Task " + task.getId());
+
+ BlockingTaskOperationMessageResponseHandler completeResponseHandler = new BlockingTaskOperationMessageResponseHandler();
+ ((HumanTaskServiceImpl)htClient).complete(task.getId(), user, null , completeResponseHandler);
+ completeResponseHandler.waitTillDone(DEFAULT_WAIT_TIME);
+ System.out.println("Completed Task " + task.getId());
+
+ return true;
+ }
+
}
diff --git a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java
index 3cde4428027..adc8e8ed7d1 100644
--- a/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java
+++ b/drools-vsm/src/test/java/org/drools/vsm/ServiceManagerTestBase.java
@@ -9,24 +9,16 @@
import org.drools.builder.ResourceType;
import org.drools.command.runtime.rule.FireAllRulesCommand;
import org.drools.io.ResourceFactory;
-import org.drools.io.impl.ClassPathResource;
import org.drools.runtime.ExecutionResults;
import org.drools.runtime.StatefulKnowledgeSession;
-import org.drools.runtime.process.ProcessInstance;
-import org.drools.task.query.TaskSummary;
-import org.drools.task.service.ContentData;
-import org.drools.task.service.HumanTaskServiceImpl;
-import org.drools.vsm.remote.StatefulKnowledgeSessionRemoteClient;
-import org.drools.vsm.task.responseHandlers.BlockingTaskOperationMessageResponseHandler;
-import org.drools.vsm.task.responseHandlers.BlockingTaskSummaryMessageResponseHandler;
public class ServiceManagerTestBase extends TestCase {
- private static final int DEFAULT_WAIT_TIME = 5000;
+
protected ServiceManager client;
- private HumanTaskService htClient;
+
public void testFireAllRules() throws Exception {
String str = "";
@@ -187,69 +179,5 @@ public void testVsmPipeline() throws Exception {
// assertEquals( 2, (int ) ( Integer) results.getValue( "fired" ) );
}
- public void testHumanTasks() throws Exception {
-
- KnowledgeBuilderProvider kbuilderFactory = this.client.getKnowledgeBuilderFactory();
- KnowledgeBuilder kbuilder = kbuilderFactory.newKnowledgeBuilder();
- kbuilder.add( new ClassPathResource("rules/humanTasks.rf"),
- ResourceType.DRF );
-
- if ( kbuilder.hasErrors() ) {
- System.out.println( "Errors: " + kbuilder.getErrors() );
- }
-
- KnowledgeBaseProvider kbaseFactory = this.client.getKnowledgeBaseFactory();
- KnowledgeBase kbase = kbaseFactory.newKnowledgeBase();
-
- kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
-
- StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
-
- ((StatefulKnowledgeSessionRemoteClient)ksession).registerWorkItemHandler("Human Task", "org.drools.vsm.task.CommandBasedVSMWSHumanTaskHandler");
- ProcessInstance processInstance = ksession.startProcess("org.drools.test.humanTasks");
- HumanTaskServiceProvider humanTaskServiceFactory = this.client.getHumanTaskService();
- htClient = humanTaskServiceFactory.newHumanTaskServiceClient();
-
- Thread.sleep(1000);
-
- ksession.fireAllRules();
-
- System.out.println("First Task Execution");
- assertEquals(true , executeNextTask("lucaz"));
- Thread.sleep(8000);
- System.out.println("Second Task Execution");
- assertEquals(true , executeNextTask("lucaz"));
- System.out.println("Inexistent Task Execution");
- Thread.sleep(8000);
- assertEquals(false, executeNextTask("lucaz"));
-
- }
-
- private boolean executeNextTask(String user) {
-
- BlockingTaskSummaryMessageResponseHandler responseHandler = new BlockingTaskSummaryMessageResponseHandler();
- ((HumanTaskServiceImpl)htClient).getTasksAssignedAsPotentialOwner(user, "en-UK", responseHandler);
- responseHandler.waitTillDone(DEFAULT_WAIT_TIME);
-
- if (responseHandler.getResults().size()==0)
- return false;
-
- TaskSummary task = responseHandler.getResults().get(0);
- ContentData data = new ContentData();
- data.setContent("next step".getBytes());
-
- BlockingTaskOperationMessageResponseHandler startResponseHandler = new BlockingTaskOperationMessageResponseHandler();
- ((HumanTaskServiceImpl)htClient).start(task.getId(), user, startResponseHandler );
- startResponseHandler.waitTillDone(DEFAULT_WAIT_TIME);
-
- System.out.println("Started Task " + task.getId());
-
- BlockingTaskOperationMessageResponseHandler completeResponseHandler = new BlockingTaskOperationMessageResponseHandler();
- ((HumanTaskServiceImpl)htClient).complete(task.getId(), user, null , completeResponseHandler);
- completeResponseHandler.waitTillDone(DEFAULT_WAIT_TIME);
- System.out.println("Completed Task " + task.getId());
-
- return true;
- }
-
+
}
|
42b44788e9f7d9a84ef6ae65a38a581c22fc7c55
|
drools
|
-removed @ignore for passing test, updated to- central test helper methods--
|
p
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/RulebasePartitioningTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/RulebasePartitioningTest.java
index e0e7a9cbf79..72a8df50b6e 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/RulebasePartitioningTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/RulebasePartitioningTest.java
@@ -31,7 +31,7 @@
public class RulebasePartitioningTest extends CommonTestMethodBase {
- @Test
+ @Test
@Ignore
public void testRulebasePartitions1() throws Exception {
final PackageBuilder builder = new PackageBuilder();
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/WorkingMemoryLoggerTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/WorkingMemoryLoggerTest.java
index 66858f5a535..949283c669f 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/WorkingMemoryLoggerTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/WorkingMemoryLoggerTest.java
@@ -3,6 +3,7 @@
import java.io.InputStreamReader;
import java.io.Reader;
+import org.drools.compiler.CommonTestMethodBase;
import org.drools.core.RuleBase;
import org.drools.core.RuleBaseFactory;
import org.drools.core.StatefulSession;
@@ -10,23 +11,19 @@
import org.drools.compiler.compiler.PackageBuilder;
import org.junit.Ignore;
import org.junit.Test;
+import org.kie.api.KieBase;
+import org.kie.internal.KnowledgeBase;
+import org.kie.internal.runtime.StatefulKnowledgeSession;
-public class WorkingMemoryLoggerTest {
-
- private static final Reader DRL = new InputStreamReader(
- WorkingMemoryLoggerTest.class.getResourceAsStream("empty.drl"));
-
+public class WorkingMemoryLoggerTest extends CommonTestMethodBase {
private static final String LOG = "session";
+
@Test
- @Ignore
public void testOutOfMemory() throws Exception {
- PackageBuilder builder = new PackageBuilder();
- builder.addPackageFromDrl(DRL);
- RuleBase ruleBase = RuleBaseFactory.newRuleBase();
- ruleBase.addPackage(builder.getPackage());
+ KnowledgeBase kbase = loadKnowledgeBase( "empty.drl");
+
for (int i = 0; i < 10000; i++) {
- //System.out.println(i);
- StatefulSession session = ruleBase.newStatefulSession();
+ StatefulKnowledgeSession session = createKnowledgeSession(kbase);
WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger(session);
session.fireAllRules();
session.dispose();
|
75fd6d4985f9e1b74294d1c8a21b5a559f0c96fd
|
elasticsearch
|
Added KeywordRepeatFilter that allows emitting- stemmed and unstemmed versions of the same token if stemmers are used--Closes -2753-
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java b/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java
new file mode 100644
index 0000000000000..ec8ad4d12f312
--- /dev/null
+++ b/src/main/java/org/apache/lucene/analysis/miscellaneous/KeywordRepeatFilter.java
@@ -0,0 +1,71 @@
+/*
+ * 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.apache.lucene.analysis.miscellaneous;
+
+import org.apache.lucene.analysis.TokenFilter;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.tokenattributes.KeywordAttribute;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+
+import java.io.IOException;
+
+
+/**
+ * This TokenFilter emits each incoming token twice once as keyword and once non-keyword, in other words once with
+ * {@link KeywordAttribute#setKeyword(boolean)} set to <code>true</code> and once set to <code>false</code>.
+ * This is useful if used with a stem filter that respects the {@link KeywordAttribute} to index the stemmed and the
+ * un-stemmed version of a term into the same field.
+ */
+//LUCENE MONITOR - this will be included in Lucene 4.3. (it's a plain copy of the lucene version)
+
+public final class KeywordRepeatFilter extends TokenFilter {
+ private final KeywordAttribute keywordAttribute = addAttribute(KeywordAttribute.class);
+ private final PositionIncrementAttribute posIncAttr = addAttribute(PositionIncrementAttribute.class);
+ private State state;
+
+ /**
+ * Construct a token stream filtering the given input.
+ */
+ public KeywordRepeatFilter(TokenStream input) {
+ super(input);
+ }
+
+ @Override
+ public boolean incrementToken() throws IOException {
+ if (state != null) {
+ restoreState(state);
+ posIncAttr.setPositionIncrement(0);
+ keywordAttribute.setKeyword(false);
+ state = null;
+ return true;
+ }
+ if (input.incrementToken()) {
+ state = captureState();
+ keywordAttribute.setKeyword(true);
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void reset() throws IOException {
+ super.reset();
+ state = null;
+ }
+}
diff --git a/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java b/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java
index 32f9c2f1b55cc..40ebfa9d16b58 100644
--- a/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java
+++ b/src/main/java/org/elasticsearch/indices/analysis/IndicesAnalysisService.java
@@ -642,6 +642,17 @@ public TokenStream create(TokenStream tokenStream) {
return new SnowballFilter(tokenStream, "Russian");
}
}));
+ tokenFilterFactories.put("keyword_repeat", new PreBuiltTokenFilterFactoryFactory(new TokenFilterFactory() {
+ @Override
+ public String name() {
+ return "keyword_repeat";
+ }
+
+ @Override
+ public TokenStream create(TokenStream tokenStream) {
+ return new KeywordRepeatFilter(tokenStream);
+ }
+ }));
// Char Filter
charFilterFactories.put("html_strip", new PreBuiltCharFilterFactoryFactory(new CharFilterFactory() {
diff --git a/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java b/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java
index 165d3748c7fbc..56820b36fedc2 100644
--- a/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java
+++ b/src/test/java/org/elasticsearch/test/unit/index/analysis/AnalysisModuleTests.java
@@ -20,7 +20,12 @@
package org.elasticsearch.test.unit.index.analysis;
import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.Tokenizer;
+import org.apache.lucene.analysis.core.WhitespaceTokenizer;
+import org.apache.lucene.analysis.miscellaneous.KeywordRepeatFilter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.util.Version;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.ModulesBuilder;
import org.elasticsearch.common.lucene.Lucene;
@@ -42,6 +47,7 @@
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
+import java.io.StringReader;
import java.util.Set;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
@@ -65,6 +71,15 @@ public void testSimpleConfigurationYaml() {
Settings settings = settingsBuilder().loadFromClasspath("org/elasticsearch/test/unit/index/analysis/test1.yml").build();
testSimpleConfiguration(settings);
}
+
+ @Test
+ public void testDefaultFactory() {
+ AnalysisService analysisService = AnalysisTestsHelper.createAnalysisServiceFromSettings(ImmutableSettings.settingsBuilder().build());
+ TokenFilterFactory tokenFilter = analysisService.tokenFilter("keyword_repeat");
+ Tokenizer tokenizer = new WhitespaceTokenizer(Version.LUCENE_36, new StringReader("foo bar"));
+ TokenStream stream = tokenFilter.create(tokenizer);
+ assertThat(stream, instanceOf(KeywordRepeatFilter.class));
+ }
private void testSimpleConfiguration(Settings settings) {
Index index = new Index("test");
|
61edb8bd082810d16bb25ac4a526df4ac036f3fa
|
restlet-framework-java
|
Fixed "not found" status for Options requests.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlApplication.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlApplication.java
index 924edf6512..c1242bc579 100644
--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlApplication.java
+++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlApplication.java
@@ -531,7 +531,10 @@ private ResourceInfo getResourceInfo(Restlet restlet, String path,
Request request, Response response) {
ResourceInfo result = null;
- if (restlet instanceof Finder) {
+ if (restlet instanceof WadlDescribable) {
+ result = ((WadlDescribable) restlet).getResourceInfo();
+ result.setPath(path);
+ } else if (restlet instanceof Finder) {
result = getResourceInfo((Finder) restlet, path, request, response);
} else if (restlet instanceof Router) {
result = new ResourceInfo();
@@ -541,7 +544,6 @@ private ResourceInfo getResourceInfo(Restlet restlet, String path,
} else if (restlet instanceof Filter) {
result = getResourceInfo((Filter) restlet, path, request, response);
}
-
return result;
}
@@ -691,6 +693,9 @@ public void handle(Request request, Response response) {
// Returns a WADL representation of the application.
response.setEntity(wadlRepresent(request, response));
+ if (response.isEntityAvailable()) {
+ response.setStatus(Status.SUCCESS_OK);
+ }
}
}
|
022cb87f855ef3cd6ed04037f8c0ef42b9b59fbe
|
orientdb
|
Fix by Luca Molino on schema and in-thread db--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java
index 19b49eb35e7..8a986e41597 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java
@@ -129,9 +129,9 @@ public OClass getSuperClass() {
* @return the object itself.
*/
public OClass setSuperClass(final OClass iSuperClass) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
final String cmd = String.format("alter class %s superclass %s", name, iSuperClass.getName());
- document.getDatabase().command(new OCommandSQL(cmd)).execute();
+ getDatabase().command(new OCommandSQL(cmd)).execute();
setSuperClassInternal(iSuperClass);
return this;
}
@@ -146,15 +146,15 @@ public String getName() {
}
public OClass setName(final String iName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
final String cmd = String.format("alter class %s name %s", name, iName);
- document.getDatabase().command(new OCommandSQL(cmd)).execute();
+ getDatabase().command(new OCommandSQL(cmd)).execute();
name = iName;
return this;
}
public void setNameInternal(final String iName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
owner.changeClassName(name, iName);
name = iName;
}
@@ -164,15 +164,15 @@ public String getShortName() {
}
public OClass setShortName(final String iShortName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
final String cmd = String.format("alter class %s shortname %s", name, iShortName);
- document.getDatabase().command(new OCommandSQL(cmd)).execute();
+ getDatabase().command(new OCommandSQL(cmd)).execute();
setShortNameInternal(iShortName);
return this;
}
public void setShortNameInternal(final String shortName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
if (this.shortName != null)
// UNREGISTER ANY PREVIOUS SHORT NAME
owner.classes.remove(shortName);
@@ -192,7 +192,7 @@ public Collection<OProperty> declaredProperties() {
}
public Collection<OProperty> properties() {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
Collection<OProperty> props = null;
@@ -213,7 +213,7 @@ public Collection<OProperty> properties() {
}
public Collection<OProperty> getIndexedProperties() {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_READ);
Collection<OProperty> indexedProps = null;
@@ -278,7 +278,7 @@ public boolean existsProperty(final String iPropertyName) {
}
public void dropProperty(final String iPropertyName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
final String lowerName = iPropertyName.toLowerCase();
@@ -291,14 +291,14 @@ public void dropProperty(final String iPropertyName) {
cmd.append('.');
cmd.append(iPropertyName);
- document.getDatabase().command(new OCommandSQL(cmd.toString())).execute();
+ getDatabase().command(new OCommandSQL(cmd.toString())).execute();
if (existsProperty(iPropertyName))
properties.remove(lowerName);
}
public void dropPropertyInternal(final String iPropertyName) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_DELETE);
final OProperty prop = properties.remove(iPropertyName.toLowerCase());
@@ -311,7 +311,7 @@ public void dropPropertyInternal(final String iPropertyName) {
}
public OProperty addProperty(final String iPropertyName, final OType iType, final OType iLinkedType, final OClass iLinkedClass) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
final String lowerName = iPropertyName.toLowerCase();
@@ -339,7 +339,7 @@ public OProperty addProperty(final String iPropertyName, final OType iType, fina
cmd.append(iLinkedClass.getName());
}
- document.getDatabase().command(new OCommandSQL(cmd.toString())).execute();
+ getDatabase().command(new OCommandSQL(cmd.toString())).execute();
if (existsProperty(iPropertyName))
return properties.get(lowerName);
@@ -374,7 +374,7 @@ public void fromStream() {
OPropertyImpl prop;
Collection<ODocument> storedProperties = document.field("properties");
for (ODocument p : storedProperties) {
- p.setDatabase(document.getDatabase());
+ p.setDatabase(getDatabase());
prop = new OPropertyImpl(this, p);
prop.fromStream();
properties.put(prop.getName().toLowerCase(), prop);
@@ -492,15 +492,15 @@ public float getOverSize() {
}
public OClass setOverSize(final float overSize) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
final String cmd = String.format("alter class %s oversize %f", name, overSize);
- document.getDatabase().command(new OCommandSQL(cmd)).execute();
+ getDatabase().command(new OCommandSQL(cmd)).execute();
setOverSizeInternal(overSize);
return this;
}
public void setOverSizeInternal(final float overSize) {
- document.getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
+ getDatabase().checkSecurity(ODatabaseSecurityResources.SCHEMA, ORole.PERMISSION_UPDATE);
this.overSize = overSize;
}
@@ -644,7 +644,7 @@ public void setInternalAndSave(final ATTRIBUTES attribute, final Object iValue)
setShortNameInternal(stringValue);
break;
case SUPERCLASS:
- setSuperClassInternal(document.getDatabase().getMetadata().getSchema().getClass(stringValue));
+ setSuperClassInternal(getDatabase().getMetadata().getSchema().getClass(stringValue));
break;
case OVERSIZE:
setOverSizeInternal(Float.parseFloat(stringValue.replace(',', '.')));
@@ -668,7 +668,7 @@ public OClass set(final ATTRIBUTES attribute, final Object iValue) {
setShortName(stringValue);
break;
case SUPERCLASS:
- setSuperClass(document.getDatabase().getMetadata().getSchema().getClass(stringValue));
+ setSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue));
break;
case OVERSIZE:
setOverSize(Float.parseFloat(stringValue));
|
6f1932ab677b4e544fa964a6aacc7e888613ff2f
|
elasticsearch
|
support yaml detection on char sequence--
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java b/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java
index c01709db88b6f..50565dbba88d3 100644
--- a/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java
+++ b/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java
@@ -115,6 +115,21 @@ public static XContent xContent(XContentType type) {
*/
public static XContentType xContentType(CharSequence content) {
int length = content.length() < GUESS_HEADER_LENGTH ? content.length() : GUESS_HEADER_LENGTH;
+ if (length == 0) {
+ return null;
+ }
+ char first = content.charAt(0);
+ if (first == '{') {
+ return XContentType.JSON;
+ }
+ // Should we throw a failure here? Smile idea is to use it in bytes....
+ if (length > 2 && first == SmileConstants.HEADER_BYTE_1 && content.charAt(1) == SmileConstants.HEADER_BYTE_2 && content.charAt(2) == SmileConstants.HEADER_BYTE_3) {
+ return XContentType.SMILE;
+ }
+ if (length > 2 && first == '-' && content.charAt(1) == '-' && content.charAt(2) == '-') {
+ return XContentType.YAML;
+ }
+
for (int i = 0; i < length; i++) {
char c = content.charAt(i);
if (c == '{') {
|
18e0bff6dbfd5189d2975574c273fe6f1208ba43
|
drools
|
JBRULES-313: adding fire limit option--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@12927 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
index 08dd4a3e144..cf773cca262 100644
--- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
+++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java
@@ -2945,6 +2945,52 @@ public void testHalt() throws Exception {
}
}
+ public void testFireLimit() throws Exception {
+ final PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_fireLimit.drl" ) ) );
+ final Package pkg = builder.getPackage();
+
+ final RuleBase ruleBase = getRuleBase();
+ ruleBase.addPackage( pkg );
+ final WorkingMemory workingMemory = ruleBase.newStatefulSession();
+
+ final List results = new ArrayList();
+ workingMemory.setGlobal( "results",
+ results );
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules();
+
+ assertEquals( 20,
+ results.size() );
+ for( int i = 0; i < 20; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules( 10 );
+
+ assertEquals( 10,
+ results.size() );
+ for( int i = 0; i < 10; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+ workingMemory.insert( new Integer( 0 ) );
+ workingMemory.fireAllRules( -1 );
+
+ assertEquals( 20,
+ results.size() );
+ for( int i = 0; i < 20; i++ ) {
+ assertEquals( new Integer( i ), results.get( i ) );
+ }
+ results.clear();
+
+
+ }
+
}
\ No newline at end of file
diff --git a/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl b/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl
new file mode 100644
index 00000000000..20c1ea9c1ff
--- /dev/null
+++ b/drools-compiler/src/test/resources/org/drools/integrationtests/test_fireLimit.drl
@@ -0,0 +1,21 @@
+package org.drools;
+
+global java.util.List results;
+
+rule "fire"
+when
+ $old : Number( $val : intValue )
+then
+ results.add( $old );
+ insert( new Integer( $val + 1 ) );
+ retract( $old );
+end
+
+rule "stop"
+ salience 10
+when
+ $old : Number( intValue == 20 )
+then
+ retract( $old );
+ drools.halt();
+end
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/WorkingMemory.java b/drools-core/src/main/java/org/drools/WorkingMemory.java
index 9887e14b991..a72995fd5ca 100644
--- a/drools-core/src/main/java/org/drools/WorkingMemory.java
+++ b/drools-core/src/main/java/org/drools/WorkingMemory.java
@@ -162,6 +162,22 @@ void setGlobal(String name,
*/
void fireAllRules(AgendaFilter agendaFilter) throws FactException;
+ /**
+ * Fire all items on the agenda until empty or at most 'fireLimit' rules have fired
+ *
+ * @throws FactException
+ * If an error occurs.
+ */
+ void fireAllRules( int fireLimit ) throws FactException;
+
+ /**
+ * Fire all items on the agenda using the given AgendaFiler
+ * until empty or at most 'fireLimit' rules have fired
+ *
+ * @throws FactException
+ * If an error occurs.
+ */
+ void fireAllRules(final AgendaFilter agendaFilter, int fireLimit ) throws FactException;
/**
* Retrieve the object associated with a <code>FactHandle</code>.
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 52d6cea401e..3acbc7deca1 100644
--- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
+++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java
@@ -404,10 +404,18 @@ public void halt() {
* @see WorkingMemory
*/
public synchronized void fireAllRules() throws FactException {
- fireAllRules( null );
+ fireAllRules( null, -1 );
}
- public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws FactException {
+ public synchronized void fireAllRules( int fireLimit ) throws FactException {
+ fireAllRules( null, fireLimit );
+ }
+
+ public synchronized void fireAllRules( final AgendaFilter agendaFilter ) throws FactException {
+ fireAllRules( agendaFilter, -1 );
+ }
+
+ public synchronized void fireAllRules(final AgendaFilter agendaFilter, int fireLimit ) throws FactException {
// If we're already firing a rule, then it'll pick up
// the firing for any other assertObject(..) that get
// nested inside, avoiding concurrent-modification
@@ -430,7 +438,8 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa
try {
this.firing = true;
- while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) {
+ while ( continueFiring( fireLimit ) && this.agenda.fireNextItem( agendaFilter ) ) {
+ fireLimit = updateFireLimit( fireLimit );
noneFired = false;
if ( !this.actionQueue.isEmpty() ) {
executeQueuedActions();
@@ -439,26 +448,34 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa
} finally {
this.firing = false;
if ( noneFired ) {
- doOtherwise( agendaFilter );
+ doOtherwise( agendaFilter, fireLimit );
}
}
}
}
+
+ private final boolean continueFiring( final int fireLimit ) {
+ return (!halt) && (fireLimit != 0 );
+ }
+
+ private final int updateFireLimit( final int fireLimit ) {
+ return fireLimit > 0 ? fireLimit-1 : fireLimit;
+ }
/**
* This does the "otherwise" phase of processing.
* If no items are fired, then it will assert a temporary "Otherwise"
* fact and allow any rules to fire to handle "otherwise" cases.
*/
- private void doOtherwise(final AgendaFilter agendaFilter) {
+ private void doOtherwise(final AgendaFilter agendaFilter, int fireLimit ) {
final FactHandle handle = this.insert( new Otherwise() );
if ( !this.actionQueue.isEmpty() ) {
executeQueuedActions();
}
- while ( (!halt) && this.agenda.fireNextItem( agendaFilter ) ) {
- ;
+ while ( continueFiring( fireLimit ) && this.agenda.fireNextItem( agendaFilter ) ) {
+ fireLimit = updateFireLimit( fireLimit );
}
this.retract( handle );
|
d66a477781a6e081bb62bbd87270c9a3aacb5a40
|
hadoop
|
YARN-2111. In FairScheduler.attemptScheduling, we- don't count containers as assigned if they have 0 memory but non-zero cores- (Sandy Ryza)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1605115 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 cdd561bf8a94d..32a62df35ec4e 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -255,6 +255,9 @@ Release 2.5.0 - UNRELEASED
YARN-2187. FairScheduler: Disable max-AM-share check by default.
(Robert Kanter via kasha)
+ YARN-2111. In FairScheduler.attemptScheduling, we don't count containers
+ as assigned if they have 0 memory but non-zero cores (Sandy Ryza)
+
Release 2.4.1 - 2014-06-23
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
index ea53165c63236..a042acd185fb0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
@@ -1033,9 +1033,8 @@ private synchronized void attemptScheduling(FSSchedulerNode node) {
int assignedContainers = 0;
while (node.getReservedContainer() == null) {
boolean assignedContainer = false;
- if (Resources.greaterThan(RESOURCE_CALCULATOR, clusterResource,
- queueMgr.getRootQueue().assignContainer(node),
- Resources.none())) {
+ if (!queueMgr.getRootQueue().assignContainer(node).equals(
+ Resources.none())) {
assignedContainers++;
assignedContainer = true;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
index 41ad896a9d0aa..68e6f14c3d4dd 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
@@ -1661,6 +1661,41 @@ public void testMaxAssign() throws Exception {
assertEquals("Incorrect number of containers allocated", 8, app
.getLiveContainers().size());
}
+
+ @Test(timeout = 3000)
+ public void testMaxAssignWithZeroMemoryContainers() throws Exception {
+ conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true);
+ conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0);
+
+ scheduler.init(conf);
+ scheduler.start();
+ scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+ RMNode node =
+ MockNodes.newNodeInfo(1, Resources.createResource(16384, 16), 0,
+ "127.0.0.1");
+ NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node);
+ NodeUpdateSchedulerEvent updateEvent = new NodeUpdateSchedulerEvent(node);
+ scheduler.handle(nodeEvent);
+
+ ApplicationAttemptId attId =
+ createSchedulingRequest(0, 1, "root.default", "user", 8);
+ FSSchedulerApp app = scheduler.getSchedulerApp(attId);
+
+ // set maxAssign to 2: only 2 containers should be allocated
+ scheduler.maxAssign = 2;
+ scheduler.update();
+ scheduler.handle(updateEvent);
+ assertEquals("Incorrect number of containers allocated", 2, app
+ .getLiveContainers().size());
+
+ // set maxAssign to -1: all remaining containers should be allocated
+ scheduler.maxAssign = -1;
+ scheduler.update();
+ scheduler.handle(updateEvent);
+ assertEquals("Incorrect number of containers allocated", 8, app
+ .getLiveContainers().size());
+ }
/**
* Test to verify the behavior of
|
80636e5a6f8e4283b0470306331c013c2ea38018
|
restlet-framework-java
|
Fixed bug--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/main/com/noelios/restlet/util/UniformCallModel.java b/source/main/com/noelios/restlet/util/UniformCallModel.java
index 3bbf8a82f9..172d18540f 100644
--- a/source/main/com/noelios/restlet/util/UniformCallModel.java
+++ b/source/main/com/noelios/restlet/util/UniformCallModel.java
@@ -118,7 +118,7 @@ public String get(String name)
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -155,7 +155,7 @@ else if(name.startsWith(NAME_COOKIE))
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -168,7 +168,7 @@ else if(rest.equals("last"))
else if((rest.charAt(0) == '"') && (rest.charAt(rest.length() - 1) == '"'))
{
// Lookup by name
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
result = CookieUtils.getFirstCookie(call.getCookies(), rest).getValue();
}
else
@@ -234,7 +234,7 @@ else if(name.startsWith(NAME_RESOURCE_QUERY))
if((rest.charAt(0) == '[') && (rest.charAt(rest.length() - 1) == ']'))
{
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
if(rest.equals("first"))
{
@@ -248,7 +248,7 @@ else if(rest.equals("last"))
else if((rest.charAt(0) == '"') && (rest.charAt(rest.length() - 1) == '"'))
{
// Lookup by name
- rest = rest.substring(1, rest.length() - 2);
+ rest = rest.substring(1, rest.length() - 1);
result = call.getResourceRef().getQueryAsForm().getFirstParameter(rest).getValue();
}
else
|
cef0b916c546bf6178b493eafc1ea4adb0357e18
|
ReactiveX-RxJava
|
1.x: ConcatMapEager allow nulls from inner- Observables.--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java b/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
index 4df115b7ae..bbf2bcc48b 100644
--- a/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
+++ b/src/main/java/rx/internal/operators/OperatorEagerConcatMap.java
@@ -166,6 +166,7 @@ void drain() {
final AtomicLong requested = sharedProducer;
final Subscriber<? super R> actualSubscriber = this.actual;
+ final NotificationLite<R> nl = NotificationLite.instance();
for (;;) {
@@ -200,13 +201,13 @@ void drain() {
long emittedAmount = 0L;
boolean unbounded = requestedAmount == Long.MAX_VALUE;
- Queue<R> innerQueue = innerSubscriber.queue;
+ Queue<Object> innerQueue = innerSubscriber.queue;
boolean innerDone = false;
for (;;) {
outerDone = innerSubscriber.done;
- R v = innerQueue.peek();
+ Object v = innerQueue.peek();
empty = v == null;
if (outerDone) {
@@ -237,7 +238,7 @@ void drain() {
innerQueue.poll();
try {
- actualSubscriber.onNext(v);
+ actualSubscriber.onNext(nl.getValue(v));
} catch (Throwable ex) {
Exceptions.throwOrReport(ex, actualSubscriber, v);
return;
@@ -271,7 +272,8 @@ void drain() {
static final class EagerInnerSubscriber<T> extends Subscriber<T> {
final EagerOuterSubscriber<?, T> parent;
- final Queue<T> queue;
+ final Queue<Object> queue;
+ final NotificationLite<T> nl;
volatile boolean done;
Throwable error;
@@ -279,19 +281,20 @@ static final class EagerInnerSubscriber<T> extends Subscriber<T> {
public EagerInnerSubscriber(EagerOuterSubscriber<?, T> parent, int bufferSize) {
super();
this.parent = parent;
- Queue<T> q;
+ Queue<Object> q;
if (UnsafeAccess.isUnsafeAvailable()) {
- q = new SpscArrayQueue<T>(bufferSize);
+ q = new SpscArrayQueue<Object>(bufferSize);
} else {
- q = new SpscAtomicArrayQueue<T>(bufferSize);
+ q = new SpscAtomicArrayQueue<Object>(bufferSize);
}
this.queue = q;
+ this.nl = NotificationLite.instance();
request(bufferSize);
}
@Override
public void onNext(T t) {
- queue.offer(t);
+ queue.offer(nl.next(t));
parent.drain();
}
diff --git a/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java b/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
index 8c7bd3d9e4..8d2d40bed4 100644
--- a/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
+++ b/src/test/java/rx/internal/operators/OperatorEagerConcatMapTest.java
@@ -394,4 +394,20 @@ public void call(Integer t) {
ts.assertNotCompleted();
Assert.assertEquals(RxRingBuffer.SIZE, count.get());
}
+
+ @Test
+ public void testInnerNull() {
+ TestSubscriber<Object> ts = TestSubscriber.create();
+
+ Observable.just(1).concatMapEager(new Func1<Integer, Observable<Integer>>() {
+ @Override
+ public Observable<Integer> call(Integer t) {
+ return Observable.just(null);
+ }
+ }).subscribe(ts);
+
+ ts.assertNoErrors();
+ ts.assertCompleted();
+ ts.assertValue(null);
+ }
}
|
610115b44e10e5046b62a7dfad06dde18e0f83e7
|
camel
|
added explicit generics to avoid possible- compiler wierdness in the DSL like we had yesterday where the compiler- decided to use Object rather than ProcessorType in some DSL expressions--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@585089 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/model/BeanRef.java b/camel-core/src/main/java/org/apache/camel/model/BeanRef.java
index cfd52e806d841..6a1dabd8c1bc7 100644
--- a/camel-core/src/main/java/org/apache/camel/model/BeanRef.java
+++ b/camel-core/src/main/java/org/apache/camel/model/BeanRef.java
@@ -33,7 +33,7 @@
*/
@XmlRootElement(name = "bean")
@XmlAccessorType(XmlAccessType.FIELD)
-public class BeanRef extends OutputType {
+public class BeanRef extends OutputType<ProcessorType> {
@XmlAttribute(required = true)
private String ref;
@XmlAttribute(required = false)
diff --git a/camel-core/src/main/java/org/apache/camel/model/CatchType.java b/camel-core/src/main/java/org/apache/camel/model/CatchType.java
index dd345a526e27d..0195cf6d6ba83 100644
--- a/camel-core/src/main/java/org/apache/camel/model/CatchType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/CatchType.java
@@ -36,7 +36,7 @@
*/
@XmlRootElement(name = "catch")
@XmlAccessorType(XmlAccessType.FIELD)
-public class CatchType extends ProcessorType {
+public class CatchType extends ProcessorType<ProcessorType> {
@XmlElementRef
private List<InterceptorType> interceptors = new ArrayList<InterceptorType>();
@XmlElement(name = "exception")
diff --git a/camel-core/src/main/java/org/apache/camel/model/FinallyType.java b/camel-core/src/main/java/org/apache/camel/model/FinallyType.java
index 6f7a695b53c05..68175959c65cc 100644
--- a/camel-core/src/main/java/org/apache/camel/model/FinallyType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/FinallyType.java
@@ -28,7 +28,7 @@
*/
@XmlRootElement(name = "finally")
@XmlAccessorType(XmlAccessType.FIELD)
-public class FinallyType extends OutputType {
+public class FinallyType extends OutputType<ProcessorType> {
@Override
public String toString() {
return "Finally[" + getOutputs() + "]";
diff --git a/camel-core/src/main/java/org/apache/camel/model/MarshalType.java b/camel-core/src/main/java/org/apache/camel/model/MarshalType.java
index 43d4405a7b9ab..2e09d13312d0e 100644
--- a/camel-core/src/main/java/org/apache/camel/model/MarshalType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/MarshalType.java
@@ -41,7 +41,7 @@
*/
@XmlRootElement(name = "marshal")
@XmlAccessorType(XmlAccessType.FIELD)
-public class MarshalType extends OutputType {
+public class MarshalType extends OutputType<ProcessorType> {
@XmlAttribute(required = false)
private String ref;
// TODO cannot use @XmlElementRef as it doesn't allow optional properties
diff --git a/camel-core/src/main/java/org/apache/camel/model/OtherwiseType.java b/camel-core/src/main/java/org/apache/camel/model/OtherwiseType.java
index 4dd7913018bca..4d8134f9f8581 100644
--- a/camel-core/src/main/java/org/apache/camel/model/OtherwiseType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/OtherwiseType.java
@@ -28,7 +28,7 @@
*/
@XmlRootElement(name = "otherwise")
@XmlAccessorType(XmlAccessType.FIELD)
-public class OtherwiseType extends OutputType {
+public class OtherwiseType extends OutputType<ProcessorType> {
@Override
public String toString() {
diff --git a/camel-core/src/main/java/org/apache/camel/model/PolicyRef.java b/camel-core/src/main/java/org/apache/camel/model/PolicyRef.java
index f9d12b011e9a8..df4afea632e67 100644
--- a/camel-core/src/main/java/org/apache/camel/model/PolicyRef.java
+++ b/camel-core/src/main/java/org/apache/camel/model/PolicyRef.java
@@ -31,7 +31,7 @@
*/
@XmlRootElement(name = "policy")
@XmlAccessorType(XmlAccessType.FIELD)
-public class PolicyRef extends OutputType {
+public class PolicyRef extends OutputType<ProcessorType> {
@XmlAttribute(required = true)
private String ref;
@XmlTransient
diff --git a/camel-core/src/main/java/org/apache/camel/model/ProceedType.java b/camel-core/src/main/java/org/apache/camel/model/ProceedType.java
index 1cc5933f6444c..16bd3bdb3b4c2 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ProceedType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ProceedType.java
@@ -31,9 +31,9 @@
*/
@XmlRootElement(name = "proceed")
@XmlAccessorType(XmlAccessType.FIELD)
-public class ProceedType extends ProcessorType {
+public class ProceedType extends ProcessorType<ProcessorType> {
- public List<ProcessorType> getOutputs() {
+ public List<ProcessorType<?>> getOutputs() {
return Collections.EMPTY_LIST;
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorRef.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorRef.java
index 1b48b8e9c38b6..3517c0489e6ee 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ProcessorRef.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorRef.java
@@ -30,7 +30,7 @@
*/
@XmlRootElement(name = "process")
@XmlAccessorType(XmlAccessType.FIELD)
-public class ProcessorRef extends OutputType {
+public class ProcessorRef extends OutputType<ProcessorType> {
@XmlAttribute(required = true)
private String ref;
@XmlTransient
diff --git a/camel-core/src/main/java/org/apache/camel/model/ThreadType.java b/camel-core/src/main/java/org/apache/camel/model/ThreadType.java
index f88298adff365..1292763745fc7 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ThreadType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ThreadType.java
@@ -40,7 +40,7 @@
*/
@XmlRootElement(name = "thread")
@XmlAccessorType(XmlAccessType.FIELD)
-public class ThreadType extends ProcessorType {
+public class ThreadType extends ProcessorType<ProcessorType> {
@XmlAttribute
private int coreSize = 1;
@@ -57,7 +57,7 @@ public class ThreadType extends ProcessorType {
@XmlAttribute
private long stackSize;
@XmlElementRef
- private List<ProcessorType> outputs = new ArrayList<ProcessorType>();
+ private List<ProcessorType<?>> outputs = new ArrayList<ProcessorType<?>>();
@XmlTransient
private BlockingQueue<Runnable> taskQueue;
@@ -84,7 +84,7 @@ public List getInterceptors() {
}
@Override
- public List getOutputs() {
+ public List<ProcessorType<?>> getOutputs() {
return outputs;
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/ThrottlerType.java b/camel-core/src/main/java/org/apache/camel/model/ThrottlerType.java
index 0abb2d2e631af..ed3f52fce9e5d 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ThrottlerType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ThrottlerType.java
@@ -34,7 +34,7 @@
*/
@XmlRootElement(name = "throttler")
@XmlAccessorType(XmlAccessType.FIELD)
-public class ThrottlerType extends ProcessorType {
+public class ThrottlerType extends ProcessorType<ProcessorType> {
@XmlAttribute
private Long maximumRequestsPerPeriod;
@XmlAttribute
@@ -42,7 +42,7 @@ public class ThrottlerType extends ProcessorType {
@XmlElementRef
private List<InterceptorType> interceptors = new ArrayList<InterceptorType>();
@XmlElementRef
- private List<ProcessorType> outputs = new ArrayList<ProcessorType>();
+ private List<ProcessorType<?>> outputs = new ArrayList<ProcessorType<?>>();
public ThrottlerType() {
}
@@ -106,11 +106,11 @@ public void setInterceptors(List<InterceptorType> interceptors) {
this.interceptors = interceptors;
}
- public List<ProcessorType> getOutputs() {
+ public List<ProcessorType<?>> getOutputs() {
return outputs;
}
- public void setOutputs(List<ProcessorType> outputs) {
+ public void setOutputs(List<ProcessorType<?>> outputs) {
this.outputs = outputs;
}
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/ToType.java b/camel-core/src/main/java/org/apache/camel/model/ToType.java
index 483f7ec1cd5b3..b9736b15394d3 100644
--- a/camel-core/src/main/java/org/apache/camel/model/ToType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/ToType.java
@@ -40,7 +40,7 @@
*/
@XmlRootElement(name = "to")
@XmlAccessorType(XmlAccessType.FIELD)
-public class ToType extends ProcessorType {
+public class ToType extends ProcessorType<ProcessorType> {
@XmlAttribute
private String uri;
@XmlAttribute
@@ -121,7 +121,7 @@ public void setEndpoint(Endpoint endpoint) {
this.endpoint = endpoint;
}
- public List<ProcessorType> getOutputs() {
+ public List<ProcessorType<?>> getOutputs() {
return Collections.EMPTY_LIST;
}
diff --git a/camel-core/src/main/java/org/apache/camel/model/UnmarshalType.java b/camel-core/src/main/java/org/apache/camel/model/UnmarshalType.java
index 90d49b96fbe6f..b17bf67437941 100644
--- a/camel-core/src/main/java/org/apache/camel/model/UnmarshalType.java
+++ b/camel-core/src/main/java/org/apache/camel/model/UnmarshalType.java
@@ -40,7 +40,7 @@
*/
@XmlRootElement(name = "unmarshal")
@XmlAccessorType(XmlAccessType.FIELD)
-public class UnmarshalType extends OutputType {
+public class UnmarshalType extends OutputType<ProcessorType> {
@XmlAttribute(required = false)
private String ref;
// TODO cannot use @XmlElementRef as it doesn't allow optional properties
|
232612c800c2583da61b95397141040d3106efda
|
ReactiveX-RxJava
|
Incoporate review suggestions.--Splits a compound unit test into to parts.-Uses mockito instead of a bespoke test object.-Removes unused import statements.-Changes the order of the Finally action w.r.t. onComplete/onError.-
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationFinally.java b/rxjava-core/src/main/java/rx/operators/OperationFinally.java
index 4474e11936..d90b0572a6 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationFinally.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationFinally.java
@@ -18,11 +18,7 @@
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-
+import org.junit.Before;
import org.junit.Test;
import rx.Observable;
@@ -47,9 +43,10 @@ public final class OperationFinally {
* @param sequence An observable sequence of elements
* @param action An action to be taken when the sequence is complete or throws an exception
* @return An observable sequence with the same elements as the input.
- * After the last element is consumed (just before {@link Observer#onComplete} is called),
- * or when an exception is thrown (just before {@link Observer#onError}), the action will be called.
- * @see http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx
+ * After the last element is consumed (and {@link Observer#onCompleted} has been called),
+ * or after an exception is thrown (and {@link Observer#onError} has been called),
+ * the given action will be called.
+ * @see <a href="http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx">MSDN Observable.Finally method</a>
*/
public static <T> Func1<Observer<T>, Subscription> finally0(final Observable<T> sequence, final Action0 action) {
return new Func1<Observer<T>, Subscription>() {
@@ -94,14 +91,14 @@ private class FinallyObserver implements Observer<T> {
@Override
public void onCompleted() {
- finalAction.call();
observer.onCompleted();
+ finalAction.call();
}
@Override
public void onError(Exception e) {
- finalAction.call();
observer.onError(e);
+ finalAction.call();
}
@Override
@@ -112,30 +109,24 @@ public void onNext(T args) {
}
public static class UnitTest {
- private static class TestAction implements Action0 {
- public int called = 0;
- @Override public void call() {
- called++;
- }
+ private Action0 aAction0;
+ private Observer<String> aObserver;
+ @Before
+ public void before() {
+ aAction0 = mock(Action0.class);
+ aObserver = mock(Observer.class);
+ }
+ private void checkActionCalled(Observable<String> input) {
+ Observable.create(finally0(input, aAction0)).subscribe(aObserver);
+ verify(aAction0, times(1)).call();
+ }
+ @Test
+ public void testFinallyCalledOnComplete() {
+ checkActionCalled(Observable.toObservable(new String[] {"1", "2", "3"}));
}
-
@Test
- public void testFinally() {
- final String[] n = {"1", "2", "3"};
- final Observable<String> nums = Observable.toObservable(n);
- TestAction action = new TestAction();
- action.called = 0;
- Observable<String> fin = Observable.create(finally0(nums, action));
- @SuppressWarnings("unchecked")
- Observer<String> aObserver = mock(Observer.class);
- fin.subscribe(aObserver);
- assertEquals(1, action.called);
-
- action.called = 0;
- Observable<String> error = Observable.<String>error(new RuntimeException("expected"));
- fin = Observable.create(finally0(error, action));
- fin.subscribe(aObserver);
- assertEquals(1, action.called);
+ public void testFinallyCalledOnError() {
+ checkActionCalled(Observable.<String>error(new RuntimeException("expected")));
}
}
}
|
bfad7226bf99c488f5e5063a44cc4a5282c9344d
|
orientdb
|
Fixed issue on set password for OUser.--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
index 19b54223d12..248ca2b419d 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/security/OUser.java
@@ -148,10 +148,10 @@ public String getPassword() {
}
public OUser setPassword(final String iPassword) {
- return setPasswordEncoded(encryptPassword(iPassword));
+ return setPasswordEncoded(iPassword);
}
- public OUser setPasswordEncoded(String iPassword) {
+ public OUser setPasswordEncoded(final String iPassword) {
document.field("password", iPassword);
return this;
}
@@ -164,7 +164,7 @@ public STATUSES getAccountStatus() {
return STATUSES.valueOf((String) document.field("status"));
}
- public void setAccountStatus(STATUSES accountStatus) {
+ public void setAccountStatus(final STATUSES accountStatus) {
document.field("status", accountStatus);
}
|
48701edad8513b27acec7216581e64637157c86a
|
drools
|
DROOLS-515 Kie-Camel is broken after Camel Update- -Added static field, to allow unit tests to ensure keys are ordered.--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java
index 1730089c241..f9b85e851b4 100644
--- a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java
+++ b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamJSon.java
@@ -45,6 +45,7 @@
import org.drools.core.command.runtime.rule.ModifyCommand;
import org.drools.core.command.runtime.rule.QueryCommand;
import org.drools.core.common.DefaultFactHandle;
+import org.drools.core.common.InternalFactHandle;
import org.drools.core.util.StringUtils;
import org.drools.core.runtime.impl.ExecutionResultImpl;
import org.drools.core.runtime.rule.impl.FlatQueryResults;
@@ -59,6 +60,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -675,12 +677,15 @@ public void marshal(Object object,
ExecutionResults result = (ExecutionResults) object;
writer.startNode( "results" );
if ( !result.getIdentifiers().isEmpty() ) {
+
+ Collection<String> identifiers = result.getIdentifiers();
// this gets sorted, otherwise unit tests will not pass
- Collection<String> col = result.getIdentifiers();
- String[] identifiers = col.toArray( new String[col.size()]);
if ( SORT_MAPS ) {
- Arrays.sort(identifiers);
+ String[] array = identifiers.toArray( new String[identifiers.size()]);
+ Arrays.sort(array);
+ identifiers = Arrays.asList(array);
}
+
for ( String identifier : identifiers ) {
writer.startNode( "result" );
@@ -706,7 +711,16 @@ public void marshal(Object object,
}
}
- for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) {
+
+ Collection<String> handles = ((ExecutionResultImpl) result).getFactHandles().keySet();
+ // this gets sorted, otherwise unit tests will not pass
+ if (SORT_MAPS) {
+ String[] array = handles.toArray( new String[handles.size()]);
+ Arrays.sort(array);
+ handles = Arrays.asList(array);
+ }
+
+ for ( String identifier : handles ) {
Object handle = result.getFactHandle( identifier );
if ( handle instanceof FactHandle ) {
writer.startNode( "fact-handle" );
diff --git a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java
index 156116e4bd6..54d5a9070ae 100644
--- a/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java
+++ b/drools-core/src/main/java/org/drools/core/runtime/help/impl/XStreamXML.java
@@ -65,6 +65,7 @@
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
public class XStreamXML {
+ public static volatile boolean SORT_MAPS = false;
public static XStream newXStreamMarshaller(XStream xstream) {
XStreamHelper.setAliases( xstream );
@@ -808,7 +809,16 @@ public void marshal(Object object,
HierarchicalStreamWriter writer,
MarshallingContext context) {
ExecutionResults result = (ExecutionResults) object;
- for ( String identifier : result.getIdentifiers() ) {
+
+ Collection<String> identifiers = result.getIdentifiers();
+ // this gets sorted, otherwise unit tests will not pass
+ if ( SORT_MAPS ) {
+ String[] array = identifiers.toArray( new String[identifiers.size()]);
+ Arrays.sort(array);
+ identifiers = Arrays.asList(array);
+ }
+
+ for ( String identifier : identifiers ) {
writer.startNode( "result" );
writer.addAttribute( "identifier",
identifier );
@@ -828,7 +838,15 @@ public void marshal(Object object,
writer.endNode();
}
- for ( String identifier : ((ExecutionResultImpl) result).getFactHandles().keySet() ) {
+ Collection<String> handles = ((ExecutionResultImpl) result).getFactHandles().keySet();
+ // this gets sorted, otherwise unit tests will not pass
+ if (SORT_MAPS) {
+ String[] array = handles.toArray( new String[handles.size()]);
+ Arrays.sort(array);
+ handles = Arrays.asList(array);
+ }
+
+ for ( String identifier : handles ) {
Object handle = result.getFactHandle( identifier );
if ( handle instanceof FactHandle ) {
writer.startNode( "fact-handle" );
|
4145b9f00c83828c55ade3b509a7dce1ab621101
|
camel
|
CAMEL-3796 Polish the- CxfRsProducerAddressOverrideTest--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1084067 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerAddressOverrideTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerAddressOverrideTest.java
index 2ad191fcf6d6b..84be7fb3fbcbf 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerAddressOverrideTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerAddressOverrideTest.java
@@ -16,15 +16,8 @@
*/
package org.apache.camel.component.cxf.jaxrs;
-import java.util.List;
-
import org.apache.camel.Exchange;
-import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
-import org.apache.camel.Processor;
-import org.apache.camel.component.cxf.CxfConstants;
-import org.apache.camel.component.cxf.jaxrs.testbean.Customer;
-import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@@ -34,97 +27,8 @@ protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/jaxrs/CxfRsSpringProducerAddressOverride.xml");
}
- @Override
- public void testGetConstumerWithClientProxyAPI() {
- // START SNIPPET: ProxyExample
- Exchange exchange = template.send("direct://proxy", new Processor() {
-
- public void process(Exchange exchange) throws Exception {
- exchange.setPattern(ExchangePattern.InOut);
- Message inMessage = exchange.getIn();
-
- inMessage.setHeader(Exchange.DESTINATION_OVERRIDE_URL,
- "http://localhost:9002");
-
- // set the operation name
- inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomer");
- // using the proxy client API
- inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
- // set the parameters , if you just have one parameter
- // camel will put this object into an Object[] itself
- inMessage.setBody("123");
- }
-
- });
-
- // get the response message
- Customer response = (Customer) exchange.getOut().getBody();
-
- assertNotNull("The response should not be null ", response);
- assertEquals("Get a wrong customer id ", String.valueOf(response.getId()), "123");
- assertEquals("Get a wrong customer name", response.getName(), "John");
- // END SNIPPET: ProxyExample
- }
-
- @Test
- public void testGetConstumersWithClientProxyAPI() {
- Exchange exchange = template.send("direct://proxy", new Processor() {
- public void process(Exchange exchange) throws Exception {
- exchange.setPattern(ExchangePattern.InOut);
- Message inMessage = exchange.getIn();
- inMessage.setHeader(Exchange.DESTINATION_OVERRIDE_URL,
- "http://localhost:9002");
- // set the operation name
- inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomers");
- // using the proxy client API
- inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.FALSE);
- // set the parameters , if you just have one parameter
- // camel will put this object into an Object[] itself
- inMessage.setBody(null);
- }
- });
-
- // get the response message
- List<Customer> response = (List<Customer>) exchange.getOut().getBody();
-
- assertNotNull("The response should not be null ", response);
- assertEquals("Get a wrong customer id ", String.valueOf(response.get(0).getId()), "113");
- assertEquals("Get a wrong customer name", response.get(0).getName(), "Dan");
+ protected void setupDestinationURL(Message inMessage) {
+ inMessage.setHeader(Exchange.DESTINATION_OVERRIDE_URL,
+ "http://localhost:9002");
}
-
- @Override
- public void testGetConstumerWithHttpCentralClientAPI() {
- // START SNIPPET: HttpExample
- Exchange exchange = template.send("direct://http", new Processor() {
-
- public void process(Exchange exchange) throws Exception {
- exchange.setPattern(ExchangePattern.InOut);
- Message inMessage = exchange.getIn();
-
- inMessage.setHeader(Exchange.DESTINATION_OVERRIDE_URL,
- "http://localhost:9002");
-
- // using the http central client API
- inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
- // set the Http method
- inMessage.setHeader(Exchange.HTTP_METHOD, "GET");
- // set the relative path
- inMessage.setHeader(Exchange.HTTP_PATH, "/customerservice/customers/123");
- // Specify the response class , cxfrs will use InputStream as the response object type
- inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS, Customer.class);
- // since we use the Get method, so we don't need to set the message body
- inMessage.setBody(null);
- }
-
- });
-
- // get the response message
- Customer response = (Customer) exchange.getOut().getBody();
-
- assertNotNull("The response should not be null ", response);
- assertEquals("Get a wrong customer id ", String.valueOf(response.getId()), "123");
- assertEquals("Get a wrong customer name", response.getName(), "John");
- // END SNIPPET: HttpExample
- }
-
}
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java
index 9ffe610d56e52..837e120c871f3 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/jaxrs/CxfRsProducerTest.java
@@ -47,6 +47,10 @@ protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/jaxrs/CxfRsSpringProducer.xml");
}
+ protected void setupDestinationURL(Message inMessage) {
+ // do nothing here
+ }
+
@Test
public void testGetConstumerWithClientProxyAPI() {
// START SNIPPET: ProxyExample
@@ -54,6 +58,7 @@ public void testGetConstumerWithClientProxyAPI() {
public void process(Exchange exchange) throws Exception {
exchange.setPattern(ExchangePattern.InOut);
Message inMessage = exchange.getIn();
+ setupDestinationURL(inMessage);
// set the operation name
inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomer");
// using the proxy client API
@@ -79,6 +84,7 @@ public void testGetConstumersWithClientProxyAPI() {
public void process(Exchange exchange) throws Exception {
exchange.setPattern(ExchangePattern.InOut);
Message inMessage = exchange.getIn();
+ setupDestinationURL(inMessage);
// set the operation name
inMessage.setHeader(CxfConstants.OPERATION_NAME, "getCustomers");
// using the proxy client API
@@ -104,6 +110,7 @@ public void testGetConstumerWithHttpCentralClientAPI() {
public void process(Exchange exchange) throws Exception {
exchange.setPattern(ExchangePattern.InOut);
Message inMessage = exchange.getIn();
+ setupDestinationURL(inMessage);
// using the http central client API
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API, Boolean.TRUE);
// set the Http method
|
0ab9ab9ce7eeaeb195740d36de05daa0fe3b003c
|
hbase
|
HBASE-8921 [thrift2] Add GenericOptionsParser to- Thrift 2 server--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1501982 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
index 87b89b5f563d..a610bf1b7912 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/thrift2/ThriftServer.java
@@ -18,6 +18,7 @@
*/
package org.apache.hadoop.hbase.thrift2;
+import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
@@ -46,6 +47,7 @@
import org.apache.hadoop.hbase.thrift.ThriftMetrics;
import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
import org.apache.hadoop.hbase.util.InfoServer;
+import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
@@ -105,9 +107,12 @@ private static Options getOptions() {
return options;
}
- private static CommandLine parseArguments(Options options, String[] args) throws ParseException {
+ private static CommandLine parseArguments(Configuration conf, Options options, String[] args)
+ throws ParseException, IOException {
+ GenericOptionsParser genParser = new GenericOptionsParser(conf, args);
+ String[] remainingArgs = genParser.getRemainingArgs();
CommandLineParser parser = new PosixParser();
- return parser.parse(options, args);
+ return parser.parse(options, remainingArgs);
}
private static TProtocolFactory getTProtocolFactory(boolean isCompact) {
@@ -222,7 +227,8 @@ public static void main(String[] args) throws Exception {
TServer server = null;
Options options = getOptions();
try {
- CommandLine cmd = parseArguments(options, args);
+ Configuration conf = HBaseConfiguration.create();
+ CommandLine cmd = parseArguments(conf, options, args);
/**
* This is to please both bin/hbase and bin/hbase-daemon. hbase-daemon provides "start" and "stop" arguments hbase
@@ -245,7 +251,6 @@ public static void main(String[] args) throws Exception {
boolean nonblocking = cmd.hasOption("nonblocking");
boolean hsha = cmd.hasOption("hsha");
- Configuration conf = HBaseConfiguration.create();
ThriftMetrics metrics = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.TWO);
String implType = "threadpool";
|
66de48a353197903c0b45c4af25be24c5588cfe1
|
hadoop
|
HDFS-2500. Avoid file system operations in- BPOfferService thread while processing deletes. Contributed by Todd Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1190072 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 2ce3a9765a8ce..9a0ecbea52e77 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -761,6 +761,9 @@ Release 0.23.0 - Unreleased
HDFS-2118. Couple dfs data dir improvements. (eli)
+ HDFS-2500. Avoid file system operations in BPOfferService thread while
+ processing deletes. (todd)
+
BUG FIXES
HDFS-2344. Fix the TestOfflineEditsViewer test failure in 0.23 branch.
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
index eb953ab7eb241..3f7733608999c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
@@ -1108,8 +1108,15 @@ private void offerService() throws Exception {
if (!heartbeatsDisabledForTests) {
DatanodeCommand[] cmds = sendHeartBeat();
metrics.addHeartbeat(now() - startTime);
+
+ long startProcessCommands = now();
if (!processCommand(cmds))
continue;
+ long endProcessCommands = now();
+ if (endProcessCommands - startProcessCommands > 2000) {
+ LOG.info("Took " + (endProcessCommands - startProcessCommands) +
+ "ms to process " + cmds.length + " commands from NN");
+ }
}
}
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
index 08b40fed2aae4..53c5525908440 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java
@@ -2088,10 +2088,9 @@ public void invalidate(String bpid, Block invalidBlks[]) throws IOException {
volumeMap.remove(bpid, invalidBlks[i]);
}
File metaFile = getMetaFile(f, invalidBlks[i].getGenerationStamp());
- long dfsBytes = f.length() + metaFile.length();
// Delete the block asynchronously to make sure we can do it fast enough
- asyncDiskService.deleteAsync(v, bpid, f, metaFile, dfsBytes,
+ asyncDiskService.deleteAsync(v, bpid, f, metaFile,
invalidBlks[i].toString());
}
if (error) {
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
index 176f8825d9fb2..0c2523b834176 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java
@@ -148,11 +148,11 @@ synchronized void shutdown() {
* dfsUsed statistics accordingly.
*/
void deleteAsync(FSDataset.FSVolume volume, String bpid, File blockFile,
- File metaFile, long dfsBytes, String blockName) {
+ File metaFile, String blockName) {
DataNode.LOG.info("Scheduling block " + blockName + " file " + blockFile
+ " for deletion");
ReplicaFileDeleteTask deletionTask =
- new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile, dfsBytes,
+ new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile,
blockName);
execute(volume.getCurrentDir(), deletionTask);
}
@@ -165,16 +165,14 @@ static class ReplicaFileDeleteTask implements Runnable {
final String blockPoolId;
final File blockFile;
final File metaFile;
- final long dfsBytes;
final String blockName;
ReplicaFileDeleteTask(FSDataset.FSVolume volume, String bpid,
- File blockFile, File metaFile, long dfsBytes, String blockName) {
+ File blockFile, File metaFile, String blockName) {
this.volume = volume;
this.blockPoolId = bpid;
this.blockFile = blockFile;
this.metaFile = metaFile;
- this.dfsBytes = dfsBytes;
this.blockName = blockName;
}
@@ -192,6 +190,7 @@ public String toString() {
@Override
public void run() {
+ long dfsBytes = blockFile.length() + metaFile.length();
if ( !blockFile.delete() || ( !metaFile.delete() && metaFile.exists() ) ) {
DataNode.LOG.warn("Unexpected error trying to delete block "
+ blockPoolId + " " + blockName + " at file " + blockFile
|
448f8dbb9fd9bf2e0ef72dda7bb235915deca94f
|
hadoop
|
HADOOP-7110. Implement chmod with JNI. Contributed- by Todd Lipcon--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1063090 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index eba3b6f39cce9..74d4265a974f6 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -266,6 +266,8 @@ Release 0.22.0 - Unreleased
HADOOP-6056. Use java.net.preferIPv4Stack to force IPv4.
(Michele Catasta via shv)
+ HADOOP-7110. Implement chmod with JNI. (todd)
+
OPTIMIZATIONS
HADOOP-6884. Add LOG.isDebugEnabled() guard for each LOG.debug(..).
diff --git a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java
index 053fd392defb8..0ecdd6241e015 100644
--- a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java
+++ b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java
@@ -36,6 +36,7 @@
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.io.nativeio.NativeIO;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
@@ -554,8 +555,13 @@ public void setOwner(Path p, String username, String groupname)
@Override
public void setPermission(Path p, FsPermission permission)
throws IOException {
- execCommand(pathToFile(p), Shell.SET_PERMISSION_COMMAND,
- String.format("%05o", permission.toShort()));
+ if (NativeIO.isAvailable()) {
+ NativeIO.chmod(pathToFile(p).getCanonicalPath(),
+ permission.toShort());
+ } else {
+ execCommand(pathToFile(p), Shell.SET_PERMISSION_COMMAND,
+ String.format("%05o", permission.toShort()));
+ }
}
private static String execCommand(File f, String... cmd) throws IOException {
diff --git a/src/java/org/apache/hadoop/io/nativeio/NativeIO.java b/src/java/org/apache/hadoop/io/nativeio/NativeIO.java
index 6e16c73fb93c0..db4512562f885 100644
--- a/src/java/org/apache/hadoop/io/nativeio/NativeIO.java
+++ b/src/java/org/apache/hadoop/io/nativeio/NativeIO.java
@@ -74,6 +74,9 @@ public static boolean isAvailable() {
public static native FileDescriptor open(String path, int flags, int mode) throws IOException;
/** Wrapper around fstat(2) */
public static native Stat fstat(FileDescriptor fd) throws IOException;
+ /** Wrapper around chmod(2) */
+ public static native void chmod(String path, int mode) throws IOException;
+
/** Initialize the JNI method ID and class ID cache */
private static native void initNative();
diff --git a/src/native/config.h.in b/src/native/config.h.in
index 26f8b0fcfb243..18f5da8462bef 100644
--- a/src/native/config.h.in
+++ b/src/native/config.h.in
@@ -82,6 +82,9 @@
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
+/* Define to the home page for this package. */
+#undef PACKAGE_URL
+
/* Define to the version of this package. */
#undef PACKAGE_VERSION
diff --git a/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c b/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c
index 1c1a9896274c0..d55072099db4e 100644
--- a/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c
+++ b/src/native/src/org/apache/hadoop/io/nativeio/NativeIO.c
@@ -221,6 +221,25 @@ Java_org_apache_hadoop_io_nativeio_NativeIO_open(
return ret;
}
+/**
+ * public static native void chmod(String path, int mode) throws IOException;
+ */
+JNIEXPORT void JNICALL
+Java_org_apache_hadoop_io_nativeio_NativeIO_chmod(
+ JNIEnv *env, jclass clazz, jstring j_path,
+ jint mode)
+{
+ const char *path = (*env)->GetStringUTFChars(env, j_path, NULL);
+ if (path == NULL) return; // JVM throws Exception for us
+
+ if (chmod(path, mode) != 0) {
+ throw_ioe(env, errno);
+ }
+
+ (*env)->ReleaseStringUTFChars(env, j_path, path);
+}
+
+
/*
* Throw a java.IO.IOException, generating the message from errno.
*/
diff --git a/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java b/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java
index 972c9fc25c85a..06e02294f698a 100644
--- a/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java
+++ b/src/test/core/org/apache/hadoop/io/nativeio/TestNativeIO.java
@@ -28,7 +28,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.NativeCodeLoader;
public class TestNativeIO {
@@ -134,4 +138,34 @@ public void testFDDoesntLeak() throws IOException {
}
}
+ /**
+ * Test basic chmod operation
+ */
+ @Test
+ public void testChmod() throws Exception {
+ try {
+ NativeIO.chmod("/this/file/doesnt/exist", 777);
+ fail("Chmod of non-existent file didn't fail");
+ } catch (NativeIOException nioe) {
+ assertEquals(Errno.ENOENT, nioe.getErrno());
+ }
+
+ File toChmod = new File(TEST_DIR, "testChmod");
+ assertTrue("Create test subject",
+ toChmod.exists() || toChmod.mkdir());
+ NativeIO.chmod(toChmod.getAbsolutePath(), 0777);
+ assertPermissions(toChmod, 0777);
+ NativeIO.chmod(toChmod.getAbsolutePath(), 0000);
+ assertPermissions(toChmod, 0000);
+ NativeIO.chmod(toChmod.getAbsolutePath(), 0644);
+ assertPermissions(toChmod, 0644);
+ }
+
+ private void assertPermissions(File f, int expected) throws IOException {
+ FileSystem localfs = FileSystem.getLocal(new Configuration());
+ FsPermission perms = localfs.getFileStatus(
+ new Path(f.getAbsolutePath())).getPermission();
+ assertEquals(expected, perms.toShort());
+ }
+
}
|
47db48934367962fb35cde65eb48054292e323f1
|
drools
|
JBRULES-1618 Check the context class-loader of the- current thread before using it--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
index a8111991739..368b337cbcd 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
@@ -323,6 +323,7 @@ public void addPackageFromXml(final Reader reader) throws DroolsParserException,
IOException {
this.resource = new ReaderResource( reader );
final XmlPackageReader xmlReader = new XmlPackageReader( this.configuration.getSemanticModules() );
+ xmlReader.getParser().setClassLoader( this.rootClassLoader );
try {
xmlReader.read( reader );
@@ -340,7 +341,8 @@ public void addPackageFromXml(final Resource resource) throws DroolsParserExcept
this.resource = resource;
final XmlPackageReader xmlReader = new XmlPackageReader( this.configuration.getSemanticModules() );
-
+ xmlReader.getParser().setClassLoader( this.rootClassLoader );
+
try {
xmlReader.read( resource.getReader() );
} catch ( final SAXException e ) {
diff --git a/drools-compiler/src/test/java/org/drools/compiler/xml/changeset/ChangeSetTest.java b/drools-compiler/src/test/java/org/drools/compiler/xml/changeset/ChangeSetTest.java
index eab0f0baf71..e6d92bb89f0 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/xml/changeset/ChangeSetTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/xml/changeset/ChangeSetTest.java
@@ -50,6 +50,7 @@ public void testXmlParser() throws SAXException,
PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
XmlChangeSetReader xmlReader = new XmlChangeSetReader( conf.getSemanticModules() );
+ xmlReader.setClassLoader( ChangeSetTest.class.getClassLoader(), ChangeSetTest.class );
String str = "";
str += "<change-set ";
@@ -114,6 +115,7 @@ public void testBasicAuthentication() throws SAXException,
PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
XmlChangeSetReader xmlReader = new XmlChangeSetReader( conf.getSemanticModules() );
+ xmlReader.setClassLoader( ChangeSetTest.class.getClassLoader(), ChangeSetTest.class );
String str = "";
str += "<change-set ";
diff --git a/drools-compiler/src/test/java/org/drools/compiler/xml/rules/DumperTestHelper.java b/drools-compiler/src/test/java/org/drools/compiler/xml/rules/DumperTestHelper.java
index eb49a1d8344..82307de7303 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/xml/rules/DumperTestHelper.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/xml/rules/DumperTestHelper.java
@@ -22,6 +22,7 @@ public static void XmlFile(String filename) throws Exception {
PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
XmlPackageReader xmlPackageReader = new XmlPackageReader( conf.getSemanticModules() );
+ xmlPackageReader.getParser().setClassLoader( DumperTestHelper.class.getClassLoader() );
xmlPackageReader.read( new InputStreamReader( DumperTestHelper.class.getResourceAsStream( filename ) ) );
final PackageDescr pkgOriginal = xmlPackageReader.getPackageDescr();
diff --git a/drools-compiler/src/test/java/org/drools/compiler/xml/rules/XmlPackageReaderTest.java b/drools-compiler/src/test/java/org/drools/compiler/xml/rules/XmlPackageReaderTest.java
index 3ed9c597630..b93371c5ab3 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/xml/rules/XmlPackageReaderTest.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/xml/rules/XmlPackageReaderTest.java
@@ -565,7 +565,9 @@ public void testParseQuery() throws Exception {
private XmlPackageReader getXmReader() {
PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
+ XmlPackageReader xmlReader = new XmlPackageReader( conf.getSemanticModules() );
+ xmlReader.getParser().setClassLoader( XmlPackageReaderTest.class.getClassLoader() );
- return new XmlPackageReader( conf.getSemanticModules() );
+ return xmlReader;
}
}
|
1927f040774aa75d2dfe1d95fae9b43ee821361b
|
hbase
|
HBASE-13958 RESTApiClusterManager calls kill()- instead of suspend() and resume()--
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java b/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
index 28fac4ee2bf2..9ea126a0af90 100644
--- a/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
+++ b/hbase-it/src/test/java/org/apache/hadoop/hbase/RESTApiClusterManager.java
@@ -158,12 +158,12 @@ public void kill(ServiceType service, String hostname, int port) throws IOExcept
@Override
public void suspend(ServiceType service, String hostname, int port) throws IOException {
- hBaseClusterManager.kill(service, hostname, port);
+ hBaseClusterManager.suspend(service, hostname, port);
}
@Override
public void resume(ServiceType service, String hostname, int port) throws IOException {
- hBaseClusterManager.kill(service, hostname, port);
+ hBaseClusterManager.resume(service, hostname, port);
}
|
591f5202c621bbfedc351dff81437dcedf4b2827
|
intellij-community
|
resolve and completion for Django settings- (PY-563)--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java b/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java
index 415529dc9fafe..bb6500b4af68a 100644
--- a/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java
+++ b/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java
@@ -24,6 +24,7 @@ public class PyDynamicMember {
private final String myResolveShortName;
private final String myResolveModuleName;
+ private final PsiElement myTarget;
public PyDynamicMember(final String name, final String type, final boolean resolveToInstance) {
this(name, type, type, resolveToInstance);
@@ -37,6 +38,17 @@ public PyDynamicMember(final String name, final String type, final String resolv
int split = resolveTo.lastIndexOf('.');
myResolveShortName = resolveTo.substring(split + 1);
myResolveModuleName = resolveTo.substring(0, split);
+
+ myTarget = null;
+ }
+
+ public PyDynamicMember(final String name, final PsiElement target) {
+ myName = name;
+ myTarget = target;
+ myResolveToInstance = false;
+ myTypeName = null;
+ myResolveModuleName = null;
+ myResolveShortName = null;
}
public String getName() {
@@ -49,6 +61,9 @@ public Icon getIcon() {
@Nullable
public PsiElement resolve(Project project, PyClass modelClass) {
+ if (myTarget != null) {
+ return myTarget;
+ }
PyClass targetClass = PyClassNameIndex.findClass(myTypeName, project);
if (targetClass != null) {
return new MyInstanceElement(targetClass, findResolveTarget(modelClass));
@@ -71,9 +86,13 @@ private PsiElement findResolveTarget(PyClass clazz) {
return module;
}
+ @Nullable
public String getShortType() {
+ if (myTypeName == null) {
+ return null;
+ }
int pos = myTypeName.lastIndexOf('.');
- return myTypeName.substring(pos+1);
+ return myTypeName.substring(pos + 1);
}
private class MyInstanceElement extends PyElementImpl implements PyExpression {
|
7d474706065c400dd59a6808c0a05d9ad1ac77ab
|
restlet-framework-java
|
- Simple HTTP connector works again--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java b/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
index 46c0adedaa..3ce0a5ecd6 100644
--- a/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
+++ b/source/ext/simple3.1/com/noelios/restlet/ext/simple/SimpleServer.java
@@ -22,28 +22,19 @@
package com.noelios.restlet.ext.simple;
-import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
-import java.security.KeyStore;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-
import org.restlet.component.Component;
import org.restlet.data.ParameterList;
-import org.restlet.data.Protocols;
-import simple.http.BufferedPipelineFactory;
import simple.http.PipelineHandler;
-import simple.http.PipelineHandlerFactory;
import simple.http.ProtocolHandler;
import simple.http.Request;
import simple.http.Response;
import simple.http.connect.Connection;
-import simple.http.connect.ConnectionFactory;
import com.noelios.restlet.impl.HttpServer;
@@ -89,42 +80,6 @@ public SimpleServer(Component owner, ParameterList parameters, String address, i
super(owner, parameters, address, port);
}
- /** Starts the Restlet. */
- public void start() throws Exception
- {
- if(!isStarted())
- {
- if (Protocols.HTTP.equals(super.protocols))
- {
- socket = new ServerSocket(port);
- }
- else if (Protocols.HTTPS.equals(super.protocols))
- {
- KeyStore keyStore = KeyStore.getInstance("JKS");
- keyStore.load(new FileInputStream(keystorePath), keystorePassword
- .toCharArray());
- KeyManagerFactory keyManagerFactory = KeyManagerFactory
- .getInstance("SunX509");
- keyManagerFactory.init(keyStore, keyPassword.toCharArray());
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
- socket = sslContext.getServerSocketFactory().createServerSocket(port);
- socket.setSoTimeout(60000);
- }
- else
- {
- // Should never happen.
- throw new RuntimeException("Unsupported protocol: " + super.protocols);
- }
-
- this.confidential = Protocols.HTTPS.equals(getProtocols());
- this.handler = PipelineHandlerFactory.getInstance(this, 20, 200);
- this.connection = ConnectionFactory.getConnection(handler, new BufferedPipelineFactory());
- this.connection.connect(socket);
- super.start();
- }
- }
-
/** Stops the Restlet. */
public void stop() throws Exception
{
diff --git a/source/main/com/noelios/restlet/impl/FactoryImpl.java b/source/main/com/noelios/restlet/impl/FactoryImpl.java
index 3e3fa990f0..ac34f648ce 100644
--- a/source/main/com/noelios/restlet/impl/FactoryImpl.java
+++ b/source/main/com/noelios/restlet/impl/FactoryImpl.java
@@ -30,7 +30,6 @@
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
-import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -116,7 +115,7 @@ public FactoryImpl()
try
{
Class<? extends Client> providerClass = (Class<? extends Client>) Class.forName(providerClassName);
- this.clients.add(providerClass.newInstance());
+ this.clients.add(providerClass.getConstructor(Component.class, ParameterList.class).newInstance(null, null));
}
catch(Exception e)
{
@@ -166,7 +165,7 @@ public FactoryImpl()
try
{
Class<? extends Server> providerClass = (Class<? extends Server>) Class.forName(providerClassName);
- this.servers.add(providerClass.newInstance());
+ this.servers.add(providerClass.getConstructor(Component.class, ParameterList.class, String.class, int.class).newInstance(null, null, null, new Integer(-1)));
}
catch(Exception e)
{
@@ -204,7 +203,7 @@ public Client createClient(List<Protocol> protocols, Component owner, ParameterL
{
try
{
- return client.getClass().getConstructor(Component.class, Map.class).newInstance(owner, parameters);
+ return client.getClass().getConstructor(Component.class, ParameterList.class).newInstance(owner, parameters);
}
catch (Exception e)
{
@@ -267,7 +266,7 @@ public Server createServer(List<Protocol> protocols, Component owner, ParameterL
{
try
{
- return server.getClass().getConstructor(Component.class, Map.class, String.class, int.class).newInstance(owner, parameters, address, port);
+ return server.getClass().getConstructor(Component.class, ParameterList.class, String.class, int.class).newInstance(owner, parameters, address, port);
}
catch (Exception e)
{
diff --git a/source/main/meta-inf/services/org.restlet.connector.Client b/source/main/meta-inf/services/org.restlet.connector.Client
index 01c6b38b2a..41ab6574c1 100644
--- a/source/main/meta-inf/services/org.restlet.connector.Client
+++ b/source/main/meta-inf/services/org.restlet.connector.Client
@@ -1,3 +1,2 @@
com.noelios.restlet.impl.HttpClient # HTTP, HTTPS
-com.noelios.restlet.impl.FileClient # FILE
-com.noelios.restlet.impl.ContextClient # CONTEXT
+com.noelios.restlet.impl.ContextClient # CONTEXT, FILE
|
31d63bcc9d3d8766c62d2c237554a38462a57456
|
drools
|
really, this is the fix for -154--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@3914 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/lang/RuleParser.java b/drools-compiler/src/main/java/org/drools/lang/RuleParser.java
index 8fc14adc01d..71a398bf31e 100644
--- a/drools-compiler/src/main/java/org/drools/lang/RuleParser.java
+++ b/drools-compiler/src/main/java/org/drools/lang/RuleParser.java
@@ -1,4 +1,4 @@
-// $ANTLR 3.0ea8 /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g 2006-04-22 22:27:31
+// $ANTLR 3.0ea8 /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g 2006-04-22 23:00:57
package org.drools.lang;
import java.util.List;
@@ -163,7 +163,7 @@ public void reportError(RecognitionException ex) {
return;
}
errorRecovery = true;
-
+ System.err.println( ex );
errors.add( ex );
}
@@ -3997,7 +3997,7 @@ public String paren_chunk() throws RecognitionException {
match(input,23,FOLLOW_23_in_paren_chunk2155);
- //System.err.println( "chunk [" + c + "]" );
+ System.err.println( "chunk [" + c + "]" );
if ( c == null ) {
c = "";
}
@@ -4016,7 +4016,7 @@ public String paren_chunk() throws RecognitionException {
any=(Token)input.LT(1);
matchAny(input);
- //System.err.println( "any [" + any.getText() + "]" );
+ System.err.println( "any [" + any.getText() + "]" );
if ( text == null ) {
text = any.getText();
} else {
@@ -4047,9 +4047,9 @@ public String paren_chunk() throws RecognitionException {
// $ANTLR end paren_chunk
- // $ANTLR start curly_chunk
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:792:1: curly_chunk returns [String text] : ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )* ;
- public String curly_chunk() throws RecognitionException {
+ // $ANTLR start paren_chunk2
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:793:1: paren_chunk2 returns [String text] : ( options {greedy=false; } : '(' c= paren_chunk2 ')' | any= . )* ;
+ public String paren_chunk2() throws RecognitionException {
String text;
Token any=null;
String c = null;
@@ -4059,18 +4059,18 @@ public String curly_chunk() throws RecognitionException {
text = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:798:17: ( ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )* )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:798:17: ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:799:18: ( ( options {greedy=false; } : '(' c= paren_chunk2 ')' | any= . )* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:799:18: ( options {greedy=false; } : '(' c= paren_chunk2 ')' | any= . )*
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:798:17: ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:799:18: ( options {greedy=false; } : '(' c= paren_chunk2 ')' | any= . )*
loop54:
do {
int alt54=3;
switch ( input.LA(1) ) {
- case 25:
+ case 23:
alt54=3;
break;
- case 24:
+ case 21:
alt54=1;
break;
case EOL:
@@ -4090,9 +4090,9 @@ public String curly_chunk() throws RecognitionException {
case 18:
case 19:
case 20:
- case 21:
case 22:
- case 23:
+ case 24:
+ case 25:
case 26:
case 27:
case 28:
@@ -4132,14 +4132,158 @@ public String curly_chunk() throws RecognitionException {
switch (alt54) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:799:25: '{' c= curly_chunk '}'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:800:25: '(' c= paren_chunk2 ')'
+ {
+ match(input,21,FOLLOW_21_in_paren_chunk22226);
+ following.push(FOLLOW_paren_chunk2_in_paren_chunk22230);
+ c=paren_chunk2();
+ following.pop();
+
+ match(input,23,FOLLOW_23_in_paren_chunk22232);
+
+ System.err.println( "chunk [" + c + "]" );
+ if ( c == null ) {
+ c = "";
+ }
+ if ( text == null ) {
+ text = "( " + c + " )";
+ } else {
+ text = text + " ( " + c + " )";
+ }
+
+
+ }
+ break;
+ case 2 :
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:812:19: any= .
+ {
+ any=(Token)input.LT(1);
+ matchAny(input);
+
+ System.err.println( "any [" + any.getText() + "]" );
+ if ( text == null ) {
+ text = any.getText();
+ } else {
+ text = text + " " + any.getText();
+ }
+
+
+ }
+ break;
+
+ default :
+ break loop54;
+ }
+ } while (true);
+
+
+ }
+
+ }
+ catch (RecognitionException re) {
+ reportError(re);
+ recover(input,re);
+ }
+ finally {
+ }
+ return text;
+ }
+ // $ANTLR end paren_chunk2
+
+
+ // $ANTLR start curly_chunk
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:824:1: curly_chunk returns [String text] : ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )* ;
+ public String curly_chunk() throws RecognitionException {
+ String text;
+ Token any=null;
+ String c = null;
+
+
+
+ text = null;
+
+ try {
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:830:17: ( ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:830:17: ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )*
+ {
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:830:17: ( options {greedy=false; } : '{' c= curly_chunk '}' | any= . )*
+ loop55:
+ do {
+ int alt55=3;
+ switch ( input.LA(1) ) {
+ case 25:
+ alt55=3;
+ break;
+ case 24:
+ alt55=1;
+ break;
+ case EOL:
+ case ID:
+ case INT:
+ case BOOL:
+ case STRING:
+ case FLOAT:
+ case MISC:
+ case WS:
+ case SH_STYLE_SINGLE_LINE_COMMENT:
+ case C_STYLE_SINGLE_LINE_COMMENT:
+ case MULTI_LINE_COMMENT:
+ case 15:
+ case 16:
+ case 17:
+ case 18:
+ case 19:
+ case 20:
+ case 21:
+ case 22:
+ case 23:
+ case 26:
+ case 27:
+ case 28:
+ case 29:
+ case 30:
+ case 31:
+ case 32:
+ case 33:
+ case 34:
+ case 35:
+ case 36:
+ case 37:
+ case 38:
+ case 39:
+ case 40:
+ case 41:
+ case 42:
+ case 43:
+ case 44:
+ case 45:
+ case 46:
+ case 47:
+ case 48:
+ case 49:
+ case 50:
+ case 51:
+ case 52:
+ case 53:
+ case 54:
+ case 55:
+ case 56:
+ case 57:
+ alt55=2;
+ break;
+
+ }
+
+ switch (alt55) {
+ case 1 :
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:831:25: '{' c= curly_chunk '}'
{
- match(input,24,FOLLOW_24_in_curly_chunk2224);
- following.push(FOLLOW_curly_chunk_in_curly_chunk2228);
+ match(input,24,FOLLOW_24_in_curly_chunk2301);
+ following.push(FOLLOW_curly_chunk_in_curly_chunk2305);
c=curly_chunk();
following.pop();
- match(input,25,FOLLOW_25_in_curly_chunk2230);
+ match(input,25,FOLLOW_25_in_curly_chunk2307);
//System.err.println( "chunk [" + c + "]" );
if ( c == null ) {
@@ -4155,7 +4299,7 @@ public String curly_chunk() throws RecognitionException {
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:811:19: any= .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:843:19: any= .
{
any=(Token)input.LT(1);
matchAny(input);
@@ -4172,7 +4316,7 @@ public String curly_chunk() throws RecognitionException {
break;
default :
- break loop54;
+ break loop55;
}
} while (true);
@@ -4192,7 +4336,7 @@ public String curly_chunk() throws RecognitionException {
// $ANTLR start lhs_or
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:823:1: lhs_or returns [PatternDescr d] : left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )* ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:855:1: lhs_or returns [PatternDescr d] : left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )* ;
public PatternDescr lhs_or() throws RecognitionException {
PatternDescr d;
PatternDescr left = null;
@@ -4204,28 +4348,28 @@ public PatternDescr lhs_or() throws RecognitionException {
d = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:828:17: (left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )* )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:828:17: left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:860:17: (left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:860:17: left= lhs_and ( ('or'|'||') opt_eol right= lhs_and )*
{
OrDescr or = null;
- following.push(FOLLOW_lhs_and_in_lhs_or2288);
+ following.push(FOLLOW_lhs_and_in_lhs_or2365);
left=lhs_and();
following.pop();
d = left;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:830:17: ( ('or'|'||') opt_eol right= lhs_and )*
- loop55:
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:862:17: ( ('or'|'||') opt_eol right= lhs_and )*
+ loop56:
do {
- int alt55=2;
- int LA55_0 = input.LA(1);
- if ( LA55_0==39||LA55_0==51 ) {
- alt55=1;
+ int alt56=2;
+ int LA56_0 = input.LA(1);
+ if ( LA56_0==39||LA56_0==51 ) {
+ alt56=1;
}
- switch (alt55) {
+ switch (alt56) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:830:19: ('or'|'||') opt_eol right= lhs_and
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:862:19: ('or'|'||') opt_eol right= lhs_and
{
if ( input.LA(1)==39||input.LA(1)==51 ) {
input.consume();
@@ -4234,14 +4378,14 @@ public PatternDescr lhs_or() throws RecognitionException {
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
- recoverFromMismatchedSet(input,mse,FOLLOW_set_in_lhs_or2297); throw mse;
+ recoverFromMismatchedSet(input,mse,FOLLOW_set_in_lhs_or2374); throw mse;
}
- following.push(FOLLOW_opt_eol_in_lhs_or2302);
+ following.push(FOLLOW_opt_eol_in_lhs_or2379);
opt_eol();
following.pop();
- following.push(FOLLOW_lhs_and_in_lhs_or2309);
+ following.push(FOLLOW_lhs_and_in_lhs_or2386);
right=lhs_and();
following.pop();
@@ -4259,7 +4403,7 @@ public PatternDescr lhs_or() throws RecognitionException {
break;
default :
- break loop55;
+ break loop56;
}
} while (true);
@@ -4279,7 +4423,7 @@ public PatternDescr lhs_or() throws RecognitionException {
// $ANTLR start lhs_and
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:844:1: lhs_and returns [PatternDescr d] : left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )* ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:876:1: lhs_and returns [PatternDescr d] : left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )* ;
public PatternDescr lhs_and() throws RecognitionException {
PatternDescr d;
PatternDescr left = null;
@@ -4291,28 +4435,28 @@ public PatternDescr lhs_and() throws RecognitionException {
d = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:849:17: (left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )* )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:849:17: left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:17: (left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:17: left= lhs_unary ( ('and'|'&&') opt_eol right= lhs_unary )*
{
AndDescr and = null;
- following.push(FOLLOW_lhs_unary_in_lhs_and2349);
+ following.push(FOLLOW_lhs_unary_in_lhs_and2426);
left=lhs_unary();
following.pop();
d = left;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:851:17: ( ('and'|'&&') opt_eol right= lhs_unary )*
- loop56:
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:883:17: ( ('and'|'&&') opt_eol right= lhs_unary )*
+ loop57:
do {
- int alt56=2;
- int LA56_0 = input.LA(1);
- if ( (LA56_0>=52 && LA56_0<=53) ) {
- alt56=1;
+ int alt57=2;
+ int LA57_0 = input.LA(1);
+ if ( (LA57_0>=52 && LA57_0<=53) ) {
+ alt57=1;
}
- switch (alt56) {
+ switch (alt57) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:851:19: ('and'|'&&') opt_eol right= lhs_unary
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:883:19: ('and'|'&&') opt_eol right= lhs_unary
{
if ( (input.LA(1)>=52 && input.LA(1)<=53) ) {
input.consume();
@@ -4321,14 +4465,14 @@ public PatternDescr lhs_and() throws RecognitionException {
else {
MismatchedSetException mse =
new MismatchedSetException(null,input);
- recoverFromMismatchedSet(input,mse,FOLLOW_set_in_lhs_and2358); throw mse;
+ recoverFromMismatchedSet(input,mse,FOLLOW_set_in_lhs_and2435); throw mse;
}
- following.push(FOLLOW_opt_eol_in_lhs_and2363);
+ following.push(FOLLOW_opt_eol_in_lhs_and2440);
opt_eol();
following.pop();
- following.push(FOLLOW_lhs_unary_in_lhs_and2370);
+ following.push(FOLLOW_lhs_unary_in_lhs_and2447);
right=lhs_unary();
following.pop();
@@ -4346,7 +4490,7 @@ public PatternDescr lhs_and() throws RecognitionException {
break;
default :
- break loop56;
+ break loop57;
}
} while (true);
@@ -4366,7 +4510,7 @@ public PatternDescr lhs_and() throws RecognitionException {
// $ANTLR start lhs_unary
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:865:1: lhs_unary returns [PatternDescr d] : (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' ) ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:897:1: lhs_unary returns [PatternDescr d] : (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' ) ;
public PatternDescr lhs_unary() throws RecognitionException {
PatternDescr d;
PatternDescr u = null;
@@ -4376,39 +4520,39 @@ public PatternDescr lhs_unary() throws RecognitionException {
d = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:869:17: ( (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' ) )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:869:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:901:17: ( (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:901:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' )
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:869:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' )
- int alt57=5;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:901:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | '(' u= lhs ')' )
+ int alt58=5;
switch ( input.LA(1) ) {
case 54:
- alt57=1;
+ alt58=1;
break;
case 55:
- alt57=2;
+ alt58=2;
break;
case 56:
- alt57=3;
+ alt58=3;
break;
case ID:
- alt57=4;
+ alt58=4;
break;
case 21:
- alt57=5;
+ alt58=5;
break;
default:
NoViableAltException nvae =
- new NoViableAltException("869:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | \'(\' u= lhs \')\' )", 57, 0, input);
+ new NoViableAltException("901:17: (u= lhs_exist | u= lhs_not | u= lhs_eval | u= lhs_column | \'(\' u= lhs \')\' )", 58, 0, input);
throw nvae;
}
- switch (alt57) {
+ switch (alt58) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:869:25: u= lhs_exist
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:901:25: u= lhs_exist
{
- following.push(FOLLOW_lhs_exist_in_lhs_unary2408);
+ following.push(FOLLOW_lhs_exist_in_lhs_unary2485);
u=lhs_exist();
following.pop();
@@ -4416,9 +4560,9 @@ public PatternDescr lhs_unary() throws RecognitionException {
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:870:25: u= lhs_not
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:902:25: u= lhs_not
{
- following.push(FOLLOW_lhs_not_in_lhs_unary2416);
+ following.push(FOLLOW_lhs_not_in_lhs_unary2493);
u=lhs_not();
following.pop();
@@ -4426,9 +4570,9 @@ public PatternDescr lhs_unary() throws RecognitionException {
}
break;
case 3 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:871:25: u= lhs_eval
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:903:25: u= lhs_eval
{
- following.push(FOLLOW_lhs_eval_in_lhs_unary2424);
+ following.push(FOLLOW_lhs_eval_in_lhs_unary2501);
u=lhs_eval();
following.pop();
@@ -4436,9 +4580,9 @@ public PatternDescr lhs_unary() throws RecognitionException {
}
break;
case 4 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:872:25: u= lhs_column
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:904:25: u= lhs_column
{
- following.push(FOLLOW_lhs_column_in_lhs_unary2432);
+ following.push(FOLLOW_lhs_column_in_lhs_unary2509);
u=lhs_column();
following.pop();
@@ -4446,14 +4590,14 @@ public PatternDescr lhs_unary() throws RecognitionException {
}
break;
case 5 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:873:25: '(' u= lhs ')'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:905:25: '(' u= lhs ')'
{
- match(input,21,FOLLOW_21_in_lhs_unary2438);
- following.push(FOLLOW_lhs_in_lhs_unary2442);
+ match(input,21,FOLLOW_21_in_lhs_unary2515);
+ following.push(FOLLOW_lhs_in_lhs_unary2519);
u=lhs();
following.pop();
- match(input,23,FOLLOW_23_in_lhs_unary2444);
+ match(input,23,FOLLOW_23_in_lhs_unary2521);
}
break;
@@ -4477,7 +4621,7 @@ public PatternDescr lhs_unary() throws RecognitionException {
// $ANTLR start lhs_exist
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:877:1: lhs_exist returns [PatternDescr d] : loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column ) ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:909:1: lhs_exist returns [PatternDescr d] : loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column ) ;
public PatternDescr lhs_exist() throws RecognitionException {
PatternDescr d;
Token loc=null;
@@ -4488,43 +4632,43 @@ public PatternDescr lhs_exist() throws RecognitionException {
d = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:17: (loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column ) )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:17: loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:913:17: (loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:913:17: loc= 'exists' ( '(' column= lhs_column ')' | column= lhs_column )
{
loc=(Token)input.LT(1);
- match(input,54,FOLLOW_54_in_lhs_exist2474);
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:30: ( '(' column= lhs_column ')' | column= lhs_column )
- int alt58=2;
- int LA58_0 = input.LA(1);
- if ( LA58_0==21 ) {
- alt58=1;
+ match(input,54,FOLLOW_54_in_lhs_exist2551);
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:913:30: ( '(' column= lhs_column ')' | column= lhs_column )
+ int alt59=2;
+ int LA59_0 = input.LA(1);
+ if ( LA59_0==21 ) {
+ alt59=1;
}
- else if ( LA58_0==ID ) {
- alt58=2;
+ else if ( LA59_0==ID ) {
+ alt59=2;
}
else {
NoViableAltException nvae =
- new NoViableAltException("881:30: ( \'(\' column= lhs_column \')\' | column= lhs_column )", 58, 0, input);
+ new NoViableAltException("913:30: ( \'(\' column= lhs_column \')\' | column= lhs_column )", 59, 0, input);
throw nvae;
}
- switch (alt58) {
+ switch (alt59) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:31: '(' column= lhs_column ')'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:913:31: '(' column= lhs_column ')'
{
- match(input,21,FOLLOW_21_in_lhs_exist2477);
- following.push(FOLLOW_lhs_column_in_lhs_exist2481);
+ match(input,21,FOLLOW_21_in_lhs_exist2554);
+ following.push(FOLLOW_lhs_column_in_lhs_exist2558);
column=lhs_column();
following.pop();
- match(input,23,FOLLOW_23_in_lhs_exist2483);
+ match(input,23,FOLLOW_23_in_lhs_exist2560);
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:881:59: column= lhs_column
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:913:59: column= lhs_column
{
- following.push(FOLLOW_lhs_column_in_lhs_exist2489);
+ following.push(FOLLOW_lhs_column_in_lhs_exist2566);
column=lhs_column();
following.pop();
@@ -4554,7 +4698,7 @@ else if ( LA58_0==ID ) {
// $ANTLR start lhs_not
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:888:1: lhs_not returns [NotDescr d] : loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column ) ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:920:1: lhs_not returns [NotDescr d] : loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column ) ;
public NotDescr lhs_not() throws RecognitionException {
NotDescr d;
Token loc=null;
@@ -4565,43 +4709,43 @@ public NotDescr lhs_not() throws RecognitionException {
d = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:892:17: (loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column ) )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:892:17: loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:17: (loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:17: loc= 'not' ( '(' column= lhs_column ')' | column= lhs_column )
{
loc=(Token)input.LT(1);
- match(input,55,FOLLOW_55_in_lhs_not2519);
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:892:27: ( '(' column= lhs_column ')' | column= lhs_column )
- int alt59=2;
- int LA59_0 = input.LA(1);
- if ( LA59_0==21 ) {
- alt59=1;
+ match(input,55,FOLLOW_55_in_lhs_not2596);
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:27: ( '(' column= lhs_column ')' | column= lhs_column )
+ int alt60=2;
+ int LA60_0 = input.LA(1);
+ if ( LA60_0==21 ) {
+ alt60=1;
}
- else if ( LA59_0==ID ) {
- alt59=2;
+ else if ( LA60_0==ID ) {
+ alt60=2;
}
else {
NoViableAltException nvae =
- new NoViableAltException("892:27: ( \'(\' column= lhs_column \')\' | column= lhs_column )", 59, 0, input);
+ new NoViableAltException("924:27: ( \'(\' column= lhs_column \')\' | column= lhs_column )", 60, 0, input);
throw nvae;
}
- switch (alt59) {
+ switch (alt60) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:892:28: '(' column= lhs_column ')'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:28: '(' column= lhs_column ')'
{
- match(input,21,FOLLOW_21_in_lhs_not2522);
- following.push(FOLLOW_lhs_column_in_lhs_not2526);
+ match(input,21,FOLLOW_21_in_lhs_not2599);
+ following.push(FOLLOW_lhs_column_in_lhs_not2603);
column=lhs_column();
following.pop();
- match(input,23,FOLLOW_23_in_lhs_not2529);
+ match(input,23,FOLLOW_23_in_lhs_not2606);
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:892:57: column= lhs_column
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:57: column= lhs_column
{
- following.push(FOLLOW_lhs_column_in_lhs_not2535);
+ following.push(FOLLOW_lhs_column_in_lhs_not2612);
column=lhs_column();
following.pop();
@@ -4631,7 +4775,7 @@ else if ( LA59_0==ID ) {
// $ANTLR start lhs_eval
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:899:1: lhs_eval returns [PatternDescr d] : 'eval' loc= '(' opt_eol c= paren_chunk ')' ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:931:1: lhs_eval returns [PatternDescr d] : 'eval' loc= '(' c= paren_chunk2 ')' ;
public PatternDescr lhs_eval() throws RecognitionException {
PatternDescr d;
Token loc=null;
@@ -4643,21 +4787,20 @@ public PatternDescr lhs_eval() throws RecognitionException {
String text = "";
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:904:17: ( 'eval' loc= '(' opt_eol c= paren_chunk ')' )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:904:17: 'eval' loc= '(' opt_eol c= paren_chunk ')'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:936:17: ( 'eval' loc= '(' c= paren_chunk2 ')' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:936:17: 'eval' loc= '(' c= paren_chunk2 ')'
{
- match(input,56,FOLLOW_56_in_lhs_eval2561);
+ match(input,56,FOLLOW_56_in_lhs_eval2638);
loc=(Token)input.LT(1);
- match(input,21,FOLLOW_21_in_lhs_eval2565);
- following.push(FOLLOW_opt_eol_in_lhs_eval2567);
- opt_eol();
- following.pop();
-
- following.push(FOLLOW_paren_chunk_in_lhs_eval2571);
- c=paren_chunk();
+ match(input,21,FOLLOW_21_in_lhs_eval2642);
+ System.err.println( "START EVAL" );
+ following.push(FOLLOW_paren_chunk2_in_lhs_eval2655);
+ c=paren_chunk2();
following.pop();
- match(input,23,FOLLOW_23_in_lhs_eval2573);
+ System.err.println( "END EVAL" );
+ match(input,23,FOLLOW_23_in_lhs_eval2664);
+ System.err.println( "END 2" );
checkTrailingSemicolon( c, loc.getLine() );
d = new EvalDescr( c );
@@ -4678,7 +4821,7 @@ public PatternDescr lhs_eval() throws RecognitionException {
// $ANTLR start dotted_name
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:911:1: dotted_name returns [String name] : id= ID ( '.' id= ID )* ;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:947:1: dotted_name returns [String name] : id= ID ( '.' id= ID )* ;
public String dotted_name() throws RecognitionException {
String name;
Token id=null;
@@ -4687,36 +4830,36 @@ public String dotted_name() throws RecognitionException {
name = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:916:17: (id= ID ( '.' id= ID )* )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:916:17: id= ID ( '.' id= ID )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:952:17: (id= ID ( '.' id= ID )* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:952:17: id= ID ( '.' id= ID )*
{
id=(Token)input.LT(1);
- match(input,ID,FOLLOW_ID_in_dotted_name2605);
+ match(input,ID,FOLLOW_ID_in_dotted_name2697);
name=id.getText();
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:916:46: ( '.' id= ID )*
- loop60:
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:952:46: ( '.' id= ID )*
+ loop61:
do {
- int alt60=2;
- int LA60_0 = input.LA(1);
- if ( LA60_0==49 ) {
- alt60=1;
+ int alt61=2;
+ int LA61_0 = input.LA(1);
+ if ( LA61_0==49 ) {
+ alt61=1;
}
- switch (alt60) {
+ switch (alt61) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:916:48: '.' id= ID
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:952:48: '.' id= ID
{
- match(input,49,FOLLOW_49_in_dotted_name2611);
+ match(input,49,FOLLOW_49_in_dotted_name2703);
id=(Token)input.LT(1);
- match(input,ID,FOLLOW_ID_in_dotted_name2615);
+ match(input,ID,FOLLOW_ID_in_dotted_name2707);
name = name + "." + id.getText();
}
break;
default :
- break loop60;
+ break loop61;
}
} while (true);
@@ -4736,7 +4879,7 @@ public String dotted_name() throws RecognitionException {
// $ANTLR start word
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:920:1: word returns [String word] : (id= ID | 'import' | 'use' | 'rule' | 'query' | 'salience' | 'no-loop' | 'when' | 'then' | 'end' | str= STRING );
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:956:1: word returns [String word] : (id= ID | 'import' | 'use' | 'rule' | 'query' | 'salience' | 'no-loop' | 'when' | 'then' | 'end' | str= STRING );
public String word() throws RecognitionException {
String word;
Token id=null;
@@ -4746,136 +4889,136 @@ public String word() throws RecognitionException {
word = null;
try {
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:17: (id= ID | 'import' | 'use' | 'rule' | 'query' | 'salience' | 'no-loop' | 'when' | 'then' | 'end' | str= STRING )
- int alt61=11;
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:960:17: (id= ID | 'import' | 'use' | 'rule' | 'query' | 'salience' | 'no-loop' | 'when' | 'then' | 'end' | str= STRING )
+ int alt62=11;
switch ( input.LA(1) ) {
case ID:
- alt61=1;
+ alt62=1;
break;
case 17:
- alt61=2;
+ alt62=2;
break;
case 57:
- alt61=3;
+ alt62=3;
break;
case 28:
- alt61=4;
+ alt62=4;
break;
case 26:
- alt61=5;
+ alt62=5;
break;
case 33:
- alt61=6;
+ alt62=6;
break;
case 34:
- alt61=7;
+ alt62=7;
break;
case 29:
- alt61=8;
+ alt62=8;
break;
case 31:
- alt61=9;
+ alt62=9;
break;
case 27:
- alt61=10;
+ alt62=10;
break;
case STRING:
- alt61=11;
+ alt62=11;
break;
default:
NoViableAltException nvae =
- new NoViableAltException("920:1: word returns [String word] : (id= ID | \'import\' | \'use\' | \'rule\' | \'query\' | \'salience\' | \'no-loop\' | \'when\' | \'then\' | \'end\' | str= STRING );", 61, 0, input);
+ new NoViableAltException("956:1: word returns [String word] : (id= ID | \'import\' | \'use\' | \'rule\' | \'query\' | \'salience\' | \'no-loop\' | \'when\' | \'then\' | \'end\' | str= STRING );", 62, 0, input);
throw nvae;
}
- switch (alt61) {
+ switch (alt62) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:924:17: id= ID
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:960:17: id= ID
{
id=(Token)input.LT(1);
- match(input,ID,FOLLOW_ID_in_word2645);
+ match(input,ID,FOLLOW_ID_in_word2737);
word=id.getText();
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:925:17: 'import'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:17: 'import'
{
- match(input,17,FOLLOW_17_in_word2657);
+ match(input,17,FOLLOW_17_in_word2749);
word="import";
}
break;
case 3 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:926:17: 'use'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:962:17: 'use'
{
- match(input,57,FOLLOW_57_in_word2666);
+ match(input,57,FOLLOW_57_in_word2758);
word="use";
}
break;
case 4 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:927:17: 'rule'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:963:17: 'rule'
{
- match(input,28,FOLLOW_28_in_word2678);
+ match(input,28,FOLLOW_28_in_word2770);
word="rule";
}
break;
case 5 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:928:17: 'query'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:964:17: 'query'
{
- match(input,26,FOLLOW_26_in_word2689);
+ match(input,26,FOLLOW_26_in_word2781);
word="query";
}
break;
case 6 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:929:17: 'salience'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:17: 'salience'
{
- match(input,33,FOLLOW_33_in_word2699);
+ match(input,33,FOLLOW_33_in_word2791);
word="salience";
}
break;
case 7 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:930:17: 'no-loop'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:966:17: 'no-loop'
{
- match(input,34,FOLLOW_34_in_word2707);
+ match(input,34,FOLLOW_34_in_word2799);
word="no-loop";
}
break;
case 8 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:931:17: 'when'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:967:17: 'when'
{
- match(input,29,FOLLOW_29_in_word2715);
+ match(input,29,FOLLOW_29_in_word2807);
word="when";
}
break;
case 9 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:932:17: 'then'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:968:17: 'then'
{
- match(input,31,FOLLOW_31_in_word2726);
+ match(input,31,FOLLOW_31_in_word2818);
word="then";
}
break;
case 10 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:933:17: 'end'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:17: 'end'
{
- match(input,27,FOLLOW_27_in_word2737);
+ match(input,27,FOLLOW_27_in_word2829);
word="end";
}
break;
case 11 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:934:17: str= STRING
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:970:17: str= STRING
{
str=(Token)input.LT(1);
- match(input,STRING,FOLLOW_STRING_in_word2751);
+ match(input,STRING,FOLLOW_STRING_in_word2843);
word=getString(str);
}
@@ -4900,20 +5043,20 @@ public int predict(IntStream input) throws RecognitionException {
return predict(input, s0);
}
DFA.State s1 = new DFA.State() {{alt=4;}};
- DFA.State s4 = new DFA.State() {{alt=2;}};
DFA.State s3 = new DFA.State() {{alt=1;}};
+ DFA.State s4 = new DFA.State() {{alt=2;}};
DFA.State s2 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case 26:
- return s4;
+ case 28:
+ return s3;
case EOL:
case 15:
return s2;
- case 28:
- return s3;
+ case 26:
+ return s4;
default:
NoViableAltException nvae =
@@ -5029,15 +5172,16 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae;
}
};
- DFA.State s99 = new DFA.State() {{alt=1;}};
+ DFA.State s71 = new DFA.State() {{alt=1;}};
+ DFA.State s100 = new DFA.State() {{alt=1;}};
DFA.State s101 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 25:
- return s99;
+ return s100;
case 24:
- return s100;
+ return s99;
case EOL:
case ID:
@@ -5100,13 +5244,13 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae; }
}
};
- DFA.State s100 = new DFA.State() {
+ DFA.State s99 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case 25:
+ case 24:
return s99;
- case 24:
+ case 25:
return s100;
case EOL:
@@ -5165,7 +5309,7 @@ public DFA.State transition(IntStream input) throws RecognitionException {
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 100, input);
+ new NoViableAltException("", 4, 99, input);
throw nvae; }
}
@@ -5173,10 +5317,10 @@ public DFA.State transition(IntStream input) throws RecognitionException {
DFA.State s93 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case 25:
+ case 24:
return s99;
- case 24:
+ case 25:
return s100;
case EOL:
@@ -5452,7 +5596,7 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae; }
}
};
- DFA.State s71 = new DFA.State() {
+ DFA.State s72 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 24:
@@ -5517,20 +5661,19 @@ public DFA.State transition(IntStream input) throws RecognitionException {
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 71, input);
+ new NoViableAltException("", 4, 72, input);
throw nvae; }
}
};
- DFA.State s72 = new DFA.State() {{alt=1;}};
DFA.State s73 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 25:
- return s72;
+ return s71;
case 24:
- return s71;
+ return s72;
case EOL:
case ID:
@@ -5596,10 +5739,10 @@ public DFA.State transition(IntStream input) throws RecognitionException {
DFA.State s58 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case 24:
+ case 25:
return s71;
- case 25:
+ case 24:
return s72;
case EOL:
@@ -5734,7 +5877,7 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae; }
}
};
- DFA.State s44 = new DFA.State() {
+ DFA.State s46 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 24:
@@ -5799,31 +5942,31 @@ public DFA.State transition(IntStream input) throws RecognitionException {
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 44, input);
+ new NoViableAltException("", 4, 46, input);
throw nvae; }
}
};
- DFA.State s43 = new DFA.State() {
+ DFA.State s45 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_43 = input.LA(1);
- if ( LA4_43==24 ) {return s44;}
- if ( LA4_43==EOL||LA4_43==15 ) {return s43;}
+ int LA4_45 = input.LA(1);
+ if ( LA4_45==24 ) {return s46;}
+ if ( LA4_45==EOL||LA4_45==15 ) {return s45;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 43, input);
+ new NoViableAltException("", 4, 45, input);
throw nvae;
}
};
- DFA.State s30 = new DFA.State() {
+ DFA.State s32 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_30 = input.LA(1);
- if ( LA4_30==EOL||LA4_30==15 ) {return s43;}
- if ( LA4_30==24 ) {return s44;}
+ int LA4_32 = input.LA(1);
+ if ( LA4_32==EOL||LA4_32==15 ) {return s45;}
+ if ( LA4_32==24 ) {return s46;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 30, input);
+ new NoViableAltException("", 4, 32, input);
throw nvae;
}
@@ -5832,10 +5975,10 @@ public DFA.State transition(IntStream input) throws RecognitionException {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 23:
- return s30;
+ return s32;
case 22:
- return s39;
+ return s43;
case EOL:
case 15:
@@ -5848,7 +5991,7 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae; }
}
};
- DFA.State s67 = new DFA.State() {
+ DFA.State s70 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case EOL:
@@ -5856,107 +5999,107 @@ public DFA.State transition(IntStream input) throws RecognitionException {
return s81;
case 23:
- return s30;
+ return s32;
case 22:
- return s39;
+ return s43;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 67, input);
+ new NoViableAltException("", 4, 70, input);
throw nvae; }
}
};
- DFA.State s63 = new DFA.State() {
+ DFA.State s66 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 23:
- return s30;
+ return s32;
case 22:
- return s39;
+ return s43;
case EOL:
case 15:
- return s63;
+ return s66;
case ID:
- return s67;
+ return s70;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 63, input);
+ new NoViableAltException("", 4, 66, input);
throw nvae; }
}
};
- DFA.State s52 = new DFA.State() {
+ DFA.State s55 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case EOL:
case 15:
- return s63;
+ return s66;
case 23:
- return s30;
+ return s32;
case 22:
- return s39;
+ return s43;
case 49:
return s16;
case ID:
- return s67;
+ return s70;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 52, input);
+ new NoViableAltException("", 4, 55, input);
throw nvae; }
}
};
- DFA.State s51 = new DFA.State() {
+ DFA.State s54 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_51 = input.LA(1);
- if ( LA4_51==ID ) {return s52;}
- if ( LA4_51==EOL||LA4_51==15 ) {return s51;}
+ int LA4_54 = input.LA(1);
+ if ( LA4_54==ID ) {return s55;}
+ if ( LA4_54==EOL||LA4_54==15 ) {return s54;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 51, input);
+ new NoViableAltException("", 4, 54, input);
throw nvae;
}
};
- DFA.State s39 = new DFA.State() {
+ DFA.State s43 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_39 = input.LA(1);
- if ( LA4_39==EOL||LA4_39==15 ) {return s51;}
- if ( LA4_39==ID ) {return s52;}
+ int LA4_43 = input.LA(1);
+ if ( LA4_43==EOL||LA4_43==15 ) {return s54;}
+ if ( LA4_43==ID ) {return s55;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 39, input);
+ new NoViableAltException("", 4, 43, input);
throw nvae;
}
};
- DFA.State s53 = new DFA.State() {
+ DFA.State s51 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 22:
- return s39;
+ return s43;
case 23:
- return s30;
+ return s32;
case EOL:
case 15:
- return s53;
+ return s51;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 53, input);
+ new NoViableAltException("", 4, 51, input);
throw nvae; }
}
@@ -5966,13 +6109,13 @@ public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case EOL:
case 15:
- return s53;
+ return s51;
case 22:
- return s39;
+ return s43;
case 23:
- return s30;
+ return s32;
default:
NoViableAltException nvae =
@@ -5981,135 +6124,135 @@ public DFA.State transition(IntStream input) throws RecognitionException {
throw nvae; }
}
};
- DFA.State s38 = new DFA.State() {
+ DFA.State s41 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case ID:
- return s42;
+ case 22:
+ return s43;
+
+ case 23:
+ return s32;
case EOL:
case 15:
- return s38;
+ return s41;
- case 22:
- return s39;
-
- case 23:
- return s30;
+ case ID:
+ return s42;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 38, input);
+ new NoViableAltException("", 4, 41, input);
throw nvae; }
}
};
- DFA.State s29 = new DFA.State() {
+ DFA.State s31 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
+ case 49:
+ return s16;
+
case EOL:
case 15:
- return s38;
+ return s41;
+
+ case ID:
+ return s42;
case 22:
- return s39;
+ return s43;
case 23:
- return s30;
-
- case 49:
- return s16;
-
- case ID:
- return s42;
+ return s32;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 29, input);
+ new NoViableAltException("", 4, 31, input);
throw nvae; }
}
};
- DFA.State s28 = new DFA.State() {
+ DFA.State s30 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case ID:
- return s29;
+ return s31;
case EOL:
case 15:
- return s28;
+ return s30;
case 23:
- return s30;
+ return s32;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 28, input);
+ new NoViableAltException("", 4, 30, input);
throw nvae; }
}
};
- DFA.State s21 = new DFA.State() {
+ DFA.State s23 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case EOL:
case 15:
- return s28;
+ return s30;
case ID:
- return s29;
+ return s31;
case 23:
- return s30;
+ return s32;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 21, input);
+ new NoViableAltException("", 4, 23, input);
throw nvae; }
}
};
- DFA.State s31 = new DFA.State() {
+ DFA.State s28 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_31 = input.LA(1);
- if ( LA4_31==21 ) {return s21;}
- if ( LA4_31==EOL||LA4_31==15 ) {return s31;}
+ int LA4_28 = input.LA(1);
+ if ( LA4_28==21 ) {return s23;}
+ if ( LA4_28==EOL||LA4_28==15 ) {return s28;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 31, input);
+ new NoViableAltException("", 4, 28, input);
throw nvae;
}
};
- DFA.State s23 = new DFA.State() {
+ DFA.State s22 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
- int LA4_23 = input.LA(1);
- if ( LA4_23==EOL||LA4_23==15 ) {return s31;}
- if ( LA4_23==21 ) {return s21;}
+ int LA4_22 = input.LA(1);
+ if ( LA4_22==EOL||LA4_22==15 ) {return s28;}
+ if ( LA4_22==21 ) {return s23;}
NoViableAltException nvae =
- new NoViableAltException("", 4, 23, input);
+ new NoViableAltException("", 4, 22, input);
throw nvae;
}
};
- DFA.State s20 = new DFA.State() {
+ DFA.State s21 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
case 21:
- return s21;
+ return s23;
case EOL:
case 15:
- return s20;
+ return s21;
case ID:
- return s23;
+ return s22;
default:
NoViableAltException nvae =
- new NoViableAltException("", 4, 20, input);
+ new NoViableAltException("", 4, 21, input);
throw nvae; }
}
@@ -6117,17 +6260,17 @@ public DFA.State transition(IntStream input) throws RecognitionException {
DFA.State s13 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
+ case 49:
+ return s16;
+
case EOL:
case 15:
- return s20;
-
- case 21:
return s21;
- case 49:
- return s16;
-
case ID:
+ return s22;
+
+ case 21:
return s23;
default:
@@ -6318,21 +6461,21 @@ public DFA.State transition(IntStream input) throws RecognitionException {
public int predict(IntStream input) throws RecognitionException {
return predict(input, s0);
}
- DFA.State s6 = new DFA.State() {{alt=1;}};
DFA.State s2 = new DFA.State() {{alt=2;}};
+ DFA.State s6 = new DFA.State() {{alt=1;}};
DFA.State s3 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case ID:
- return s6;
+ case 22:
+ case 23:
+ return s2;
case EOL:
case 15:
return s3;
- case 22:
- case 23:
- return s2;
+ case ID:
+ return s6;
default:
NoViableAltException nvae =
@@ -6444,13 +6587,13 @@ public int predict(IntStream input) throws RecognitionException {
DFA.State s1 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case ID:
- return s2;
-
case EOL:
case 15:
return s1;
+ case ID:
+ return s2;
+
case 23:
return s3;
@@ -6486,14 +6629,11 @@ public DFA.State transition(IntStream input) throws RecognitionException {
public int predict(IntStream input) throws RecognitionException {
return predict(input, s0);
}
- DFA.State s3 = new DFA.State() {{alt=1;}};
DFA.State s2 = new DFA.State() {{alt=2;}};
+ DFA.State s3 = new DFA.State() {{alt=1;}};
DFA.State s1 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
- case 22:
- return s3;
-
case EOL:
case 15:
return s1;
@@ -6501,6 +6641,9 @@ public DFA.State transition(IntStream input) throws RecognitionException {
case 23:
return s2;
+ case 22:
+ return s3;
+
default:
NoViableAltException nvae =
new NoViableAltException("", 48, 1, input);
@@ -6533,8 +6676,8 @@ public DFA.State transition(IntStream input) throws RecognitionException {
public int predict(IntStream input) throws RecognitionException {
return predict(input, s0);
}
- DFA.State s3 = new DFA.State() {{alt=2;}};
- DFA.State s6 = new DFA.State() {{alt=1;}};
+ DFA.State s4 = new DFA.State() {{alt=2;}};
+ DFA.State s3 = new DFA.State() {{alt=1;}};
DFA.State s2 = new DFA.State() {
public DFA.State transition(IntStream input) throws RecognitionException {
switch ( input.LA(1) ) {
@@ -6552,10 +6695,10 @@ public DFA.State transition(IntStream input) throws RecognitionException {
case 45:
case 46:
case 47:
- return s3;
+ return s4;
case 30:
- return s6;
+ return s3;
default:
NoViableAltException nvae =
@@ -6571,6 +6714,9 @@ public DFA.State transition(IntStream input) throws RecognitionException {
case 15:
return s2;
+ case 30:
+ return s3;
+
case 22:
case 23:
case 40:
@@ -6581,10 +6727,7 @@ public DFA.State transition(IntStream input) throws RecognitionException {
case 45:
case 46:
case 47:
- return s3;
-
- case 30:
- return s6;
+ return s4;
default:
NoViableAltException nvae =
@@ -6812,52 +6955,54 @@ public DFA.State transition(IntStream input) throws RecognitionException {
public static final BitSet FOLLOW_21_in_paren_chunk2149 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
public static final BitSet FOLLOW_paren_chunk_in_paren_chunk2153 = new BitSet(new long[]{0x0000000000800000L});
public static final BitSet FOLLOW_23_in_paren_chunk2155 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
- public static final BitSet FOLLOW_24_in_curly_chunk2224 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
- public static final BitSet FOLLOW_curly_chunk_in_curly_chunk2228 = new BitSet(new long[]{0x0000000002000000L});
- public static final BitSet FOLLOW_25_in_curly_chunk2230 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
- public static final BitSet FOLLOW_lhs_and_in_lhs_or2288 = new BitSet(new long[]{0x0008008000000002L});
- public static final BitSet FOLLOW_set_in_lhs_or2297 = new BitSet(new long[]{0x0000000000008012L});
- public static final BitSet FOLLOW_opt_eol_in_lhs_or2302 = new BitSet(new long[]{0x01C0000000200020L});
- public static final BitSet FOLLOW_lhs_and_in_lhs_or2309 = new BitSet(new long[]{0x0008008000000002L});
- public static final BitSet FOLLOW_lhs_unary_in_lhs_and2349 = new BitSet(new long[]{0x0030000000000002L});
- public static final BitSet FOLLOW_set_in_lhs_and2358 = new BitSet(new long[]{0x0000000000008012L});
- public static final BitSet FOLLOW_opt_eol_in_lhs_and2363 = new BitSet(new long[]{0x01C0000000200020L});
- public static final BitSet FOLLOW_lhs_unary_in_lhs_and2370 = new BitSet(new long[]{0x0030000000000002L});
- public static final BitSet FOLLOW_lhs_exist_in_lhs_unary2408 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_lhs_not_in_lhs_unary2416 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_lhs_eval_in_lhs_unary2424 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_lhs_column_in_lhs_unary2432 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_21_in_lhs_unary2438 = new BitSet(new long[]{0x01C0000000200020L});
- public static final BitSet FOLLOW_lhs_in_lhs_unary2442 = new BitSet(new long[]{0x0000000000800000L});
- public static final BitSet FOLLOW_23_in_lhs_unary2444 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_54_in_lhs_exist2474 = new BitSet(new long[]{0x0000000000200020L});
- public static final BitSet FOLLOW_21_in_lhs_exist2477 = new BitSet(new long[]{0x0000000000000020L});
- public static final BitSet FOLLOW_lhs_column_in_lhs_exist2481 = new BitSet(new long[]{0x0000000000800000L});
- public static final BitSet FOLLOW_23_in_lhs_exist2483 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_lhs_column_in_lhs_exist2489 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_55_in_lhs_not2519 = new BitSet(new long[]{0x0000000000200020L});
- public static final BitSet FOLLOW_21_in_lhs_not2522 = new BitSet(new long[]{0x0000000000000020L});
- public static final BitSet FOLLOW_lhs_column_in_lhs_not2526 = new BitSet(new long[]{0x0000000000800000L});
- public static final BitSet FOLLOW_23_in_lhs_not2529 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_lhs_column_in_lhs_not2535 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_56_in_lhs_eval2561 = new BitSet(new long[]{0x0000000000200000L});
- public static final BitSet FOLLOW_21_in_lhs_eval2565 = new BitSet(new long[]{0x0000000000008012L});
- public static final BitSet FOLLOW_opt_eol_in_lhs_eval2567 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
- public static final BitSet FOLLOW_paren_chunk_in_lhs_eval2571 = new BitSet(new long[]{0x0000000000800000L});
- public static final BitSet FOLLOW_23_in_lhs_eval2573 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_ID_in_dotted_name2605 = new BitSet(new long[]{0x0002000000000002L});
- public static final BitSet FOLLOW_49_in_dotted_name2611 = new BitSet(new long[]{0x0000000000000020L});
- public static final BitSet FOLLOW_ID_in_dotted_name2615 = new BitSet(new long[]{0x0002000000000002L});
- public static final BitSet FOLLOW_ID_in_word2645 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_17_in_word2657 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_57_in_word2666 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_28_in_word2678 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_26_in_word2689 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_33_in_word2699 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_34_in_word2707 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_29_in_word2715 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_31_in_word2726 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_27_in_word2737 = new BitSet(new long[]{0x0000000000000002L});
- public static final BitSet FOLLOW_STRING_in_word2751 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_21_in_paren_chunk22226 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
+ public static final BitSet FOLLOW_paren_chunk2_in_paren_chunk22230 = new BitSet(new long[]{0x0000000000800000L});
+ public static final BitSet FOLLOW_23_in_paren_chunk22232 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
+ public static final BitSet FOLLOW_24_in_curly_chunk2301 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
+ public static final BitSet FOLLOW_curly_chunk_in_curly_chunk2305 = new BitSet(new long[]{0x0000000002000000L});
+ public static final BitSet FOLLOW_25_in_curly_chunk2307 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
+ public static final BitSet FOLLOW_lhs_and_in_lhs_or2365 = new BitSet(new long[]{0x0008008000000002L});
+ public static final BitSet FOLLOW_set_in_lhs_or2374 = new BitSet(new long[]{0x0000000000008012L});
+ public static final BitSet FOLLOW_opt_eol_in_lhs_or2379 = new BitSet(new long[]{0x01C0000000200020L});
+ public static final BitSet FOLLOW_lhs_and_in_lhs_or2386 = new BitSet(new long[]{0x0008008000000002L});
+ public static final BitSet FOLLOW_lhs_unary_in_lhs_and2426 = new BitSet(new long[]{0x0030000000000002L});
+ public static final BitSet FOLLOW_set_in_lhs_and2435 = new BitSet(new long[]{0x0000000000008012L});
+ public static final BitSet FOLLOW_opt_eol_in_lhs_and2440 = new BitSet(new long[]{0x01C0000000200020L});
+ public static final BitSet FOLLOW_lhs_unary_in_lhs_and2447 = new BitSet(new long[]{0x0030000000000002L});
+ public static final BitSet FOLLOW_lhs_exist_in_lhs_unary2485 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_lhs_not_in_lhs_unary2493 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_lhs_eval_in_lhs_unary2501 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_lhs_column_in_lhs_unary2509 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_21_in_lhs_unary2515 = new BitSet(new long[]{0x01C0000000200020L});
+ public static final BitSet FOLLOW_lhs_in_lhs_unary2519 = new BitSet(new long[]{0x0000000000800000L});
+ public static final BitSet FOLLOW_23_in_lhs_unary2521 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_54_in_lhs_exist2551 = new BitSet(new long[]{0x0000000000200020L});
+ public static final BitSet FOLLOW_21_in_lhs_exist2554 = new BitSet(new long[]{0x0000000000000020L});
+ public static final BitSet FOLLOW_lhs_column_in_lhs_exist2558 = new BitSet(new long[]{0x0000000000800000L});
+ public static final BitSet FOLLOW_23_in_lhs_exist2560 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_lhs_column_in_lhs_exist2566 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_55_in_lhs_not2596 = new BitSet(new long[]{0x0000000000200020L});
+ public static final BitSet FOLLOW_21_in_lhs_not2599 = new BitSet(new long[]{0x0000000000000020L});
+ public static final BitSet FOLLOW_lhs_column_in_lhs_not2603 = new BitSet(new long[]{0x0000000000800000L});
+ public static final BitSet FOLLOW_23_in_lhs_not2606 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_lhs_column_in_lhs_not2612 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_56_in_lhs_eval2638 = new BitSet(new long[]{0x0000000000200000L});
+ public static final BitSet FOLLOW_21_in_lhs_eval2642 = new BitSet(new long[]{0x03FFFFFFFFFFFFF2L});
+ public static final BitSet FOLLOW_paren_chunk2_in_lhs_eval2655 = new BitSet(new long[]{0x0000000000800000L});
+ public static final BitSet FOLLOW_23_in_lhs_eval2664 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_ID_in_dotted_name2697 = new BitSet(new long[]{0x0002000000000002L});
+ public static final BitSet FOLLOW_49_in_dotted_name2703 = new BitSet(new long[]{0x0000000000000020L});
+ public static final BitSet FOLLOW_ID_in_dotted_name2707 = new BitSet(new long[]{0x0002000000000002L});
+ public static final BitSet FOLLOW_ID_in_word2737 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_17_in_word2749 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_57_in_word2758 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_28_in_word2770 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_26_in_word2781 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_33_in_word2791 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_34_in_word2799 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_29_in_word2807 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_31_in_word2818 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_27_in_word2829 = new BitSet(new long[]{0x0000000000000002L});
+ public static final BitSet FOLLOW_STRING_in_word2843 = new BitSet(new long[]{0x0000000000000002L});
}
\ No newline at end of file
diff --git a/drools-compiler/src/main/java/org/drools/lang/RuleParserLexer.java b/drools-compiler/src/main/java/org/drools/lang/RuleParserLexer.java
index 318b27bab15..82190f58895 100644
--- a/drools-compiler/src/main/java/org/drools/lang/RuleParserLexer.java
+++ b/drools-compiler/src/main/java/org/drools/lang/RuleParserLexer.java
@@ -1,4 +1,4 @@
-// $ANTLR 3.0ea8 /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g 2006-04-22 22:27:32
+// $ANTLR 3.0ea8 /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g 2006-04-22 23:00:58
package org.drools.lang;
@@ -1235,7 +1235,7 @@ public void mMISC() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 44) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:17: ( '!' | '@' | '$' | '%' | '^' | '&' | '*' | '_' | '-' | '+' | '|' | ',' | '{' | '}' | '[' | ']' | '=' | '/' | '(' | ')' | '\'' | '\\' | '||' | '&&' | '<<<' | '++' | '--' | '>>>' | '==' | '+=' | '=+' | '-=' | '=-' | '*=' | '=*' | '/=' | '=/' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:17: ( '!' | '@' | '$' | '%' | '^' | '&' | '*' | '_' | '-' | '+' | '|' | ',' | '{' | '}' | '[' | ']' | '=' | '/' | '(' | ')' | '\'' | '\\' | '||' | '&&' | '<<<' | '++' | '--' | '>>>' | '==' | '+=' | '=+' | '-=' | '=-' | '*=' | '=*' | '/=' | '=/' )
int alt1=37;
switch ( input.LA(1) ) {
case '!':
@@ -1369,168 +1369,168 @@ public void mMISC() throws RecognitionException {
default:
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("938:1: MISC : ( \'!\' | \'@\' | \'$\' | \'%\' | \'^\' | \'&\' | \'*\' | \'_\' | \'-\' | \'+\' | \'|\' | \',\' | \'{\' | \'}\' | \'[\' | \']\' | \'=\' | \'/\' | \'(\' | \')\' | \'\\\'\' | \'\\\\\' | \'||\' | \'&&\' | \'<<<\' | \'++\' | \'--\' | \'>>>\' | \'==\' | \'+=\' | \'=+\' | \'-=\' | \'=-\' | \'*=\' | \'=*\' | \'/=\' | \'=/\' );", 1, 0, input);
+ new NoViableAltException("974:1: MISC : ( \'!\' | \'@\' | \'$\' | \'%\' | \'^\' | \'&\' | \'*\' | \'_\' | \'-\' | \'+\' | \'|\' | \',\' | \'{\' | \'}\' | \'[\' | \']\' | \'=\' | \'/\' | \'(\' | \')\' | \'\\\'\' | \'\\\\\' | \'||\' | \'&&\' | \'<<<\' | \'++\' | \'--\' | \'>>>\' | \'==\' | \'+=\' | \'=+\' | \'-=\' | \'=-\' | \'*=\' | \'=*\' | \'/=\' | \'=/\' );", 1, 0, input);
throw nvae;
}
switch (alt1) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:17: '!'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:17: '!'
{
match('!'); if (failed) return ;
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:23: '@'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:23: '@'
{
match('@'); if (failed) return ;
}
break;
case 3 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:29: '$'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:29: '$'
{
match('$'); if (failed) return ;
}
break;
case 4 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:35: '%'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:35: '%'
{
match('%'); if (failed) return ;
}
break;
case 5 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:41: '^'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:41: '^'
{
match('^'); if (failed) return ;
}
break;
case 6 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:47: '&'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:47: '&'
{
match('&'); if (failed) return ;
}
break;
case 7 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:53: '*'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:53: '*'
{
match('*'); if (failed) return ;
}
break;
case 8 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:59: '_'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:59: '_'
{
match('_'); if (failed) return ;
}
break;
case 9 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:65: '-'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:65: '-'
{
match('-'); if (failed) return ;
}
break;
case 10 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:939:71: '+'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:975:71: '+'
{
match('+'); if (failed) return ;
}
break;
case 11 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:19: '|'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:19: '|'
{
match('|'); if (failed) return ;
}
break;
case 12 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:25: ','
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:25: ','
{
match(','); if (failed) return ;
}
break;
case 13 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:31: '{'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:31: '{'
{
match('{'); if (failed) return ;
}
break;
case 14 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:37: '}'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:37: '}'
{
match('}'); if (failed) return ;
}
break;
case 15 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:43: '['
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:43: '['
{
match('['); if (failed) return ;
}
break;
case 16 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:49: ']'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:49: ']'
{
match(']'); if (failed) return ;
}
break;
case 17 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:55: '='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:55: '='
{
match('='); if (failed) return ;
}
break;
case 18 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:61: '/'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:61: '/'
{
match('/'); if (failed) return ;
}
break;
case 19 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:67: '('
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:67: '('
{
match('('); if (failed) return ;
}
break;
case 20 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:73: ')'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:73: ')'
{
match(')'); if (failed) return ;
}
break;
case 21 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:79: '\''
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:79: '\''
{
match('\''); if (failed) return ;
}
break;
case 22 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:940:86: '\\'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:976:86: '\\'
{
match('\\'); if (failed) return ;
}
break;
case 23 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:19: '||'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:19: '||'
{
match("||"); if (failed) return ;
@@ -1538,7 +1538,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 24 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:26: '&&'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:26: '&&'
{
match("&&"); if (failed) return ;
@@ -1546,7 +1546,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 25 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:33: '<<<'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:33: '<<<'
{
match("<<<"); if (failed) return ;
@@ -1554,7 +1554,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 26 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:41: '++'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:41: '++'
{
match("++"); if (failed) return ;
@@ -1562,7 +1562,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 27 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:48: '--'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:48: '--'
{
match("--"); if (failed) return ;
@@ -1570,7 +1570,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 28 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:55: '>>>'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:55: '>>>'
{
match(">>>"); if (failed) return ;
@@ -1578,7 +1578,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 29 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:63: '=='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:63: '=='
{
match("=="); if (failed) return ;
@@ -1586,7 +1586,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 30 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:70: '+='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:70: '+='
{
match("+="); if (failed) return ;
@@ -1594,7 +1594,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 31 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:77: '=+'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:77: '=+'
{
match("=+"); if (failed) return ;
@@ -1602,7 +1602,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 32 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:84: '-='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:84: '-='
{
match("-="); if (failed) return ;
@@ -1610,7 +1610,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 33 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:91: '=-'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:91: '=-'
{
match("=-"); if (failed) return ;
@@ -1618,7 +1618,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 34 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:97: '*='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:97: '*='
{
match("*="); if (failed) return ;
@@ -1626,7 +1626,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 35 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:941:104: '=*'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:104: '=*'
{
match("=*"); if (failed) return ;
@@ -1634,7 +1634,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 36 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:942:19: '/='
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:978:19: '/='
{
match("/="); if (failed) return ;
@@ -1642,7 +1642,7 @@ public void mMISC() throws RecognitionException {
}
break;
case 37 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:942:26: '=/'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:978:26: '=/'
{
match("=/"); if (failed) return ;
@@ -1670,8 +1670,8 @@ public void mWS() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 45) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:946:17: ( (' '|'\t'|'\f'))
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:946:17: (' '|'\t'|'\f')
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:17: ( (' '|'\t'|'\f'))
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:17: (' '|'\t'|'\f')
{
if ( input.LA(1)=='\t'||input.LA(1)=='\f'||input.LA(1)==' ' ) {
input.consume();
@@ -1709,10 +1709,10 @@ public void mEOL() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 46) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:17: ( ( ( '\r\n' )=> '\r\n' | '\r' | '\n' ) )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:17: ( ( '\r\n' )=> '\r\n' | '\r' | '\n' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:17: ( ( ( '\r\n' )=> '\r\n' | '\r' | '\n' ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:17: ( ( '\r\n' )=> '\r\n' | '\r' | '\n' )
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:17: ( ( '\r\n' )=> '\r\n' | '\r' | '\n' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:17: ( ( '\r\n' )=> '\r\n' | '\r' | '\n' )
int alt2=3;
int LA2_0 = input.LA(1);
if ( LA2_0=='\r' ) {
@@ -1729,13 +1729,13 @@ else if ( LA2_0=='\n' ) {
else {
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("954:17: ( ( \'\\r\\n\' )=> \'\\r\\n\' | \'\\r\' | \'\\n\' )", 2, 0, input);
+ new NoViableAltException("990:17: ( ( \'\\r\\n\' )=> \'\\r\\n\' | \'\\r\' | \'\\n\' )", 2, 0, input);
throw nvae;
}
switch (alt2) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:25: ( '\r\n' )=> '\r\n'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:25: ( '\r\n' )=> '\r\n'
{
match("\r\n"); if (failed) return ;
@@ -1744,14 +1744,14 @@ else if ( LA2_0=='\n' ) {
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:955:25: '\r'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:991:25: '\r'
{
match('\r'); if (failed) return ;
}
break;
case 3 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:956:25: '\n'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:992:25: '\n'
{
match('\n'); if (failed) return ;
@@ -1782,10 +1782,10 @@ public void mINT() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 47) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:17: ( ( '-' )? ( '0' .. '9' )+ )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:17: ( '-' )? ( '0' .. '9' )+
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:17: ( ( '-' )? ( '0' .. '9' )+ )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:17: ( '-' )? ( '0' .. '9' )+
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:17: ( '-' )?
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:17: ( '-' )?
int alt3=2;
int LA3_0 = input.LA(1);
if ( LA3_0=='-' ) {
@@ -1797,13 +1797,13 @@ else if ( (LA3_0>='0' && LA3_0<='9') ) {
else {
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("961:17: ( \'-\' )?", 3, 0, input);
+ new NoViableAltException("997:17: ( \'-\' )?", 3, 0, input);
throw nvae;
}
switch (alt3) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:18: '-'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:18: '-'
{
match('-'); if (failed) return ;
@@ -1812,7 +1812,7 @@ else if ( (LA3_0>='0' && LA3_0<='9') ) {
}
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:23: ( '0' .. '9' )+
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:23: ( '0' .. '9' )+
int cnt4=0;
loop4:
do {
@@ -1825,7 +1825,7 @@ else if ( (LA3_0>='0' && LA3_0<='9') ) {
switch (alt4) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:961:24: '0' .. '9'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:997:24: '0' .. '9'
{
matchRange('0','9'); if (failed) return ;
@@ -1864,10 +1864,10 @@ public void mFLOAT() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 48) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:17: ( ( '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+ )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:17: ( '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:17: ( ( '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+ )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:17: ( '-' )? ( '0' .. '9' )+ '.' ( '0' .. '9' )+
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:17: ( '-' )?
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:17: ( '-' )?
int alt5=2;
int LA5_0 = input.LA(1);
if ( LA5_0=='-' ) {
@@ -1879,13 +1879,13 @@ else if ( (LA5_0>='0' && LA5_0<='9') ) {
else {
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("965:17: ( \'-\' )?", 5, 0, input);
+ new NoViableAltException("1001:17: ( \'-\' )?", 5, 0, input);
throw nvae;
}
switch (alt5) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:18: '-'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:18: '-'
{
match('-'); if (failed) return ;
@@ -1894,7 +1894,7 @@ else if ( (LA5_0>='0' && LA5_0<='9') ) {
}
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:23: ( '0' .. '9' )+
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:23: ( '0' .. '9' )+
int cnt6=0;
loop6:
do {
@@ -1907,7 +1907,7 @@ else if ( (LA5_0>='0' && LA5_0<='9') ) {
switch (alt6) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:24: '0' .. '9'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:24: '0' .. '9'
{
matchRange('0','9'); if (failed) return ;
@@ -1925,7 +1925,7 @@ else if ( (LA5_0>='0' && LA5_0<='9') ) {
} while (true);
match('.'); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:39: ( '0' .. '9' )+
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:39: ( '0' .. '9' )+
int cnt7=0;
loop7:
do {
@@ -1938,7 +1938,7 @@ else if ( (LA5_0>='0' && LA5_0<='9') ) {
switch (alt7) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:965:40: '0' .. '9'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1001:40: '0' .. '9'
{
matchRange('0','9'); if (failed) return ;
@@ -1977,7 +1977,7 @@ public void mSTRING() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 49) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:17: ( ( '"' ( options {greedy=false; } : . )* '"' ) | ( '\'' ( options {greedy=false; } : . )* '\'' ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:17: ( ( '"' ( options {greedy=false; } : . )* '"' ) | ( '\'' ( options {greedy=false; } : . )* '\'' ) )
int alt10=2;
int LA10_0 = input.LA(1);
if ( LA10_0=='"' ) {
@@ -1989,19 +1989,19 @@ else if ( LA10_0=='\'' ) {
else {
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("968:1: STRING : ( ( \'\"\' ( options {greedy=false; } : . )* \'\"\' ) | ( \'\\\'\' ( options {greedy=false; } : . )* \'\\\'\' ) );", 10, 0, input);
+ new NoViableAltException("1004:1: STRING : ( ( \'\"\' ( options {greedy=false; } : . )* \'\"\' ) | ( \'\\\'\' ( options {greedy=false; } : . )* \'\\\'\' ) );", 10, 0, input);
throw nvae;
}
switch (alt10) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:17: ( '"' ( options {greedy=false; } : . )* '"' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:17: ( '"' ( options {greedy=false; } : . )* '"' )
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:17: ( '"' ( options {greedy=false; } : . )* '"' )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:18: '"' ( options {greedy=false; } : . )* '"'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:17: ( '"' ( options {greedy=false; } : . )* '"' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:18: '"' ( options {greedy=false; } : . )* '"'
{
match('"'); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:22: ( options {greedy=false; } : . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:22: ( options {greedy=false; } : . )*
loop8:
do {
int alt8=2;
@@ -2016,7 +2016,7 @@ else if ( (LA8_0>='\u0000' && LA8_0<='!')||(LA8_0>='#' && LA8_0<='\uFFFE') ) {
switch (alt8) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:49: .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:49: .
{
matchAny(); if (failed) return ;
@@ -2036,13 +2036,13 @@ else if ( (LA8_0>='\u0000' && LA8_0<='!')||(LA8_0>='#' && LA8_0<='\uFFFE') ) {
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:61: ( '\'' ( options {greedy=false; } : . )* '\'' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:61: ( '\'' ( options {greedy=false; } : . )* '\'' )
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:61: ( '\'' ( options {greedy=false; } : . )* '\'' )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:62: '\'' ( options {greedy=false; } : . )* '\''
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:61: ( '\'' ( options {greedy=false; } : . )* '\'' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:62: '\'' ( options {greedy=false; } : . )* '\''
{
match('\''); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:67: ( options {greedy=false; } : . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:67: ( options {greedy=false; } : . )*
loop9:
do {
int alt9=2;
@@ -2057,7 +2057,7 @@ else if ( (LA9_0>='\u0000' && LA9_0<='&')||(LA9_0>='(' && LA9_0<='\uFFFE') ) {
switch (alt9) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:969:94: .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1005:94: .
{
matchAny(); if (failed) return ;
@@ -2097,10 +2097,10 @@ public void mBOOL() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 50) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:973:17: ( ( 'true' | 'false' ) )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:973:17: ( 'true' | 'false' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1009:17: ( ( 'true' | 'false' ) )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1009:17: ( 'true' | 'false' )
{
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:973:17: ( 'true' | 'false' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1009:17: ( 'true' | 'false' )
int alt11=2;
int LA11_0 = input.LA(1);
if ( LA11_0=='t' ) {
@@ -2112,13 +2112,13 @@ else if ( LA11_0=='f' ) {
else {
if (backtracking>0) {failed=true; return ;}
NoViableAltException nvae =
- new NoViableAltException("973:17: ( \'true\' | \'false\' )", 11, 0, input);
+ new NoViableAltException("1009:17: ( \'true\' | \'false\' )", 11, 0, input);
throw nvae;
}
switch (alt11) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:973:18: 'true'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1009:18: 'true'
{
match("true"); if (failed) return ;
@@ -2126,7 +2126,7 @@ else if ( LA11_0=='f' ) {
}
break;
case 2 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:973:25: 'false'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1009:25: 'false'
{
match("false"); if (failed) return ;
@@ -2158,8 +2158,8 @@ public void mID() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 51) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:17: ( ('a'..'z'|'A'..'Z'|'_'|'$') ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))* )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:17: ('a'..'z'|'A'..'Z'|'_'|'$') ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1013:17: ( ('a'..'z'|'A'..'Z'|'_'|'$') ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))* )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1013:17: ('a'..'z'|'A'..'Z'|'_'|'$') ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))*
{
if ( input.LA(1)=='$'||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
@@ -2172,7 +2172,7 @@ public void mID() throws RecognitionException {
recover(mse); throw mse;
}
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:44: ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1013:44: ( ('a'..'z'|'A'..'Z'|'_'|'0'..'9'))*
loop12:
do {
int alt12=2;
@@ -2184,7 +2184,7 @@ public void mID() throws RecognitionException {
switch (alt12) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:977:45: ('a'..'z'|'A'..'Z'|'_'|'0'..'9')
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1013:45: ('a'..'z'|'A'..'Z'|'_'|'0'..'9')
{
if ( (input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='Z')||input.LA(1)=='_'||(input.LA(1)>='a' && input.LA(1)<='z') ) {
input.consume();
@@ -2228,11 +2228,11 @@ public void mSH_STYLE_SINGLE_LINE_COMMENT() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 52) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:17: ( '#' ( options {greedy=false; } : . )* EOL )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:17: '#' ( options {greedy=false; } : . )* EOL
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1018:17: ( '#' ( options {greedy=false; } : . )* EOL )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1018:17: '#' ( options {greedy=false; } : . )* EOL
{
match('#'); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:21: ( options {greedy=false; } : . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1018:21: ( options {greedy=false; } : . )*
loop13:
do {
int alt13=2;
@@ -2250,7 +2250,7 @@ else if ( (LA13_0>='\u0000' && LA13_0<='\t')||(LA13_0>='\u000B' && LA13_0<='\f')
switch (alt13) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:982:48: .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1018:48: .
{
matchAny(); if (failed) return ;
@@ -2288,12 +2288,12 @@ public void mC_STYLE_SINGLE_LINE_COMMENT() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 53) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:988:17: ( '//' ( options {greedy=false; } : . )* EOL )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:988:17: '//' ( options {greedy=false; } : . )* EOL
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1024:17: ( '//' ( options {greedy=false; } : . )* EOL )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1024:17: '//' ( options {greedy=false; } : . )* EOL
{
match("//"); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:988:22: ( options {greedy=false; } : . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1024:22: ( options {greedy=false; } : . )*
loop14:
do {
int alt14=2;
@@ -2311,7 +2311,7 @@ else if ( (LA14_0>='\u0000' && LA14_0<='\t')||(LA14_0>='\u000B' && LA14_0<='\f')
switch (alt14) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:988:49: .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1024:49: .
{
matchAny(); if (failed) return ;
@@ -2349,12 +2349,12 @@ public void mMULTI_LINE_COMMENT() throws RecognitionException {
int charPosition = getCharPositionInLine();
int channel = Token.DEFAULT_CHANNEL;
if ( backtracking>0 && alreadyParsedRule(input, 54) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:993:17: ( '/*' ( options {greedy=false; } : . )* '*/' )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:993:17: '/*' ( options {greedy=false; } : . )* '*/'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1029:17: ( '/*' ( options {greedy=false; } : . )* '*/' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1029:17: '/*' ( options {greedy=false; } : . )* '*/'
{
match("/*"); if (failed) return ;
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:993:22: ( options {greedy=false; } : . )*
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1029:22: ( options {greedy=false; } : . )*
loop15:
do {
int alt15=2;
@@ -2377,7 +2377,7 @@ else if ( (LA15_0>='\u0000' && LA15_0<=')')||(LA15_0>='+' && LA15_0<='\uFFFE') )
switch (alt15) {
case 1 :
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:993:48: .
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:1029:48: .
{
matchAny(); if (failed) return ;
@@ -2799,8 +2799,8 @@ public void mSynpred1_fragment() throws RecognitionException {
int Synpred1_fragment_StartIndex = input.index();
try {
if ( backtracking>0 && alreadyParsedRule(input, 56) ) { return ; }
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:25: ( '\r\n' )
- // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:954:27: '\r\n'
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:25: ( '\r\n' )
+ // /Users/bob/checkouts/jbossrules/drools-compiler/src/main/resources/org/drools/lang/drl.g:990:27: '\r\n'
{
match("\r\n"); if (failed) return ;
diff --git a/drools-compiler/src/main/resources/org/drools/lang/drl.g b/drools-compiler/src/main/resources/org/drools/lang/drl.g
index 057af0c668b..ae3f222b2fd 100644
--- a/drools-compiler/src/main/resources/org/drools/lang/drl.g
+++ b/drools-compiler/src/main/resources/org/drools/lang/drl.g
@@ -136,7 +136,7 @@ grammar RuleParser;
return;
}
errorRecovery = true;
-
+ System.err.println( ex );
errors.add( ex );
}
@@ -767,7 +767,7 @@ paren_chunk returns [String text]
( options{greedy=false;} :
'(' c=paren_chunk ')'
{
- //System.err.println( "chunk [" + c + "]" );
+ System.err.println( "chunk [" + c + "]" );
if ( c == null ) {
c = "";
}
@@ -779,7 +779,39 @@ paren_chunk returns [String text]
}
| any=.
{
- //System.err.println( "any [" + any.getText() + "]" );
+ System.err.println( "any [" + any.getText() + "]" );
+ if ( text == null ) {
+ text = any.getText();
+ } else {
+ text = text + " " + any.getText();
+ }
+ }
+ )*
+ ;
+
+
+paren_chunk2 returns [String text]
+ @init {
+ text = null;
+ }
+
+ :
+ ( options{greedy=false;} :
+ '(' c=paren_chunk2 ')'
+ {
+ System.err.println( "chunk [" + c + "]" );
+ if ( c == null ) {
+ c = "";
+ }
+ if ( text == null ) {
+ text = "( " + c + " )";
+ } else {
+ text = text + " ( " + c + " )";
+ }
+ }
+ | any=.
+ {
+ System.err.println( "any [" + any.getText() + "]" );
if ( text == null ) {
text = any.getText();
} else {
@@ -901,7 +933,11 @@ lhs_eval returns [PatternDescr d]
d = null;
String text = "";
}
- : 'eval' loc='(' opt_eol c=paren_chunk ')'
+ : 'eval' loc='('
+ { System.err.println( "START EVAL" ); }
+ c=paren_chunk2
+ { System.err.println( "END EVAL" ); }
+ ')' { System.err.println( "END 2" ); }
{
checkTrailingSemicolon( c, loc.getLine() );
d = new EvalDescr( c );
diff --git a/drools-compiler/src/test/java/org/drools/lang/RuleParserTest.java b/drools-compiler/src/test/java/org/drools/lang/RuleParserTest.java
index 3e1001e4267..70c6c8f38f6 100644
--- a/drools-compiler/src/test/java/org/drools/lang/RuleParserTest.java
+++ b/drools-compiler/src/test/java/org/drools/lang/RuleParserTest.java
@@ -1282,7 +1282,7 @@ public void testRuleNamesStartingWithNumbers() throws Exception {
assertEquals( "2. Do More Stuff!", ((RuleDescr)pkg.getRules().get( 1 )).getName() );
}
- public void FIXME_testEvalWithNewline() throws Exception {
+ public void testEvalWithNewline() throws Exception {
parseResource( "eval_with_newline.drl" ).compilation_unit();
System.err.println( parser.getErrorMessages() );
diff --git a/drools-compiler/src/test/resources/org/drools/lang/eval_with_newline.drl b/drools-compiler/src/test/resources/org/drools/lang/eval_with_newline.drl
index 147031a60e1..50097bc704c 100644
--- a/drools-compiler/src/test/resources/org/drools/lang/eval_with_newline.drl
+++ b/drools-compiler/src/test/resources/org/drools/lang/eval_with_newline.drl
@@ -4,9 +4,18 @@ rule simple_rule
Foo()
Bar()
eval(
- abc("foo")
- + 5
- )
+
+
+
+ abc(
+
+ "foo") +
+ 5
+
+
+
+
+ )
then
Kapow
Poof
|
db57f0af3a110ed418bb0177cbc46ed4c7672c82
|
camel
|
Removed the printStackTrace line in the- CxfWsdlFirstTest--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@665997 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
index cd21176baabe0..0503dcbe21d31 100644
--- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
+++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfWsdlFirstTest.java
@@ -94,7 +94,6 @@ public void testInvokingServiceFromCXFClient() throws Exception {
fail("We expect to get the UnknowPersonFault here");
} catch (UnknownPersonFault fault) {
// We expect to get fault here
- fault.printStackTrace();
}
}
|
5c575c099f69e87b7bbd605f492022912096f3cf
|
restlet-framework-java
|
- Minor refactoring in RDF extension.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/eclipse/dictionary.xml b/build/tmpl/eclipse/dictionary.xml
index 615e887786..f730420228 100644
--- a/build/tmpl/eclipse/dictionary.xml
+++ b/build/tmpl/eclipse/dictionary.xml
@@ -56,3 +56,5 @@ laufer
evolvability
introspecting
deprecated
+datatype
+namespaces
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Literal.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Literal.java
index 35eb60a570..d52906b36b 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Literal.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/Literal.java
@@ -27,7 +27,7 @@
*
* Restlet is a registered trademark of Noelios Technologies.
*/
-
+
package org.restlet.ext.rdf;
import org.restlet.data.Language;
@@ -38,7 +38,8 @@
* reference and language properties.
*
* @author Jerome Louvel
- * @see <a href="http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal">RDF literals</a>
+ * @see <a href="http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal">RDF
+ * literals</a>
*/
public class Literal {
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfN3Representation.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfN3Representation.java
index 1b42db5121..e7d6b6beb1 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfN3Representation.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfN3Representation.java
@@ -45,35 +45,35 @@
*/
public class RdfN3Representation extends RdfRepresentation {
- /**
- * Constructor.
- *
- * @param linkSet
- * The given graph of links.
- */
- public RdfN3Representation(Graph linkSet) {
- super(linkSet);
- }
+ /**
+ * Constructor.
+ *
+ * @param linkSet
+ * The given graph of links.
+ */
+ public RdfN3Representation(Graph linkSet) {
+ super(linkSet);
+ }
- /**
- * Constructor. Parses the given representation into the given graph.
- *
- * @param rdfRepresentation
- * The RDF N3 representation to parse.
- * @param linkSet
- * The graph to update.
- * @throws IOException
- */
- public RdfN3Representation(Representation rdfRepresentation, Graph linkSet)
- throws IOException {
- super(linkSet);
- new RdfN3ParsingContentHandler(linkSet, rdfRepresentation);
- }
+ /**
+ * Constructor. Parses the given representation into the given graph.
+ *
+ * @param rdfRepresentation
+ * The RDF N3 representation to parse.
+ * @param linkSet
+ * The graph to update.
+ * @throws IOException
+ */
+ public RdfN3Representation(Representation rdfRepresentation, Graph linkSet)
+ throws IOException {
+ super(linkSet);
+ new RdfN3ParsingContentHandler(linkSet, rdfRepresentation);
+ }
- @Override
- public void write(OutputStream outputStream) throws IOException {
- if (getGraph() != null) {
- new RdfN3WritingContentHandler(getGraph(), outputStream);
- }
- }
+ @Override
+ public void write(OutputStream outputStream) throws IOException {
+ if (getGraph() != null) {
+ new RdfN3WritingContentHandler(getGraph(), outputStream);
+ }
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfRepresentation.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfRepresentation.java
index 2fd7a5841d..dcab4f14ec 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfRepresentation.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfRepresentation.java
@@ -45,71 +45,71 @@
*/
public abstract class RdfRepresentation extends OutputRepresentation {
- /** The inner graph of links. */
- private Graph graph;
+ /** The inner graph of links. */
+ private Graph graph;
- /**
- * Constructor with argument.
- *
- * @param linkSet
- * The graph of link.
- */
- public RdfRepresentation(Graph linkSet) {
- super(null);
- this.graph = linkSet;
- }
+ /**
+ * Constructor with argument.
+ *
+ * @param linkSet
+ * The graph of link.
+ */
+ public RdfRepresentation(Graph linkSet) {
+ super(null);
+ this.graph = linkSet;
+ }
- /**
- * Constructor that parsed a given RDF representation into a link set.
- *
- * @param rdfRepresentation
- * The RDF representation to parse.
- * @param linkSet
- * The link set to update.
- * @throws IOException
- */
- public RdfRepresentation(Representation rdfRepresentation, Graph linkSet)
- throws IOException {
- this(linkSet);
- if (MediaType.TEXT_RDF_N3.equals(rdfRepresentation.getMediaType())) {
- new RdfN3Representation(rdfRepresentation, linkSet);
- } else if (MediaType.TEXT_XML.equals(rdfRepresentation.getMediaType())) {
- new RdfXmlRepresentation(rdfRepresentation, linkSet);
- } else if (MediaType.APPLICATION_ALL_XML.includes(rdfRepresentation
- .getMediaType())) {
- new RdfXmlRepresentation(rdfRepresentation, linkSet);
- }
- // Parsing for other media types goes here.
- }
+ /**
+ * Constructor that parsed a given RDF representation into a link set.
+ *
+ * @param rdfRepresentation
+ * The RDF representation to parse.
+ * @param linkSet
+ * The link set to update.
+ * @throws IOException
+ */
+ public RdfRepresentation(Representation rdfRepresentation, Graph linkSet)
+ throws IOException {
+ this(linkSet);
+ if (MediaType.TEXT_RDF_N3.equals(rdfRepresentation.getMediaType())) {
+ new RdfN3Representation(rdfRepresentation, linkSet);
+ } else if (MediaType.TEXT_XML.equals(rdfRepresentation.getMediaType())) {
+ new RdfXmlRepresentation(rdfRepresentation, linkSet);
+ } else if (MediaType.APPLICATION_ALL_XML.includes(rdfRepresentation
+ .getMediaType())) {
+ new RdfXmlRepresentation(rdfRepresentation, linkSet);
+ }
+ // Parsing for other media types goes here.
+ }
- /**
- * Returns the graph of links.
- *
- * @return The graph of links.
- */
- public Graph getGraph() {
- return graph;
- }
+ /**
+ * Returns the graph of links.
+ *
+ * @return The graph of links.
+ */
+ public Graph getGraph() {
+ return graph;
+ }
- /**
- * Sets the graph of links.
- *
- * @param linkSet
- * The graph of links.
- */
- public void setGraph(Graph linkSet) {
- this.graph = linkSet;
- }
+ /**
+ * Sets the graph of links.
+ *
+ * @param linkSet
+ * The graph of links.
+ */
+ public void setGraph(Graph linkSet) {
+ this.graph = linkSet;
+ }
- @Override
- public void write(OutputStream outputStream) throws IOException {
- if (MediaType.TEXT_RDF_N3.equals(getMediaType())) {
- new RdfN3Representation(getGraph()).write(outputStream);
- } else if (MediaType.TEXT_XML.equals(getMediaType())) {
- new RdfXmlRepresentation(getGraph()).write(outputStream);
- } else if (MediaType.APPLICATION_ALL_XML.includes(getMediaType())) {
- new RdfXmlRepresentation(getGraph()).write(outputStream);
- }
- // Writing for other media types goes here.
- }
+ @Override
+ public void write(OutputStream outputStream) throws IOException {
+ if (MediaType.TEXT_RDF_N3.equals(getMediaType())) {
+ new RdfN3Representation(getGraph()).write(outputStream);
+ } else if (MediaType.TEXT_XML.equals(getMediaType())) {
+ new RdfXmlRepresentation(getGraph()).write(outputStream);
+ } else if (MediaType.APPLICATION_ALL_XML.includes(getMediaType())) {
+ new RdfXmlRepresentation(getGraph()).write(outputStream);
+ }
+ // Writing for other media types goes here.
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfXmlRepresentation.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfXmlRepresentation.java
index da509570dc..0f9ee75e3b 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfXmlRepresentation.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/RdfXmlRepresentation.java
@@ -45,35 +45,35 @@
*/
public class RdfXmlRepresentation extends RdfRepresentation {
- /**
- * Constructor.
- *
- * @param linkSet
- * The given graph of links.
- */
- public RdfXmlRepresentation(Graph linkSet) {
- super(linkSet);
- }
+ /**
+ * Constructor.
+ *
+ * @param linkSet
+ * The given graph of links.
+ */
+ public RdfXmlRepresentation(Graph linkSet) {
+ super(linkSet);
+ }
- /**
- * Constructor. Parses the given representation into the given graph.
- *
- * @param rdfRepresentation
- * The RDF N3 representation to parse.
- * @param linkSet
- * The graph to update.
- * @throws IOException
- */
- public RdfXmlRepresentation(Representation rdfRepresentation, Graph linkSet)
- throws IOException {
- super(linkSet);
- new RdfXmlParsingContentHandler(linkSet, rdfRepresentation);
- }
+ /**
+ * Constructor. Parses the given representation into the given graph.
+ *
+ * @param rdfRepresentation
+ * The RDF N3 representation to parse.
+ * @param linkSet
+ * The graph to update.
+ * @throws IOException
+ */
+ public RdfXmlRepresentation(Representation rdfRepresentation, Graph linkSet)
+ throws IOException {
+ super(linkSet);
+ new RdfXmlParsingContentHandler(linkSet, rdfRepresentation);
+ }
- @Override
- public void write(OutputStream outputStream) throws IOException {
- if (getGraph() != null) {
- new RdfXmlWritingContentHandler(getGraph(), outputStream);
- }
- }
+ @Override
+ public void write(OutputStream outputStream) throws IOException {
+ if (getGraph() != null) {
+ new RdfXmlWritingContentHandler(getGraph(), outputStream);
+ }
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfConstants.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfConstants.java
index 724a89436f..0ea71f7fcc 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfConstants.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/RdfConstants.java
@@ -1,3 +1,33 @@
+/**
+ * Copyright 2005-2009 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
package org.restlet.ext.rdf.internal;
import org.restlet.data.Reference;
@@ -5,67 +35,68 @@
/**
* Constants related to RDF documents.
*
+ * @author Thierry Boileau
*/
public class RdfConstants {
- /** List "first". */
- public static final Reference LIST_FIRST = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
-
- /** List "rest". */
- public static final Reference LIST_REST = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
-
- /** Object "nil". */
- public static final Reference OBJECT_NIL = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
-
- /** Predicate "implies" . */
- public static final Reference PREDICATE_IMPLIES = new Reference(
- "http://www.w3.org/2000/10/swap/log#implies");
-
- /** Predicate "object". */
- public static final Reference PREDICATE_OBJECT = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#object");
-
- /** Predicate "predicate". */
- public static final Reference PREDICATE_PREDICATE = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate");
-
- /** Predicate "same as". */
- public static final Reference PREDICATE_SAME = new Reference(
- "http://www.w3.org/2002/07/owl#sameAs");
-
- /** Predicate "statement". */
- public static final Reference PREDICATE_STATEMENT = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement");
-
- /** Predicate "subject". */
- public static final Reference PREDICATE_SUBJECT = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject");
-
- /** Predicate "is a". */
- public static final Reference PREDICATE_TYPE = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
-
- /** Rdf schema. */
- public static final Reference RDF_SCHEMA = new Reference(
- "http://www.w3.org/2000/01/rdf-schema#");
-
- /** Rdf syntax. */
- public static final Reference RDF_SYNTAX = new Reference(
- "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
-
- /** XML schema. */
- public static final Reference XML_SCHEMA = new Reference(
- "http://www.w3.org/2001/XMLSchema#");
-
- /** Float type of the XML schema. */
- public static final Reference XML_SCHEMA_TYPE_FLOAT = new Reference(
- "http://www.w3.org/2001/XMLSchema#float");
-
- /** Integer type of the XML schema. */
- public static final Reference XML_SCHEMA_TYPE_INTEGER = new Reference(
- "http://www.w3.org/2001/XMLSchema#int");
+ /** List "first". */
+ public static final Reference LIST_FIRST = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#first");
+
+ /** List "rest". */
+ public static final Reference LIST_REST = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest");
+
+ /** Object "nil". */
+ public static final Reference OBJECT_NIL = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
+
+ /** Predicate "implies" . */
+ public static final Reference PREDICATE_IMPLIES = new Reference(
+ "http://www.w3.org/2000/10/swap/log#implies");
+
+ /** Predicate "object". */
+ public static final Reference PREDICATE_OBJECT = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#object");
+
+ /** Predicate "predicate". */
+ public static final Reference PREDICATE_PREDICATE = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate");
+
+ /** Predicate "same as". */
+ public static final Reference PREDICATE_SAME = new Reference(
+ "http://www.w3.org/2002/07/owl#sameAs");
+
+ /** Predicate "statement". */
+ public static final Reference PREDICATE_STATEMENT = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement");
+
+ /** Predicate "subject". */
+ public static final Reference PREDICATE_SUBJECT = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#subject");
+
+ /** Predicate "is a". */
+ public static final Reference PREDICATE_TYPE = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
+
+ /** Rdf schema. */
+ public static final Reference RDF_SCHEMA = new Reference(
+ "http://www.w3.org/2000/01/rdf-schema#");
+
+ /** Rdf syntax. */
+ public static final Reference RDF_SYNTAX = new Reference(
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
+
+ /** XML schema. */
+ public static final Reference XML_SCHEMA = new Reference(
+ "http://www.w3.org/2001/XMLSchema#");
+
+ /** Float type of the XML schema. */
+ public static final Reference XML_SCHEMA_TYPE_FLOAT = new Reference(
+ "http://www.w3.org/2001/XMLSchema#float");
+
+ /** Integer type of the XML schema. */
+ public static final Reference XML_SCHEMA_TYPE_INTEGER = new Reference(
+ "http://www.w3.org/2001/XMLSchema#int");
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/BlankNodeToken.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/BlankNodeToken.java
index 1ef91baf1a..046105b543 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/BlankNodeToken.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/BlankNodeToken.java
@@ -40,11 +40,13 @@
/**
* Represents a blank node inside a RDF N3 document. Contains all the logic to
* parse a blank node in N3 documents.
+ *
+ * @author Thierry Boileau
*/
public class BlankNodeToken extends LexicalUnit {
/** List of lexical units contained by this blank node. */
- List<LexicalUnit> lexicalUnits;
+ private List<LexicalUnit> lexicalUnits;
/** Indicates if the given blank node has been already resolved. */
private boolean resolved = false;
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Context.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Context.java
index ffb3bfbd57..ae5917f65f 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Context.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Context.java
@@ -40,8 +40,11 @@
/**
* Contains essentials data updated during the parsing of a N3 document such as
* the list of known namespaces, keywords.
+ *
+ * @author Thierry Boileau
*/
public class Context {
+
/** The value of the "base" keyword. */
private Reference base;
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/FormulaToken.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/FormulaToken.java
index a0714de147..af049ed7ce 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/FormulaToken.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/FormulaToken.java
@@ -35,6 +35,8 @@
/**
* Allows to parse a formula in RDF N3 notation. Please note that this kind of
* feature is not supported yet.
+ *
+ * @author Thierry Boileau
*/
public class FormulaToken extends LexicalUnit {
@@ -44,8 +46,8 @@ public Object resolve() {
return null;
}
- public FormulaToken(RdfN3ParsingContentHandler contentHandler, Context context)
- throws IOException {
+ public FormulaToken(RdfN3ParsingContentHandler contentHandler,
+ Context context) throws IOException {
super(contentHandler, context);
this.parse();
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/LexicalUnit.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/LexicalUnit.java
index e1dfda2bba..502194b936 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/LexicalUnit.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/LexicalUnit.java
@@ -34,6 +34,8 @@
/**
* Represents a lexical unit inside a N3 document.
+ *
+ * @author Thierry Boileau
*/
public abstract class LexicalUnit {
@@ -54,7 +56,8 @@ public abstract class LexicalUnit {
* @param context
* The parsing context.
*/
- public LexicalUnit(RdfN3ParsingContentHandler contentHandler, Context context) {
+ public LexicalUnit(RdfN3ParsingContentHandler contentHandler,
+ Context context) {
super();
this.contentHandler = contentHandler;
this.context = context;
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/ListToken.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/ListToken.java
index 2f18fdce8c..a5db88e399 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/ListToken.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/ListToken.java
@@ -38,113 +38,115 @@
import org.restlet.ext.rdf.internal.RdfConstants;
/**
- * Represens a list of N3 tokens.
+ * Represents a list of N3 tokens.
+ *
+ * @author Thierry Boileau
*/
class ListToken extends LexicalUnit {
- /** The list of contained tokens. */
- List<LexicalUnit> lexicalUnits;
+ /** The list of contained tokens. */
+ List<LexicalUnit> lexicalUnits;
- /**
- * Constructor with arguments.
- *
- * @param contentHandler
- * The document's parent handler.
- * @param context
- * The parsing context.
- */
- public ListToken(RdfN3ParsingContentHandler contentHandler, Context context)
- throws IOException {
- super(contentHandler, context);
- lexicalUnits = new ArrayList<LexicalUnit>();
- this.parse();
- }
+ /**
+ * Constructor with arguments.
+ *
+ * @param contentHandler
+ * The document's parent handler.
+ * @param context
+ * The parsing context.
+ */
+ public ListToken(RdfN3ParsingContentHandler contentHandler, Context context)
+ throws IOException {
+ super(contentHandler, context);
+ lexicalUnits = new ArrayList<LexicalUnit>();
+ this.parse();
+ }
- @Override
- public Object resolve() {
- Reference currentBlankNode = (Reference) new BlankNodeToken(
- RdfN3ParsingContentHandler.newBlankNodeId()).resolve();
- for (LexicalUnit lexicalUnit : lexicalUnits) {
- Object element = lexicalUnit.resolve();
+ @Override
+ public Object resolve() {
+ Reference currentBlankNode = (Reference) new BlankNodeToken(
+ RdfN3ParsingContentHandler.newBlankNodeId()).resolve();
+ for (LexicalUnit lexicalUnit : lexicalUnits) {
+ Object element = lexicalUnit.resolve();
- if (element instanceof Reference) {
- getContentHandler().link(currentBlankNode,
- RdfConstants.LIST_FIRST, (Reference) element);
- } else if (element instanceof String) {
- getContentHandler().link(currentBlankNode,
- RdfConstants.LIST_FIRST,
- new Reference((String) element));
- } else {
- // TODO Error.
- }
+ if (element instanceof Reference) {
+ getContentHandler().link(currentBlankNode,
+ RdfConstants.LIST_FIRST, (Reference) element);
+ } else if (element instanceof String) {
+ getContentHandler().link(currentBlankNode,
+ RdfConstants.LIST_FIRST,
+ new Reference((String) element));
+ } else {
+ // TODO Error.
+ }
- Reference restBlankNode = (Reference) new BlankNodeToken(
- RdfN3ParsingContentHandler.newBlankNodeId()).resolve();
+ Reference restBlankNode = (Reference) new BlankNodeToken(
+ RdfN3ParsingContentHandler.newBlankNodeId()).resolve();
- getContentHandler().link(currentBlankNode, RdfConstants.LIST_REST,
- restBlankNode);
- currentBlankNode = restBlankNode;
- }
- getContentHandler().link(currentBlankNode, RdfConstants.LIST_REST,
- RdfConstants.OBJECT_NIL);
+ getContentHandler().link(currentBlankNode, RdfConstants.LIST_REST,
+ restBlankNode);
+ currentBlankNode = restBlankNode;
+ }
+ getContentHandler().link(currentBlankNode, RdfConstants.LIST_REST,
+ RdfConstants.OBJECT_NIL);
- return currentBlankNode;
- }
+ return currentBlankNode;
+ }
- @Override
- public String getValue() {
- return lexicalUnits.toString();
- }
+ @Override
+ public String getValue() {
+ return lexicalUnits.toString();
+ }
- @Override
- public void parse() throws IOException {
- getContentHandler().step();
- do {
- getContentHandler().consumeWhiteSpaces();
- switch (getContentHandler().getChar()) {
- case '(':
- lexicalUnits.add(new ListToken(getContentHandler(),
- getContext()));
- break;
- case '<':
- if (getContentHandler().step() == '=') {
- lexicalUnits.add(new Token("<="));
- getContentHandler().step();
- getContentHandler().discard();
- } else {
- getContentHandler().stepBack();
- lexicalUnits.add(new UriToken(getContentHandler(),
- getContext()));
- }
- break;
- case '_':
- lexicalUnits.add(new BlankNodeToken(getContentHandler()
- .parseToken()));
- break;
- case '"':
- lexicalUnits.add(new StringToken(getContentHandler(),
- getContext()));
- break;
- case '[':
- lexicalUnits.add(new BlankNodeToken(getContentHandler(),
- getContext()));
- break;
- case '{':
- lexicalUnits.add(new FormulaToken(getContentHandler(),
- getContext()));
- break;
- case ')':
- break;
- case RdfN3ParsingContentHandler.EOF:
- break;
- default:
- lexicalUnits.add(new Token(getContentHandler(), getContext()));
- break;
- }
- } while (getContentHandler().getChar() != RdfN3ParsingContentHandler.EOF
- && getContentHandler().getChar() != ')');
- if (getContentHandler().getChar() == ')') {
- // Set the cursor at the right of the list token.
- getContentHandler().step();
- }
- }
+ @Override
+ public void parse() throws IOException {
+ getContentHandler().step();
+ do {
+ getContentHandler().consumeWhiteSpaces();
+ switch (getContentHandler().getChar()) {
+ case '(':
+ lexicalUnits.add(new ListToken(getContentHandler(),
+ getContext()));
+ break;
+ case '<':
+ if (getContentHandler().step() == '=') {
+ lexicalUnits.add(new Token("<="));
+ getContentHandler().step();
+ getContentHandler().discard();
+ } else {
+ getContentHandler().stepBack();
+ lexicalUnits.add(new UriToken(getContentHandler(),
+ getContext()));
+ }
+ break;
+ case '_':
+ lexicalUnits.add(new BlankNodeToken(getContentHandler()
+ .parseToken()));
+ break;
+ case '"':
+ lexicalUnits.add(new StringToken(getContentHandler(),
+ getContext()));
+ break;
+ case '[':
+ lexicalUnits.add(new BlankNodeToken(getContentHandler(),
+ getContext()));
+ break;
+ case '{':
+ lexicalUnits.add(new FormulaToken(getContentHandler(),
+ getContext()));
+ break;
+ case ')':
+ break;
+ case RdfN3ParsingContentHandler.EOF:
+ break;
+ default:
+ lexicalUnits.add(new Token(getContentHandler(), getContext()));
+ break;
+ }
+ } while (getContentHandler().getChar() != RdfN3ParsingContentHandler.EOF
+ && getContentHandler().getChar() != ')');
+ if (getContentHandler().getChar() == ')') {
+ // Set the cursor at the right of the list token.
+ getContentHandler().step();
+ }
+ }
}
\ No newline at end of file
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3ParsingContentHandler.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3ParsingContentHandler.java
index b3eec7b869..197c9e838c 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3ParsingContentHandler.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3ParsingContentHandler.java
@@ -46,659 +46,662 @@
/**
* Handler of RDF content according to the N3 notation.
+ *
+ * @author Thierry Boileau
*/
public class RdfN3ParsingContentHandler extends GraphHandler {
- /** Increment used to identify inner blank nodes. */
- private static int blankNodeId = 0;
-
- /** Size of the reading buffer. */
- private static final int BUFFER_SIZE = 4096;
-
- /** End of reading buffer marker. */
- public static final int EOF = 0;
-
- /**
- * Returns true if the given character is alphanumeric.
- *
- * @param c
- * The given character to check.
- * @return true if the given character is alphanumeric.
- */
- public static boolean isAlphaNum(int c) {
- return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
- || (c >= '0' && c <= '9');
- }
-
- /**
- * Returns true if the given character is a delimiter.
- *
- * @param c
- * The given character to check.
- * @return true if the given character is a delimiter.
- */
- public static boolean isDelimiter(int c) {
- return isWhiteSpace(c) || c == '^' || c == '!' || c == '=' || c == '<'
- || c == '"' || c == '{' || c == '}' || c == '[' || c == ']'
- || c == '(' || c == ')' || c == '.' || c == ';' || c == ','
- || c == '@';
- }
-
- /**
- * Returns true if the given character is a whitespace.
- *
- * @param c
- * The given character to check.
- * @return true if the given character is a whitespace.
- */
- public static boolean isWhiteSpace(int c) {
- return c == ' ' || c == '\n' || c == '\r' || c == '\t';
- }
-
- /**
- * Returns the identifier of a new blank node.
- *
- * @return The identifier of a new blank node.
- */
- public static String newBlankNodeId() {
- return "#_bn" + blankNodeId++;
- }
-
- /** Internal buffered reader. */
- private BufferedReader br;
-
- /** The reading buffer. */
- private final char[] buffer;
-
- /** The current context object. */
- private Context context;
-
- /** The set of links to update when parsing. */
- private Graph linkSet;
-
- /** The representation to read. */
- private Representation rdfN3Representation;
-
- /**
- * Index that discovers the end of the current token and the beginning of
- * the futur one.
- */
- private int scoutIndex;
-
- /** Start index of current lexical unit. */
- private int startTokenIndex;
-
- /**
- * Constructor.
- *
- * @param linkSet
- * The set of links to update during the parsing.
- * @param rdfN3Representation
- * The representation to read.
- * @throws IOException
- */
- public RdfN3ParsingContentHandler(Graph linkSet,
- Representation rdfN3Representation) throws IOException {
- super();
- this.linkSet = linkSet;
- this.rdfN3Representation = rdfN3Representation;
-
- // Initialize the buffer in two parts
- this.buffer = new char[(RdfN3ParsingContentHandler.BUFFER_SIZE + 1) * 2];
- // Mark the upper index of each part.
- this.buffer[RdfN3ParsingContentHandler.BUFFER_SIZE] = this.buffer[2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1] = EOF;
- this.scoutIndex = 2 * RdfN3ParsingContentHandler.BUFFER_SIZE;
- this.startTokenIndex = 0;
-
- this.br = new BufferedReader(new InputStreamReader(
- this.rdfN3Representation.getStream()));
- this.context = new Context();
- context.getKeywords().addAll(
- Arrays.asList("a", "is", "of", "this", "has"));
- parse();
- }
-
- /**
- * Discard all read characters until the end of the statement is reached
- * (marked by a '.').
- *
- * @throws IOException
- */
- public void consumeStatement() throws IOException {
- int c = getChar();
- while (c != RdfN3ParsingContentHandler.EOF && c != '.') {
- c = step();
- }
- if (getChar() == '.') {
- // A further step at the right of the statement.
- step();
- }
- discard();
- }
-
- /**
- * Discard all read characters. A call to {@link getCurrentToken} will
- * return a single character.
- *
- * @throws IOException
- */
- public void consumeWhiteSpaces() throws IOException {
- while (RdfN3ParsingContentHandler.isWhiteSpace(getChar())) {
- step();
- }
- discard();
- }
-
- /**
- * Discard all read characters. A call to {@link getCurrentToken} will
- * return a single character.
- */
- public void discard() {
- startTokenIndex = scoutIndex;
- }
-
- /**
- * Loops over the given list of lexical units and generates the adequat
- * calls to link* methods.
- *
- * @see GraphHandler#link(Graph, Reference, Reference)
- * @see GraphHandler#link(Reference, Reference, Literal)
- * @see GraphHandler#link(Reference, Reference, Reference)
- * @param lexicalUnits
- * The list of lexical units used to generate the links.
- */
- public void generateLinks(List<LexicalUnit> lexicalUnits) {
- Object currentSubject = null;
- Reference currentPredicate = null;
- Object currentObject = null;
- int nbTokens = 0;
- boolean swapSubjectObject = false;
- for (int i = 0; i < lexicalUnits.size(); i++) {
- LexicalUnit lexicalUnit = lexicalUnits.get(i);
-
- nbTokens++;
- switch (nbTokens) {
- case 1:
- if (",".equals(lexicalUnit.getValue())) {
- nbTokens++;
- } else if (!";".equals(lexicalUnit.getValue())) {
- currentSubject = lexicalUnit.resolve();
- }
- break;
- case 2:
- if ("is".equalsIgnoreCase(lexicalUnit.getValue())) {
- nbTokens--;
- swapSubjectObject = true;
- } else if ("has".equalsIgnoreCase(lexicalUnit.getValue())) {
- nbTokens--;
- } else if ("=".equalsIgnoreCase(lexicalUnit.getValue())) {
- currentPredicate = RdfConstants.PREDICATE_SAME;
- } else if ("=>".equalsIgnoreCase(lexicalUnit.getValue())) {
- currentPredicate = RdfConstants.PREDICATE_IMPLIES;
- } else if ("<=".equalsIgnoreCase(lexicalUnit.getValue())) {
- swapSubjectObject = true;
- currentPredicate = RdfConstants.PREDICATE_IMPLIES;
- } else if ("a".equalsIgnoreCase(lexicalUnit.getValue())) {
- currentPredicate = RdfConstants.PREDICATE_TYPE;
- } else if ("!".equalsIgnoreCase(lexicalUnit.getValue())) {
- currentObject = new BlankNodeToken(
- RdfN3ParsingContentHandler.newBlankNodeId())
- .resolve();
- currentPredicate = getPredicate(lexicalUnits.get(++i));
- this.link(currentSubject, currentPredicate, currentObject);
- currentSubject = currentObject;
- nbTokens = 1;
- } else if ("^".equalsIgnoreCase(lexicalUnit.getValue())) {
- currentObject = currentSubject;
- currentPredicate = getPredicate(lexicalUnits.get(++i));
- currentSubject = new BlankNodeToken(
- RdfN3ParsingContentHandler.newBlankNodeId())
- .resolve();
- this.link(currentSubject, currentPredicate, currentObject);
- nbTokens = 1;
- } else {
- currentPredicate = getPredicate(lexicalUnit);
- }
- break;
- case 3:
- if ("of".equalsIgnoreCase(lexicalUnit.getValue())) {
- nbTokens--;
- } else {
- if (swapSubjectObject) {
- currentObject = currentSubject;
- currentSubject = lexicalUnit.resolve();
- } else {
- currentObject = lexicalUnit.resolve();
- }
- this.link(currentSubject, currentPredicate, currentObject);
- nbTokens = 0;
- swapSubjectObject = false;
- }
- break;
- default:
- break;
- }
- }
- }
-
- /**
- * Returns the current parsed character.
- *
- * @return The current parsed character.
- */
- public char getChar() {
- return (char) buffer[scoutIndex];
- }
-
- /**
- * Returns the current token.
- *
- * @return The current token.
- */
- public String getCurrentToken() {
- StringBuilder builder = new StringBuilder();
- if (startTokenIndex <= scoutIndex) {
- if (scoutIndex <= RdfN3ParsingContentHandler.BUFFER_SIZE) {
- for (int i = startTokenIndex; i < scoutIndex; i++) {
- builder.append((char) buffer[i]);
- }
- } else {
- for (int i = startTokenIndex; i < RdfN3ParsingContentHandler.BUFFER_SIZE; i++) {
- builder.append((char) buffer[i]);
- }
- for (int i = RdfN3ParsingContentHandler.BUFFER_SIZE + 1; i < scoutIndex; i++) {
- builder.append((char) buffer[i]);
- }
- }
- } else {
- if (startTokenIndex <= RdfN3ParsingContentHandler.BUFFER_SIZE) {
- for (int i = startTokenIndex; i < RdfN3ParsingContentHandler.BUFFER_SIZE; i++) {
- builder.append((char) buffer[i]);
- }
- for (int i = RdfN3ParsingContentHandler.BUFFER_SIZE + 1; i < (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1); i++) {
- builder.append((char) buffer[i]);
- }
- for (int i = 0; i < scoutIndex; i++) {
- builder.append((char) buffer[i]);
- }
- } else {
- for (int i = startTokenIndex; i < (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1); i++) {
- builder.append((char) buffer[i]);
- }
- for (int i = 0; i < scoutIndex; i++) {
- builder.append((char) buffer[i]);
- }
- }
- }
- // the current token is consumed.
- startTokenIndex = scoutIndex;
- return builder.toString();
- }
-
- /**
- * Returns the given lexical unit as a predicate.
- *
- * @param lexicalUnit
- * The lexical unit to get as a predicate.
- * @return A RDF URI reference of the predicate.
- */
- private Reference getPredicate(LexicalUnit lexicalUnit) {
- Reference result = null;
- Object p = lexicalUnit.resolve();
- if (p instanceof Reference) {
- result = (Reference) p;
- } else if (p instanceof String) {
- result = new Reference((String) p);
- }
-
- return result;
- }
-
- @Override
- public void link(Graph source, Reference typeRef, Literal target) {
- this.linkSet.add(source, typeRef, target);
- }
-
- @Override
- public void link(Graph source, Reference typeRef, Reference target) {
- this.linkSet.add(source, typeRef, target);
- }
-
- /**
- * Callback method used when a link is parsed or written.
- *
- * @param source
- * The source or subject of the link.
- * @param typeRef
- * The type reference of the link.
- * @param target
- * The target or object of the link.
- */
- private void link(Object source, Reference typeRef, Object target) {
- if (source instanceof Reference) {
- if (target instanceof Reference) {
- link((Reference) source, typeRef, (Reference) target);
- } else if (target instanceof Literal) {
- link((Reference) source, typeRef, (Literal) target);
- } else {
- // Error?
- }
- } else if (source instanceof Graph) {
- if (target instanceof Reference) {
- link((Graph) source, typeRef, (Reference) target);
- } else if (target instanceof Literal) {
- link((Graph) source, typeRef, (Literal) target);
- } else {
- // Error?
- }
- }
- }
-
- @Override
- public void link(Reference source, Reference typeRef, Literal target) {
- this.linkSet.add(source, typeRef, target);
- }
-
- @Override
- public void link(Reference source, Reference typeRef, Reference target) {
- this.linkSet.add(source, typeRef, target);
- }
-
- /**
- * Parses the current representation.
- *
- * @throws IOException
- */
- private void parse() throws IOException {
- // Init the reading.
- step();
- do {
- consumeWhiteSpaces();
- switch (getChar()) {
- case '@':
- parseDirective(this.context);
- break;
- case '#':
- parseComment();
- break;
- case '.':
- step();
- break;
- default:
- parseStatement(this.context);
- break;
- }
- } while (getChar() != RdfN3ParsingContentHandler.EOF);
-
- }
-
- /**
- * Parses a comment.
- *
- * @throws IOException
- */
- public void parseComment() throws IOException {
- int c;
- do {
- c = step();
- } while (c != RdfN3ParsingContentHandler.EOF && c != '\n' && c != '\r');
- discard();
- }
-
- /**
- * Parse the current directive and update the context according to the kind
- * of directive ("base", "prefix", etc).
- *
- * @param context
- * The context to update.
- * @throws IOException
- */
- public void parseDirective(Context context) throws IOException {
- // Remove the leading '@' character.
- step();
- discard();
- String currentKeyword = parseToken();
- if ("base".equalsIgnoreCase(currentKeyword)) {
- consumeWhiteSpaces();
- String base = parseUri();
- Reference ref = new Reference(base);
- if (ref.isRelative()) {
- context.getBase().addSegment(base);
- } else {
- context.setBase(ref);
- }
- consumeStatement();
- } else if ("prefix".equalsIgnoreCase(currentKeyword)) {
- consumeWhiteSpaces();
- String prefix = parseToken();
- consumeWhiteSpaces();
- String uri = parseUri();
- context.getPrefixes().put(prefix, uri);
- consumeStatement();
- } else if ("keywords".equalsIgnoreCase(currentKeyword)) {
- consumeWhiteSpaces();
- int c;
- do {
- c = step();
- } while (c != RdfN3ParsingContentHandler.EOF && c != '.');
- String strKeywords = getCurrentToken();
- String[] keywords = strKeywords.split(",");
- context.getKeywords().clear();
- for (String keyword : keywords) {
- context.getKeywords().add(keyword.trim());
- }
- consumeStatement();
- } else {
- // TODO @ForAll and @ForSome are not supported yet.
- consumeStatement();
- }
- }
-
- /**
- * Reads the current statement until its end, and parses it.
- *
- * @param context
- * The current context.
- * @throws IOException
- */
- public void parseStatement(Context context) throws IOException {
- List<LexicalUnit> lexicalUnits = new ArrayList<LexicalUnit>();
- do {
- consumeWhiteSpaces();
- switch (getChar()) {
- case '(':
- lexicalUnits.add(new ListToken(this, context));
- break;
- case '<':
- if (step() == '=') {
- lexicalUnits.add(new Token("<="));
- step();
- discard();
- } else {
- stepBack();
- lexicalUnits.add(new UriToken(this, context));
- }
- break;
- case '_':
- lexicalUnits.add(new BlankNodeToken(parseToken()));
- break;
- case '"':
- lexicalUnits.add(new StringToken(this, context));
- break;
- case '[':
- lexicalUnits.add(new BlankNodeToken(this, context));
- break;
- case '!':
- lexicalUnits.add(new Token("!"));
- step();
- discard();
- break;
- case '^':
- lexicalUnits.add(new Token("^"));
- step();
- discard();
- break;
- case '=':
- if (step() == '>') {
- lexicalUnits.add(new Token("=>"));
- step();
- discard();
- } else {
- lexicalUnits.add(new Token("="));
- discard();
- }
- break;
- case '@':
- // Remove the leading '@' character.
- step();
- discard();
- lexicalUnits.add(new Token(this, context));
- discard();
- break;
- case ';':
- // TODO
- step();
- discard();
- lexicalUnits.add(new Token(";"));
- break;
- case ',':
- // TODO
- step();
- discard();
- lexicalUnits.add(new Token(","));
- break;
- case '{':
- lexicalUnits.add(new FormulaToken(this, context));
- break;
- case '.':
- break;
- case RdfN3ParsingContentHandler.EOF:
- break;
- default:
- lexicalUnits.add(new Token(this, context));
- break;
- }
- } while (getChar() != RdfN3ParsingContentHandler.EOF
- && getChar() != '.' && getChar() != '}');
-
- // Generate the links
- generateLinks(lexicalUnits);
- }
-
- /**
- * Returns the value of the current token.
- *
- * @return The value of the current token.
- * @throws IOException
- */
- public String parseToken() throws IOException {
- int c;
- do {
- c = step();
- } while (c != RdfN3ParsingContentHandler.EOF && !isDelimiter(c));
- String result = getCurrentToken();
- return result;
- }
-
- /**
- * Returns the value of the current URI.
- *
- * @return The value of the current URI.
- * @throws IOException
- */
- public String parseUri() throws IOException {
- StringBuilder builder = new StringBuilder();
- // Suppose the current character is "<".
- int c = step();
- while (c != RdfN3ParsingContentHandler.EOF && c != '>') {
- if (!isWhiteSpace(c)) {
- // Discard white spaces.
- builder.append((char) c);
- }
- c = step();
- }
- if (c == '>') {
- // Set the cursor at the right of the uri.
- step();
- }
- discard();
-
- return builder.toString();
- }
-
- /**
- * Read a new character.
- *
- * @return The new read character.
- * @throws IOException
- */
- public int step() throws IOException {
- scoutIndex++;
- if (buffer[scoutIndex] == RdfN3ParsingContentHandler.EOF) {
- if (scoutIndex == RdfN3ParsingContentHandler.BUFFER_SIZE) {
- // Reached the end of the first part of the buffer, read into
- // the second one.
- scoutIndex++;
- int len = this.br.read(buffer, 0,
- RdfN3ParsingContentHandler.BUFFER_SIZE);
- if (len == -1) {
- // End of the stream reached
- buffer[scoutIndex] = RdfN3ParsingContentHandler.EOF;
- } else {
- buffer[RdfN3ParsingContentHandler.BUFFER_SIZE + len + 1] = RdfN3ParsingContentHandler.EOF;
- }
- } else if (scoutIndex == (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1)) {
- scoutIndex = 0;
- // Reached the end of the second part of the buffer, read into
- // the first one.
- int len = this.br.read(buffer, 0,
- RdfN3ParsingContentHandler.BUFFER_SIZE);
- if (len == -1) {
- // End of the stream reached
- buffer[scoutIndex] = RdfN3ParsingContentHandler.EOF;
- } else {
- buffer[len] = RdfN3ParsingContentHandler.EOF;
- }
- } else {
- // Reached the end of the stream.
- }
- }
-
- return buffer[scoutIndex];
- }
-
- /**
- * Steps forward.
- *
- * @param n
- * the number of steps to go forward.
- * @throws IOException
- */
- public void step(int n) throws IOException {
- for (int i = 0; i < n; i++) {
- step();
- }
- }
-
- /**
- * Steps back of one step.
- *
- */
- public void stepBack() {
- stepBack(1);
- }
-
- /**
- * Steps back.
- *
- * @param n
- * the number of steps to go back.
- */
- public void stepBack(int n) {
- scoutIndex -= n;
- if (scoutIndex < 0) {
- scoutIndex = RdfN3ParsingContentHandler.BUFFER_SIZE * 2 + 1
- - scoutIndex;
- }
- }
+
+ /** Increment used to identify inner blank nodes. */
+ private static int blankNodeId = 0;
+
+ /** Size of the reading buffer. */
+ private static final int BUFFER_SIZE = 4096;
+
+ /** End of reading buffer marker. */
+ public static final int EOF = 0;
+
+ /**
+ * Returns true if the given character is alphanumeric.
+ *
+ * @param c
+ * The given character to check.
+ * @return true if the given character is alphanumeric.
+ */
+ public static boolean isAlphaNum(int c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
+ || (c >= '0' && c <= '9');
+ }
+
+ /**
+ * Returns true if the given character is a delimiter.
+ *
+ * @param c
+ * The given character to check.
+ * @return true if the given character is a delimiter.
+ */
+ public static boolean isDelimiter(int c) {
+ return isWhiteSpace(c) || c == '^' || c == '!' || c == '=' || c == '<'
+ || c == '"' || c == '{' || c == '}' || c == '[' || c == ']'
+ || c == '(' || c == ')' || c == '.' || c == ';' || c == ','
+ || c == '@';
+ }
+
+ /**
+ * Returns true if the given character is a whitespace.
+ *
+ * @param c
+ * The given character to check.
+ * @return true if the given character is a whitespace.
+ */
+ public static boolean isWhiteSpace(int c) {
+ return c == ' ' || c == '\n' || c == '\r' || c == '\t';
+ }
+
+ /**
+ * Returns the identifier of a new blank node.
+ *
+ * @return The identifier of a new blank node.
+ */
+ public static String newBlankNodeId() {
+ return "#_bn" + blankNodeId++;
+ }
+
+ /** Internal buffered reader. */
+ private BufferedReader br;
+
+ /** The reading buffer. */
+ private final char[] buffer;
+
+ /** The current context object. */
+ private Context context;
+
+ /** The set of links to update when parsing. */
+ private Graph linkSet;
+
+ /** The representation to read. */
+ private Representation rdfN3Representation;
+
+ /**
+ * Index that discovers the end of the current token and the beginning of
+ * the futur one.
+ */
+ private int scoutIndex;
+
+ /** Start index of current lexical unit. */
+ private int startTokenIndex;
+
+ /**
+ * Constructor.
+ *
+ * @param linkSet
+ * The set of links to update during the parsing.
+ * @param rdfN3Representation
+ * The representation to read.
+ * @throws IOException
+ */
+ public RdfN3ParsingContentHandler(Graph linkSet,
+ Representation rdfN3Representation) throws IOException {
+ super();
+ this.linkSet = linkSet;
+ this.rdfN3Representation = rdfN3Representation;
+
+ // Initialize the buffer in two parts
+ this.buffer = new char[(RdfN3ParsingContentHandler.BUFFER_SIZE + 1) * 2];
+ // Mark the upper index of each part.
+ this.buffer[RdfN3ParsingContentHandler.BUFFER_SIZE] = this.buffer[2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1] = EOF;
+ this.scoutIndex = 2 * RdfN3ParsingContentHandler.BUFFER_SIZE;
+ this.startTokenIndex = 0;
+
+ this.br = new BufferedReader(new InputStreamReader(
+ this.rdfN3Representation.getStream()));
+ this.context = new Context();
+ context.getKeywords().addAll(
+ Arrays.asList("a", "is", "of", "this", "has"));
+ parse();
+ }
+
+ /**
+ * Discard all read characters until the end of the statement is reached
+ * (marked by a '.').
+ *
+ * @throws IOException
+ */
+ public void consumeStatement() throws IOException {
+ int c = getChar();
+ while (c != RdfN3ParsingContentHandler.EOF && c != '.') {
+ c = step();
+ }
+ if (getChar() == '.') {
+ // A further step at the right of the statement.
+ step();
+ }
+ discard();
+ }
+
+ /**
+ * Discard all read characters. A call to {@link getCurrentToken} will
+ * return a single character.
+ *
+ * @throws IOException
+ */
+ public void consumeWhiteSpaces() throws IOException {
+ while (RdfN3ParsingContentHandler.isWhiteSpace(getChar())) {
+ step();
+ }
+ discard();
+ }
+
+ /**
+ * Discard all read characters. A call to {@link getCurrentToken} will
+ * return a single character.
+ */
+ public void discard() {
+ startTokenIndex = scoutIndex;
+ }
+
+ /**
+ * Loops over the given list of lexical units and generates the adequat
+ * calls to link* methods.
+ *
+ * @see GraphHandler#link(Graph, Reference, Reference)
+ * @see GraphHandler#link(Reference, Reference, Literal)
+ * @see GraphHandler#link(Reference, Reference, Reference)
+ * @param lexicalUnits
+ * The list of lexical units used to generate the links.
+ */
+ public void generateLinks(List<LexicalUnit> lexicalUnits) {
+ Object currentSubject = null;
+ Reference currentPredicate = null;
+ Object currentObject = null;
+ int nbTokens = 0;
+ boolean swapSubjectObject = false;
+ for (int i = 0; i < lexicalUnits.size(); i++) {
+ LexicalUnit lexicalUnit = lexicalUnits.get(i);
+
+ nbTokens++;
+ switch (nbTokens) {
+ case 1:
+ if (",".equals(lexicalUnit.getValue())) {
+ nbTokens++;
+ } else if (!";".equals(lexicalUnit.getValue())) {
+ currentSubject = lexicalUnit.resolve();
+ }
+ break;
+ case 2:
+ if ("is".equalsIgnoreCase(lexicalUnit.getValue())) {
+ nbTokens--;
+ swapSubjectObject = true;
+ } else if ("has".equalsIgnoreCase(lexicalUnit.getValue())) {
+ nbTokens--;
+ } else if ("=".equalsIgnoreCase(lexicalUnit.getValue())) {
+ currentPredicate = RdfConstants.PREDICATE_SAME;
+ } else if ("=>".equalsIgnoreCase(lexicalUnit.getValue())) {
+ currentPredicate = RdfConstants.PREDICATE_IMPLIES;
+ } else if ("<=".equalsIgnoreCase(lexicalUnit.getValue())) {
+ swapSubjectObject = true;
+ currentPredicate = RdfConstants.PREDICATE_IMPLIES;
+ } else if ("a".equalsIgnoreCase(lexicalUnit.getValue())) {
+ currentPredicate = RdfConstants.PREDICATE_TYPE;
+ } else if ("!".equalsIgnoreCase(lexicalUnit.getValue())) {
+ currentObject = new BlankNodeToken(
+ RdfN3ParsingContentHandler.newBlankNodeId())
+ .resolve();
+ currentPredicate = getPredicate(lexicalUnits.get(++i));
+ this.link(currentSubject, currentPredicate, currentObject);
+ currentSubject = currentObject;
+ nbTokens = 1;
+ } else if ("^".equalsIgnoreCase(lexicalUnit.getValue())) {
+ currentObject = currentSubject;
+ currentPredicate = getPredicate(lexicalUnits.get(++i));
+ currentSubject = new BlankNodeToken(
+ RdfN3ParsingContentHandler.newBlankNodeId())
+ .resolve();
+ this.link(currentSubject, currentPredicate, currentObject);
+ nbTokens = 1;
+ } else {
+ currentPredicate = getPredicate(lexicalUnit);
+ }
+ break;
+ case 3:
+ if ("of".equalsIgnoreCase(lexicalUnit.getValue())) {
+ nbTokens--;
+ } else {
+ if (swapSubjectObject) {
+ currentObject = currentSubject;
+ currentSubject = lexicalUnit.resolve();
+ } else {
+ currentObject = lexicalUnit.resolve();
+ }
+ this.link(currentSubject, currentPredicate, currentObject);
+ nbTokens = 0;
+ swapSubjectObject = false;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ /**
+ * Returns the current parsed character.
+ *
+ * @return The current parsed character.
+ */
+ public char getChar() {
+ return (char) buffer[scoutIndex];
+ }
+
+ /**
+ * Returns the current token.
+ *
+ * @return The current token.
+ */
+ public String getCurrentToken() {
+ StringBuilder builder = new StringBuilder();
+ if (startTokenIndex <= scoutIndex) {
+ if (scoutIndex <= RdfN3ParsingContentHandler.BUFFER_SIZE) {
+ for (int i = startTokenIndex; i < scoutIndex; i++) {
+ builder.append((char) buffer[i]);
+ }
+ } else {
+ for (int i = startTokenIndex; i < RdfN3ParsingContentHandler.BUFFER_SIZE; i++) {
+ builder.append((char) buffer[i]);
+ }
+ for (int i = RdfN3ParsingContentHandler.BUFFER_SIZE + 1; i < scoutIndex; i++) {
+ builder.append((char) buffer[i]);
+ }
+ }
+ } else {
+ if (startTokenIndex <= RdfN3ParsingContentHandler.BUFFER_SIZE) {
+ for (int i = startTokenIndex; i < RdfN3ParsingContentHandler.BUFFER_SIZE; i++) {
+ builder.append((char) buffer[i]);
+ }
+ for (int i = RdfN3ParsingContentHandler.BUFFER_SIZE + 1; i < (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1); i++) {
+ builder.append((char) buffer[i]);
+ }
+ for (int i = 0; i < scoutIndex; i++) {
+ builder.append((char) buffer[i]);
+ }
+ } else {
+ for (int i = startTokenIndex; i < (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1); i++) {
+ builder.append((char) buffer[i]);
+ }
+ for (int i = 0; i < scoutIndex; i++) {
+ builder.append((char) buffer[i]);
+ }
+ }
+ }
+ // the current token is consumed.
+ startTokenIndex = scoutIndex;
+ return builder.toString();
+ }
+
+ /**
+ * Returns the given lexical unit as a predicate.
+ *
+ * @param lexicalUnit
+ * The lexical unit to get as a predicate.
+ * @return A RDF URI reference of the predicate.
+ */
+ private Reference getPredicate(LexicalUnit lexicalUnit) {
+ Reference result = null;
+ Object p = lexicalUnit.resolve();
+ if (p instanceof Reference) {
+ result = (Reference) p;
+ } else if (p instanceof String) {
+ result = new Reference((String) p);
+ }
+
+ return result;
+ }
+
+ @Override
+ public void link(Graph source, Reference typeRef, Literal target) {
+ this.linkSet.add(source, typeRef, target);
+ }
+
+ @Override
+ public void link(Graph source, Reference typeRef, Reference target) {
+ this.linkSet.add(source, typeRef, target);
+ }
+
+ /**
+ * Callback method used when a link is parsed or written.
+ *
+ * @param source
+ * The source or subject of the link.
+ * @param typeRef
+ * The type reference of the link.
+ * @param target
+ * The target or object of the link.
+ */
+ private void link(Object source, Reference typeRef, Object target) {
+ if (source instanceof Reference) {
+ if (target instanceof Reference) {
+ link((Reference) source, typeRef, (Reference) target);
+ } else if (target instanceof Literal) {
+ link((Reference) source, typeRef, (Literal) target);
+ } else {
+ // Error?
+ }
+ } else if (source instanceof Graph) {
+ if (target instanceof Reference) {
+ link((Graph) source, typeRef, (Reference) target);
+ } else if (target instanceof Literal) {
+ link((Graph) source, typeRef, (Literal) target);
+ } else {
+ // Error?
+ }
+ }
+ }
+
+ @Override
+ public void link(Reference source, Reference typeRef, Literal target) {
+ this.linkSet.add(source, typeRef, target);
+ }
+
+ @Override
+ public void link(Reference source, Reference typeRef, Reference target) {
+ this.linkSet.add(source, typeRef, target);
+ }
+
+ /**
+ * Parses the current representation.
+ *
+ * @throws IOException
+ */
+ private void parse() throws IOException {
+ // Init the reading.
+ step();
+ do {
+ consumeWhiteSpaces();
+ switch (getChar()) {
+ case '@':
+ parseDirective(this.context);
+ break;
+ case '#':
+ parseComment();
+ break;
+ case '.':
+ step();
+ break;
+ default:
+ parseStatement(this.context);
+ break;
+ }
+ } while (getChar() != RdfN3ParsingContentHandler.EOF);
+
+ }
+
+ /**
+ * Parses a comment.
+ *
+ * @throws IOException
+ */
+ public void parseComment() throws IOException {
+ int c;
+ do {
+ c = step();
+ } while (c != RdfN3ParsingContentHandler.EOF && c != '\n' && c != '\r');
+ discard();
+ }
+
+ /**
+ * Parse the current directive and update the context according to the kind
+ * of directive ("base", "prefix", etc).
+ *
+ * @param context
+ * The context to update.
+ * @throws IOException
+ */
+ public void parseDirective(Context context) throws IOException {
+ // Remove the leading '@' character.
+ step();
+ discard();
+ String currentKeyword = parseToken();
+ if ("base".equalsIgnoreCase(currentKeyword)) {
+ consumeWhiteSpaces();
+ String base = parseUri();
+ Reference ref = new Reference(base);
+ if (ref.isRelative()) {
+ context.getBase().addSegment(base);
+ } else {
+ context.setBase(ref);
+ }
+ consumeStatement();
+ } else if ("prefix".equalsIgnoreCase(currentKeyword)) {
+ consumeWhiteSpaces();
+ String prefix = parseToken();
+ consumeWhiteSpaces();
+ String uri = parseUri();
+ context.getPrefixes().put(prefix, uri);
+ consumeStatement();
+ } else if ("keywords".equalsIgnoreCase(currentKeyword)) {
+ consumeWhiteSpaces();
+ int c;
+ do {
+ c = step();
+ } while (c != RdfN3ParsingContentHandler.EOF && c != '.');
+ String strKeywords = getCurrentToken();
+ String[] keywords = strKeywords.split(",");
+ context.getKeywords().clear();
+ for (String keyword : keywords) {
+ context.getKeywords().add(keyword.trim());
+ }
+ consumeStatement();
+ } else {
+ // TODO @ForAll and @ForSome are not supported yet.
+ consumeStatement();
+ }
+ }
+
+ /**
+ * Reads the current statement until its end, and parses it.
+ *
+ * @param context
+ * The current context.
+ * @throws IOException
+ */
+ public void parseStatement(Context context) throws IOException {
+ List<LexicalUnit> lexicalUnits = new ArrayList<LexicalUnit>();
+ do {
+ consumeWhiteSpaces();
+ switch (getChar()) {
+ case '(':
+ lexicalUnits.add(new ListToken(this, context));
+ break;
+ case '<':
+ if (step() == '=') {
+ lexicalUnits.add(new Token("<="));
+ step();
+ discard();
+ } else {
+ stepBack();
+ lexicalUnits.add(new UriToken(this, context));
+ }
+ break;
+ case '_':
+ lexicalUnits.add(new BlankNodeToken(parseToken()));
+ break;
+ case '"':
+ lexicalUnits.add(new StringToken(this, context));
+ break;
+ case '[':
+ lexicalUnits.add(new BlankNodeToken(this, context));
+ break;
+ case '!':
+ lexicalUnits.add(new Token("!"));
+ step();
+ discard();
+ break;
+ case '^':
+ lexicalUnits.add(new Token("^"));
+ step();
+ discard();
+ break;
+ case '=':
+ if (step() == '>') {
+ lexicalUnits.add(new Token("=>"));
+ step();
+ discard();
+ } else {
+ lexicalUnits.add(new Token("="));
+ discard();
+ }
+ break;
+ case '@':
+ // Remove the leading '@' character.
+ step();
+ discard();
+ lexicalUnits.add(new Token(this, context));
+ discard();
+ break;
+ case ';':
+ // TODO
+ step();
+ discard();
+ lexicalUnits.add(new Token(";"));
+ break;
+ case ',':
+ // TODO
+ step();
+ discard();
+ lexicalUnits.add(new Token(","));
+ break;
+ case '{':
+ lexicalUnits.add(new FormulaToken(this, context));
+ break;
+ case '.':
+ break;
+ case RdfN3ParsingContentHandler.EOF:
+ break;
+ default:
+ lexicalUnits.add(new Token(this, context));
+ break;
+ }
+ } while (getChar() != RdfN3ParsingContentHandler.EOF
+ && getChar() != '.' && getChar() != '}');
+
+ // Generate the links
+ generateLinks(lexicalUnits);
+ }
+
+ /**
+ * Returns the value of the current token.
+ *
+ * @return The value of the current token.
+ * @throws IOException
+ */
+ public String parseToken() throws IOException {
+ int c;
+ do {
+ c = step();
+ } while (c != RdfN3ParsingContentHandler.EOF && !isDelimiter(c));
+ String result = getCurrentToken();
+ return result;
+ }
+
+ /**
+ * Returns the value of the current URI.
+ *
+ * @return The value of the current URI.
+ * @throws IOException
+ */
+ public String parseUri() throws IOException {
+ StringBuilder builder = new StringBuilder();
+ // Suppose the current character is "<".
+ int c = step();
+ while (c != RdfN3ParsingContentHandler.EOF && c != '>') {
+ if (!isWhiteSpace(c)) {
+ // Discard white spaces.
+ builder.append((char) c);
+ }
+ c = step();
+ }
+ if (c == '>') {
+ // Set the cursor at the right of the uri.
+ step();
+ }
+ discard();
+
+ return builder.toString();
+ }
+
+ /**
+ * Read a new character.
+ *
+ * @return The new read character.
+ * @throws IOException
+ */
+ public int step() throws IOException {
+ scoutIndex++;
+ if (buffer[scoutIndex] == RdfN3ParsingContentHandler.EOF) {
+ if (scoutIndex == RdfN3ParsingContentHandler.BUFFER_SIZE) {
+ // Reached the end of the first part of the buffer, read into
+ // the second one.
+ scoutIndex++;
+ int len = this.br.read(buffer, 0,
+ RdfN3ParsingContentHandler.BUFFER_SIZE);
+ if (len == -1) {
+ // End of the stream reached
+ buffer[scoutIndex] = RdfN3ParsingContentHandler.EOF;
+ } else {
+ buffer[RdfN3ParsingContentHandler.BUFFER_SIZE + len + 1] = RdfN3ParsingContentHandler.EOF;
+ }
+ } else if (scoutIndex == (2 * RdfN3ParsingContentHandler.BUFFER_SIZE + 1)) {
+ scoutIndex = 0;
+ // Reached the end of the second part of the buffer, read into
+ // the first one.
+ int len = this.br.read(buffer, 0,
+ RdfN3ParsingContentHandler.BUFFER_SIZE);
+ if (len == -1) {
+ // End of the stream reached
+ buffer[scoutIndex] = RdfN3ParsingContentHandler.EOF;
+ } else {
+ buffer[len] = RdfN3ParsingContentHandler.EOF;
+ }
+ } else {
+ // Reached the end of the stream.
+ }
+ }
+
+ return buffer[scoutIndex];
+ }
+
+ /**
+ * Steps forward.
+ *
+ * @param n
+ * the number of steps to go forward.
+ * @throws IOException
+ */
+ public void step(int n) throws IOException {
+ for (int i = 0; i < n; i++) {
+ step();
+ }
+ }
+
+ /**
+ * Steps back of one step.
+ *
+ */
+ public void stepBack() {
+ stepBack(1);
+ }
+
+ /**
+ * Steps back.
+ *
+ * @param n
+ * the number of steps to go back.
+ */
+ public void stepBack(int n) {
+ scoutIndex -= n;
+ if (scoutIndex < 0) {
+ scoutIndex = RdfN3ParsingContentHandler.BUFFER_SIZE * 2 + 1
+ - scoutIndex;
+ }
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3WritingContentHandler.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3WritingContentHandler.java
index b6db8b3713..2ab77fb250 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3WritingContentHandler.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/RdfN3WritingContentHandler.java
@@ -47,252 +47,254 @@
/**
* Handler of RDF content according to the N3 notation.
+ *
+ * @author Thierry Boileau
*/
public class RdfN3WritingContentHandler extends GraphHandler {
- /** Buffered writer. */
- BufferedWriter bw;
+ /** Buffered writer. */
+ private BufferedWriter bw;
- /** The current context object. */
- private Context context;
+ /** The current context object. */
+ private Context context;
- /** The preceding predicate used for factorization matter. */
- private Reference precPredicate;
+ /** The preceding predicate used for factorization matter. */
+ private Reference precPredicate;
- /** The preceding source used for factorization matter. */
- private Reference precSource;
+ /** The preceding source used for factorization matter. */
+ private Reference precSource;
- /** Indicates if the end of the statement is to be written. */
- private boolean writeExtraDot;
+ /** Indicates if the end of the statement is to be written. */
+ private boolean writeExtraDot;
- /**
- * Constructor.
- *
- * @param linkSet
- * The set of links to write to the output stream.
- * @param outputStream
- * The output stream to write to.
- * @throws IOException
- * @throws IOException
- */
- public RdfN3WritingContentHandler(Graph linkset, OutputStream outputStream)
- throws IOException {
- super();
- this.bw = new BufferedWriter(new OutputStreamWriter(outputStream));
- this.context = new Context();
- Map<String, String> prefixes = context.getPrefixes();
- prefixes.put(RdfConstants.RDF_SCHEMA.toString(), "rdf");
- prefixes.put(RdfConstants.RDF_SYNTAX.toString(), "rdfs");
- prefixes.put("http://www.w3.org/2000/10/swap/grammar/bnf#", "cfg");
- prefixes.put("http://www.w3.org/2000/10/swap/grammar/n3#", "n3");
- prefixes.put("http://www.w3.org/2000/10/swap/list#", "list");
- prefixes.put("http://www.w3.org/2000/10/swap/pim/doc#", "doc");
- prefixes.put("http://www.w3.org/2002/07/owl#", "owl");
- prefixes.put("http://www.w3.org/2000/10/swap/log#", "log");
- prefixes.put("http://purl.org/dc/elements/1.1/", "dc");
- prefixes.put("http://www.w3.org/2001/XMLSchema#", "type");
+ /**
+ * Constructor.
+ *
+ * @param linkSet
+ * The set of links to write to the output stream.
+ * @param outputStream
+ * The output stream to write to.
+ * @throws IOException
+ * @throws IOException
+ */
+ public RdfN3WritingContentHandler(Graph linkset, OutputStream outputStream)
+ throws IOException {
+ super();
+ this.bw = new BufferedWriter(new OutputStreamWriter(outputStream));
+ this.context = new Context();
+ Map<String, String> prefixes = context.getPrefixes();
+ prefixes.put(RdfConstants.RDF_SCHEMA.toString(), "rdf");
+ prefixes.put(RdfConstants.RDF_SYNTAX.toString(), "rdfs");
+ prefixes.put("http://www.w3.org/2000/10/swap/grammar/bnf#", "cfg");
+ prefixes.put("http://www.w3.org/2000/10/swap/grammar/n3#", "n3");
+ prefixes.put("http://www.w3.org/2000/10/swap/list#", "list");
+ prefixes.put("http://www.w3.org/2000/10/swap/pim/doc#", "doc");
+ prefixes.put("http://www.w3.org/2002/07/owl#", "owl");
+ prefixes.put("http://www.w3.org/2000/10/swap/log#", "log");
+ prefixes.put("http://purl.org/dc/elements/1.1/", "dc");
+ prefixes.put("http://www.w3.org/2001/XMLSchema#", "type");
- for (Entry<String, String> entry : prefixes.entrySet()) {
- this.bw.append("@prefix ").append(entry.getValue()).append(": ")
- .append(entry.getKey()).append(".\n");
- }
- this.bw.append("@keywords a, is, of, has.\n");
+ for (Entry<String, String> entry : prefixes.entrySet()) {
+ this.bw.append("@prefix ").append(entry.getValue()).append(": ")
+ .append(entry.getKey()).append(".\n");
+ }
+ this.bw.append("@keywords a, is, of, has.\n");
- this.write(linkset);
- this.bw.flush();
- }
+ this.write(linkset);
+ this.bw.flush();
+ }
- @Override
- public void link(Graph source, Reference typeRef, Literal target) {
- try {
- this.bw.write("{");
- write(source);
- this.bw.write("} ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- write(target);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- }
- }
+ @Override
+ public void link(Graph source, Reference typeRef, Literal target) {
+ try {
+ this.bw.write("{");
+ write(source);
+ this.bw.write("} ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ write(target);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ }
+ }
- @Override
- public void link(Graph source, Reference typeRef, Reference target) {
- try {
- this.bw.write("{");
- write(source);
- this.bw.write("} ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- write(target, this.context.getPrefixes());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- }
- }
+ @Override
+ public void link(Graph source, Reference typeRef, Reference target) {
+ try {
+ this.bw.write("{");
+ write(source);
+ this.bw.write("} ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ write(target, this.context.getPrefixes());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ }
+ }
- @Override
- public void link(Reference source, Reference typeRef, Literal target) {
- try {
- if (source.equals(this.precSource)) {
- if (typeRef.equals(this.precPredicate)) {
- this.bw.write(", ");
- } else {
- this.bw.write("; ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- }
- } else {
- write(source, this.context.getPrefixes());
- this.bw.write(" ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- }
- write(target);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- }
- }
+ @Override
+ public void link(Reference source, Reference typeRef, Literal target) {
+ try {
+ if (source.equals(this.precSource)) {
+ if (typeRef.equals(this.precPredicate)) {
+ this.bw.write(", ");
+ } else {
+ this.bw.write("; ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ }
+ } else {
+ write(source, this.context.getPrefixes());
+ this.bw.write(" ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ }
+ write(target);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ }
+ }
- @Override
- public void link(Reference source, Reference typeRef, Reference target) {
- try {
- if (source.equals(this.precSource)) {
- this.writeExtraDot = false;
- if (typeRef.equals(this.precPredicate)) {
- this.bw.write(", ");
- } else {
- this.bw.write("; ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- }
- } else {
- this.writeExtraDot = true;
- write(source, this.context.getPrefixes());
- this.bw.write(" ");
- write(typeRef, this.context.getPrefixes());
- this.bw.write(" ");
- }
- write(target, this.context.getPrefixes());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- }
- }
+ @Override
+ public void link(Reference source, Reference typeRef, Reference target) {
+ try {
+ if (source.equals(this.precSource)) {
+ this.writeExtraDot = false;
+ if (typeRef.equals(this.precPredicate)) {
+ this.bw.write(", ");
+ } else {
+ this.bw.write("; ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ }
+ } else {
+ this.writeExtraDot = true;
+ write(source, this.context.getPrefixes());
+ this.bw.write(" ");
+ write(typeRef, this.context.getPrefixes());
+ this.bw.write(" ");
+ }
+ write(target, this.context.getPrefixes());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ }
+ }
- /**
- * Write the representation of the given graph of links.
- *
- * @param linkset
- * the given graph of links.
- * @throws IOException
- * @throws IOException
- */
- private void write(Graph linkset) throws IOException {
- for (Link link : linkset) {
- if (link.hasReferenceSource()) {
- if (!link.getSourceAsReference().equals(this.precSource)) {
- this.bw.write(".\n");
- this.writeExtraDot = true;
- }
- if (link.hasReferenceTarget()) {
- link(link.getSourceAsReference(), link.getTypeRef(), link
- .getTargetAsReference());
- } else if (link.hasLiteralTarget()) {
- link(link.getSourceAsReference(), link.getTypeRef(), link
- .getTargetAsLiteral());
- } else if (link.hasLiteralTarget()) {
- // TODO Hande source as link.
- } else {
- // Error?
- }
- } else if (link.hasGraphSource()) {
- this.writeExtraDot = false;
- if (link.hasReferenceTarget()) {
- link(link.getSourceAsGraph(), link.getTypeRef(), link
- .getTargetAsReference());
- } else if (link.hasLiteralTarget()) {
- link(link.getSourceAsGraph(), link.getTypeRef(), link
- .getTargetAsLiteral());
- } else if (link.hasLiteralTarget()) {
- // TODO Hande source as link.
- } else {
- // Error?
- }
- this.bw.write(".\n");
- }
- this.precSource = link.getSourceAsReference();
- this.precPredicate = link.getTypeRef();
- }
- if (writeExtraDot) {
- this.bw.write(".\n");
- }
- }
+ /**
+ * Write the representation of the given graph of links.
+ *
+ * @param linkset
+ * the given graph of links.
+ * @throws IOException
+ * @throws IOException
+ */
+ private void write(Graph linkset) throws IOException {
+ for (Link link : linkset) {
+ if (link.hasReferenceSource()) {
+ if (!link.getSourceAsReference().equals(this.precSource)) {
+ this.bw.write(".\n");
+ this.writeExtraDot = true;
+ }
+ if (link.hasReferenceTarget()) {
+ link(link.getSourceAsReference(), link.getTypeRef(), link
+ .getTargetAsReference());
+ } else if (link.hasLiteralTarget()) {
+ link(link.getSourceAsReference(), link.getTypeRef(), link
+ .getTargetAsLiteral());
+ } else if (link.hasLiteralTarget()) {
+ // TODO Hande source as link.
+ } else {
+ // Error?
+ }
+ } else if (link.hasGraphSource()) {
+ this.writeExtraDot = false;
+ if (link.hasReferenceTarget()) {
+ link(link.getSourceAsGraph(), link.getTypeRef(), link
+ .getTargetAsReference());
+ } else if (link.hasLiteralTarget()) {
+ link(link.getSourceAsGraph(), link.getTypeRef(), link
+ .getTargetAsLiteral());
+ } else if (link.hasLiteralTarget()) {
+ // TODO Handle source as link.
+ } else {
+ // Error?
+ }
+ this.bw.write(".\n");
+ }
+ this.precSource = link.getSourceAsReference();
+ this.precPredicate = link.getTypeRef();
+ }
+ if (writeExtraDot) {
+ this.bw.write(".\n");
+ }
+ }
- /**
- * Writes the representation of a given reference to a byte stream.
- *
- * @param outputStream
- * The output stream.
- * @param reference
- * The reference to write.
- * @param prefixes
- * The map of known namespaces.
- * @throws IOException
- */
- private void write(Literal literal) throws IOException {
- // Write it as a string
- this.bw.write("\"");
- if (literal.getValue().contains("\n")) {
- this.bw.write("\"");
- this.bw.write("\"");
- this.bw.write(literal.getValue());
- this.bw.write("\"");
- this.bw.write("\"");
- } else {
- this.bw.write(literal.getValue());
- }
+ /**
+ * Writes the representation of a given reference to a byte stream.
+ *
+ * @param outputStream
+ * The output stream.
+ * @param reference
+ * The reference to write.
+ * @param prefixes
+ * The map of known namespaces.
+ * @throws IOException
+ */
+ private void write(Literal literal) throws IOException {
+ // Write it as a string
+ this.bw.write("\"");
+ if (literal.getValue().contains("\n")) {
+ this.bw.write("\"");
+ this.bw.write("\"");
+ this.bw.write(literal.getValue());
+ this.bw.write("\"");
+ this.bw.write("\"");
+ } else {
+ this.bw.write(literal.getValue());
+ }
- this.bw.write("\"");
- if (literal.getDatatypeRef() != null) {
- this.bw.write("^^");
- write(literal.getDatatypeRef(), context.getPrefixes());
- }
- if (literal.getLanguage() != null) {
- this.bw.write("@");
- this.bw.write(literal.getLanguage().toString());
- }
- }
+ this.bw.write("\"");
+ if (literal.getDatatypeRef() != null) {
+ this.bw.write("^^");
+ write(literal.getDatatypeRef(), context.getPrefixes());
+ }
+ if (literal.getLanguage() != null) {
+ this.bw.write("@");
+ this.bw.write(literal.getLanguage().toString());
+ }
+ }
- /**
- * Writes the representation of a given reference.
- *
- * @param reference
- * The reference to write.
- * @param prefixes
- * The map of known namespaces.
- * @throws IOException
- */
- private void write(Reference reference, Map<String, String> prefixes)
- throws IOException {
- String uri = reference.toString();
- if (LinkReference.isBlank(reference)) {
- this.bw.write(uri);
- } else {
- boolean found = false;
- for (Entry<String, String> entry : prefixes.entrySet()) {
- if (uri.startsWith(entry.getKey())) {
- found = true;
- this.bw.append(entry.getValue());
- this.bw.append(":");
- this.bw.append(uri.substring(entry.getKey().length()));
- break;
- }
- }
- if (!found) {
- this.bw.append("<");
- this.bw.append(uri);
- this.bw.append(">");
- }
- }
- }
+ /**
+ * Writes the representation of a given reference.
+ *
+ * @param reference
+ * The reference to write.
+ * @param prefixes
+ * The map of known namespaces.
+ * @throws IOException
+ */
+ private void write(Reference reference, Map<String, String> prefixes)
+ throws IOException {
+ String uri = reference.toString();
+ if (LinkReference.isBlank(reference)) {
+ this.bw.write(uri);
+ } else {
+ boolean found = false;
+ for (Entry<String, String> entry : prefixes.entrySet()) {
+ if (uri.startsWith(entry.getKey())) {
+ found = true;
+ this.bw.append(entry.getValue());
+ this.bw.append(":");
+ this.bw.append(uri.substring(entry.getKey().length()));
+ break;
+ }
+ }
+ if (!found) {
+ this.bw.append("<");
+ this.bw.append(uri);
+ this.bw.append(">");
+ }
+ }
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/StringToken.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/StringToken.java
index ee99cf9227..6922c42e0c 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/StringToken.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/StringToken.java
@@ -38,6 +38,8 @@
/**
* Represents a string of characters. This string could have a type and a
* language.
+ *
+ * @author Thierry Boileau
*/
class StringToken extends LexicalUnit {
/** Does this string contains at least a new line character? */
@@ -57,8 +59,8 @@ class StringToken extends LexicalUnit {
* @param context
* The parsing context.
*/
- public StringToken(RdfN3ParsingContentHandler contentHandler, Context context)
- throws IOException {
+ public StringToken(RdfN3ParsingContentHandler contentHandler,
+ Context context) throws IOException {
super(contentHandler, context);
multiLines = false;
this.parse();
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Token.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Token.java
index 08e63ff360..9d9eecfce9 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Token.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/Token.java
@@ -37,65 +37,67 @@
/**
* Represents a still unidentified N3 token.
+ *
+ * @author Thierry Boileau
*/
class Token extends LexicalUnit {
- /**
- * Constructor with arguments.
- *
- * @param contentHandler
- * The document's parent handler.
- * @param context
- * The parsing context.
- */
- public Token(RdfN3ParsingContentHandler contentHandler, Context context)
- throws IOException {
- super(contentHandler, context);
- this.parse();
- }
+ /**
+ * Constructor with arguments.
+ *
+ * @param contentHandler
+ * The document's parent handler.
+ * @param context
+ * The parsing context.
+ */
+ public Token(RdfN3ParsingContentHandler contentHandler, Context context)
+ throws IOException {
+ super(contentHandler, context);
+ this.parse();
+ }
- /**
- * Constructor with value.
- *
- * @param value
- * The value of the current lexical unit.
- */
- public Token(String value) {
- super(value);
- }
+ /**
+ * Constructor with value.
+ *
+ * @param value
+ * The value of the current lexical unit.
+ */
+ public Token(String value) {
+ super(value);
+ }
- @Override
- public void parse() throws IOException {
- int c;
- do {
- c = getContentHandler().step();
- } while (c != RdfN3ParsingContentHandler.EOF
- && !RdfN3ParsingContentHandler.isDelimiter(c));
- setValue(getContentHandler().getCurrentToken());
- }
+ @Override
+ public void parse() throws IOException {
+ int c;
+ do {
+ c = getContentHandler().step();
+ } while (c != RdfN3ParsingContentHandler.EOF
+ && !RdfN3ParsingContentHandler.isDelimiter(c));
+ setValue(getContentHandler().getCurrentToken());
+ }
- @Override
- public Object resolve() {
- Object result = null;
- if (getContext().isQName(getValue())) {
- result = (getContext() != null) ? getContext().resolve(getValue())
- : getValue();
- } else {
- // Must be a literal
- if (getValue().charAt(0) > '0' && getValue().charAt(0) < '9') {
- if (getValue().contains(".")) {
- // Consider it as a float
- result = new Literal(getValue(),
- RdfConstants.XML_SCHEMA_TYPE_FLOAT);
- } else {
- // Consider it as an integer
- result = new Literal(getValue(),
- RdfConstants.XML_SCHEMA_TYPE_INTEGER);
- }
- } else {
- // TODO What kind of literal?
- }
- }
- return result;
- }
+ @Override
+ public Object resolve() {
+ Object result = null;
+ if (getContext().isQName(getValue())) {
+ result = (getContext() != null) ? getContext().resolve(getValue())
+ : getValue();
+ } else {
+ // Must be a literal
+ if (getValue().charAt(0) > '0' && getValue().charAt(0) < '9') {
+ if (getValue().contains(".")) {
+ // Consider it as a float
+ result = new Literal(getValue(),
+ RdfConstants.XML_SCHEMA_TYPE_FLOAT);
+ } else {
+ // Consider it as an integer
+ result = new Literal(getValue(),
+ RdfConstants.XML_SCHEMA_TYPE_INTEGER);
+ }
+ } else {
+ // TODO What kind of literal?
+ }
+ }
+ return result;
+ }
}
\ No newline at end of file
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/UriToken.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/UriToken.java
index aab5170289..ff5737d905 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/UriToken.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/n3/UriToken.java
@@ -36,6 +36,8 @@
/**
* Represents a URI token inside a RDF N3 document.
+ *
+ * @author Thierry Boileau
*/
class UriToken extends LexicalUnit {
/**
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ContentReader.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ContentReader.java
new file mode 100644
index 0000000000..0cfb970367
--- /dev/null
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ContentReader.java
@@ -0,0 +1,695 @@
+/**
+ * Copyright 2005-2009 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
+package org.restlet.ext.rdf.internal.xml;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.restlet.data.Language;
+import org.restlet.data.Reference;
+import org.restlet.ext.rdf.GraphHandler;
+import org.restlet.ext.rdf.LinkReference;
+import org.restlet.ext.rdf.Literal;
+import org.restlet.ext.rdf.RdfRepresentation;
+import org.restlet.ext.rdf.internal.RdfConstants;
+import org.restlet.representation.Representation;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * Content reader part.
+ *
+ * @author Thierry Boileau
+ */
+class ContentReader extends DefaultHandler {
+ public enum State {
+ LITERAL, NONE, OBJECT, PREDICATE, SUBJECT
+ }
+
+ /** Increment used to identify inner blank nodes. */
+ private static int blankNodeId = 0;
+
+ /**
+ * Returns the identifier of a new blank node.
+ *
+ * @return The identifier of a new blank node.
+ */
+ private static String newBlankNodeId() {
+ return "#_bn" + blankNodeId++;
+ }
+
+ /** The value of the "base" URI. */
+ private ScopedProperty<Reference> base;
+
+ /** Container for string content. */
+ private StringBuilder builder;
+
+ /** Indicates if the string content must be consumed. */
+ private boolean consumeContent;
+
+ /** Current data type. */
+ private String currentDataType;
+
+ /** Current language. */
+ private ScopedProperty<Language> language;
+
+ /** Current object. */
+ private Object currentObject;
+
+ /** Current predicate. */
+ private Reference currentPredicate;
+
+ /** The graph handler to call when a link is detected. */
+ private GraphHandler graphHandler;
+
+ /** Used to get the content of XMl literal. */
+ private int nodeDepth;
+
+ /** The list of known prefixes. */
+ private Map<String, String> prefixes;
+
+ /**
+ * True if {@link RdfRepresentation#RDF_SYNTAX} is the default namespace.
+ */
+ private boolean rdfDefaultNamespace;
+
+ /** Used when a statement must be reified. */
+ private Reference reifiedRef;
+
+ /** Heap of states. */
+ private List<ContentReader.State> states;
+
+ /** Heap of subjects. */
+ private List<Reference> subjects;
+
+ /**
+ *
+ *
+ * @param graphHandler
+ *
+ */
+ /**
+ * Constructor.
+ *
+ * @param graphHandler
+ * The graph handler to call when a link is detected.
+ * @param representation
+ * The input representation.
+ */
+ public ContentReader(GraphHandler graphHandler,
+ Representation representation) {
+ super();
+ this.graphHandler = graphHandler;
+ this.base = new ScopedProperty<Reference>();
+ this.language = new ScopedProperty<Language>();
+ if (representation.getIdentifier() != null) {
+ this.base.add(representation.getIdentifier().getTargetRef());
+ this.base.incrDepth();
+ }
+ if (representation.getLanguages().size() == 1) {
+ this.language.add(representation.getLanguages().get(1));
+ this.language.incrDepth();
+ }
+ }
+
+ @Override
+ public void characters(char[] ch, int start, int length)
+ throws SAXException {
+ if (consumeContent) {
+ builder.append(ch, start, length);
+ }
+ }
+
+ /**
+ * Returns true if the given qualified name is in the RDF namespace and is
+ * equal to the given local name.
+ *
+ * @param localName
+ * The local name to compare to.
+ * @param qName
+ * The qualified name
+ */
+ private boolean checkRdfQName(String localName, String qName) {
+ boolean result = qName.equals("rdf:" + localName);
+ if (!result) {
+ int index = qName.indexOf(":");
+ // The qualified name has no prefix.
+ result = rdfDefaultNamespace && (index == -1)
+ && localName.equals(qName);
+ }
+
+ return result;
+ }
+
+ @Override
+ public void endDocument() throws SAXException {
+ this.builder = null;
+ this.currentObject = null;
+ this.currentPredicate = null;
+ this.graphHandler = null;
+ this.prefixes.clear();
+ this.prefixes = null;
+ this.states.clear();
+ this.states = null;
+ this.subjects.clear();
+ this.subjects = null;
+ this.nodeDepth = 0;
+ }
+
+ @Override
+ public void endElement(String uri, String localName, String name)
+ throws SAXException {
+ ContentReader.State state = popState();
+
+ if (state == State.SUBJECT) {
+ popSubject();
+ } else if (state == State.PREDICATE) {
+ if (this.consumeContent) {
+ link(getCurrentSubject(), this.currentPredicate, getLiteral(
+ builder.toString(), null, this.language.getValue()));
+ this.consumeContent = false;
+ }
+ } else if (state == State.OBJECT) {
+ } else if (state == State.LITERAL) {
+ if (nodeDepth == 0) {
+ // End of the XML literal
+ link(getCurrentSubject(), this.currentPredicate, getLiteral(
+ builder.toString(), this.currentDataType, this.language
+ .getValue()));
+ } else {
+ // Still gleaning the content of an XML literal
+ // Glean the XML content
+ this.builder.append("</");
+ if (uri != null && !"".equals(uri)) {
+ this.builder.append(uri).append(":");
+ }
+ this.builder.append(localName).append(">");
+ nodeDepth--;
+ pushState(state);
+ }
+ }
+ this.base.decrDepth();
+ this.language.decrDepth();
+ }
+
+ @Override
+ public void endPrefixMapping(String prefix) throws SAXException {
+ this.prefixes.remove(prefix);
+ }
+
+ /**
+ * Returns the state at the top of the heap.
+ *
+ * @return The state at the top of the heap.
+ */
+ private ContentReader.State getCurrentState() {
+ ContentReader.State result = null;
+ int size = this.states.size();
+
+ if (size > 0) {
+ result = this.states.get(size - 1);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the subject at the top of the heap.
+ *
+ * @return The subject at the top of the heap.
+ */
+ private Reference getCurrentSubject() {
+ Reference result = null;
+ int size = this.subjects.size();
+
+ if (size > 0) {
+ result = this.subjects.get(size - 1);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns a Literal object according to the given parameters.
+ *
+ * @param value
+ * The value of the literal.
+ * @param datatype
+ * The datatype of the literal.
+ * @param language
+ * The language of the literal.
+ * @return A Literal object
+ */
+ private Literal getLiteral(String value, String datatype, Language language) {
+ Literal literal = new Literal(value);
+ if (datatype != null) {
+ literal.setDatatypeRef(new Reference(datatype));
+ }
+ if (language != null) {
+ literal.setLanguage(language);
+ }
+ return literal;
+ }
+
+ /**
+ * A new statement has been detected with the current subject, predicate and
+ * object.
+ */
+ private void link() {
+ Reference currentSubject = getCurrentSubject();
+ if (currentSubject instanceof Reference) {
+ if (this.currentObject instanceof Reference) {
+ link(currentSubject, this.currentPredicate,
+ (Reference) this.currentObject);
+ } else if (this.currentObject instanceof Literal) {
+ link(currentSubject, this.currentPredicate,
+ (Literal) this.currentObject);
+ } else {
+ // TODO Error.
+ }
+ } else {
+ // TODO Error.
+ }
+ }
+
+ /**
+ * Creates a statement and reify it, if necessary.
+ *
+ * @param subject
+ * The subject of the statement.
+ * @param predicate
+ * The predicate of the statement.
+ * @param object
+ * The object of the statement.
+ */
+ private void link(Reference subject, Reference predicate, Literal object) {
+ this.graphHandler.link(subject, predicate, object);
+ if (this.reifiedRef != null) {
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_SUBJECT, subject);
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_PREDICATE, predicate);
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_OBJECT, object);
+ this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE,
+ RdfConstants.PREDICATE_STATEMENT);
+ this.reifiedRef = null;
+ }
+ }
+
+ /**
+ * Creates a statement and reify it, if necessary.
+ *
+ * @param subject
+ * The subject of the statement.
+ * @param predicate
+ * The predicate of the statement.
+ * @param object
+ * The object of the statement.
+ */
+ private void link(Reference subject, Reference predicate, Reference object) {
+ this.graphHandler.link(subject, predicate, object);
+
+ if (this.reifiedRef != null) {
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_SUBJECT, subject);
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_PREDICATE, predicate);
+ this.graphHandler.link(this.reifiedRef,
+ RdfConstants.PREDICATE_OBJECT, object);
+ this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE,
+ RdfConstants.PREDICATE_STATEMENT);
+ this.reifiedRef = null;
+ }
+ }
+
+ /**
+ * Returns the RDF URI of the given node represented by its namespace uri,
+ * local name, name, and attributes. It also generates the available
+ * statements, thanks to some shortcuts provided by the RDF XML syntax.
+ *
+ * @param uri
+ * @param localName
+ * @param name
+ * @param attributes
+ * @return The RDF URI of the given node.
+ */
+ private Reference parseNode(String uri, String localName, String name,
+ Attributes attributes) {
+ Reference result = null;
+ // Stores the arcs
+ List<String[]> arcs = new ArrayList<String[]>();
+ boolean found = false;
+ if (attributes.getIndex("xml:base") != -1) {
+ this.base.add(new Reference(attributes.getValue("xml:base")));
+ }
+ // Get the RDF URI of this node
+ for (int i = 0; i < attributes.getLength(); i++) {
+ String qName = attributes.getQName(i);
+ if (checkRdfQName("about", qName)) {
+ found = true;
+ result = resolve(attributes.getValue(i), false);
+ } else if (checkRdfQName("nodeID", qName)) {
+ found = true;
+ result = LinkReference.createBlank(attributes.getValue(i));
+ } else if (checkRdfQName("ID", qName)) {
+ found = true;
+ result = resolve(attributes.getValue(i), true);
+ } else if ("xml:lang".equals(qName)) {
+ this.language.add(Language.valueOf(attributes.getValue(i)));
+ } else if ("xml:base".equals(qName)) {
+ // Already stored
+ } else {
+ if (!qName.startsWith("xmlns")) {
+ String[] arc = { qName, attributes.getValue(i) };
+ arcs.add(arc);
+ }
+ }
+ }
+ if (!found) {
+ // Blank node with no given ID
+ result = LinkReference.createBlank(ContentReader.newBlankNodeId());
+ }
+
+ // Create the available statements
+ if (!checkRdfQName("Description", name)) {
+ // Handle typed node
+ this.graphHandler.link(result, RdfConstants.PREDICATE_TYPE,
+ resolve(uri, name));
+ }
+ for (String[] arc : arcs) {
+ this.graphHandler.link(result, resolve(null, arc[0]), getLiteral(
+ arc[1], null, this.language.getValue()));
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the state at the top of the heap and removes it from the heap.
+ *
+ * @return The state at the top of the heap.
+ */
+ private ContentReader.State popState() {
+ ContentReader.State result = null;
+ int size = this.states.size();
+
+ if (size > 0) {
+ result = this.states.remove(size - 1);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the subject at the top of the heap and removes it from the heap.
+ *
+ * @return The subject at the top of the heap.
+ */
+ private Reference popSubject() {
+ Reference result = null;
+ int size = this.subjects.size();
+
+ if (size > 0) {
+ result = this.subjects.remove(size - 1);
+ }
+
+ return result;
+ }
+
+ /**
+ * Adds a new state at the top of the heap.
+ *
+ * @param state
+ * The state to add.
+ */
+ private void pushState(ContentReader.State state) {
+ this.states.add(state);
+ }
+
+ /**
+ * Adds a new subject at the top of the heap.
+ *
+ * @param subject
+ * The subject to add.
+ */
+ private void pushSubject(Reference subject) {
+ this.subjects.add(subject);
+ }
+
+ /**
+ * Returns the absolute reference for a given value. If this value is not an
+ * absolute URI, then the base URI is used.
+ *
+ * @param value
+ * The value.
+ * @param fragment
+ * True if the value is a fragment to add to the base reference.
+ * @return Returns the absolute reference for a given value.
+ */
+ private Reference resolve(String value, boolean fragment) {
+ Reference result = null;
+
+ if (fragment) {
+ result = new Reference(this.base.getValue());
+ result.setFragment(value);
+ } else {
+ result = new Reference(value);
+ if (result.isRelative()) {
+ result = new Reference(this.base.getValue(), value);
+ }
+ }
+ return result.getTargetRef();
+ }
+
+ /**
+ * Returns the absolute reference of a parsed element according to its URI,
+ * qualified name. In case the base URI is null or empty, then an attempt is
+ * made to look for the mapped URI according to the qName.
+ *
+ * @param uri
+ * The base URI.
+ * @param qName
+ * The qualified name of the parsed element.
+ * @return Returns the absolute reference of a parsed element.
+ */
+ private Reference resolve(String uri, String qName) {
+ Reference result = null;
+
+ int index = qName.indexOf(":");
+ String prefix = null;
+ String localName = null;
+ if (index != -1) {
+ prefix = qName.substring(0, index);
+ localName = qName.substring(index + 1);
+ } else {
+ localName = qName;
+ prefix = "";
+ }
+
+ if (uri != null && !"".equals(uri)) {
+ if (!uri.endsWith("#") && !uri.endsWith("/")) {
+ result = new Reference(uri + "/" + localName);
+ } else {
+ result = new Reference(uri + localName);
+ }
+ } else {
+ String baseUri = this.prefixes.get(prefix);
+ if (baseUri != null) {
+ result = new Reference(baseUri + localName);
+ }
+ }
+
+ return (result == null) ? null : result.getTargetRef();
+ }
+
+ @Override
+ public void startDocument() throws SAXException {
+ this.prefixes = new HashMap<String, String>();
+ this.builder = new StringBuilder();
+ this.states = new ArrayList<ContentReader.State>();
+ this.subjects = new ArrayList<Reference>();
+ nodeDepth = 0;
+ pushState(State.NONE);
+ }
+
+ @Override
+ public void startElement(String uri, String localName, String name,
+ Attributes attributes) throws SAXException {
+ ContentReader.State state = getCurrentState();
+ this.base.incrDepth();
+ this.language.incrDepth();
+ if (!this.consumeContent && this.builder != null) {
+ this.builder = null;
+ }
+ if (state == State.NONE) {
+ if (checkRdfQName("RDF", name)) {
+ // Top element
+ String base = attributes.getValue("xml:base");
+ if (base != null) {
+ this.base.add(new Reference(base));
+ }
+ } else {
+ // Parse the current subject
+ pushSubject(parseNode(uri, localName, name, attributes));
+ pushState(State.SUBJECT);
+ }
+ } else if (state == State.SUBJECT) {
+ // Parse the current predicate
+ List<String[]> arcs = new ArrayList<String[]>();
+ pushState(State.PREDICATE);
+ this.consumeContent = true;
+ Reference currentSubject = getCurrentSubject();
+ this.currentPredicate = resolve(uri, name);
+ Reference currentObject = null;
+ for (int i = 0; i < attributes.getLength(); i++) {
+ String qName = attributes.getQName(i);
+ if (checkRdfQName("resource", qName)) {
+ this.consumeContent = false;
+ currentObject = resolve(attributes.getValue(i), false);
+ popState();
+ pushState(State.OBJECT);
+ } else if (checkRdfQName("datatype", qName)) {
+ // The object is a literal
+ this.consumeContent = true;
+ popState();
+ pushState(State.LITERAL);
+ this.currentDataType = attributes.getValue(i);
+ } else if (checkRdfQName("parseType", qName)) {
+ String value = attributes.getValue(i);
+ if ("Literal".equals(value)) {
+ this.consumeContent = true;
+ // The object is an XML literal
+ popState();
+ pushState(State.LITERAL);
+ this.currentDataType = RdfConstants.RDF_SYNTAX
+ + "XMLLiteral";
+ nodeDepth = 0;
+ } else if ("Resource".equals(value)) {
+ this.consumeContent = false;
+ // Create a new blank node
+ currentObject = LinkReference.createBlank(ContentReader
+ .newBlankNodeId());
+ popState();
+ pushState(State.SUBJECT);
+ pushSubject(currentObject);
+ } else {
+ this.consumeContent = false;
+ // Error
+ }
+ } else if (checkRdfQName("nodeID", qName)) {
+ this.consumeContent = false;
+ currentObject = LinkReference.createBlank(attributes
+ .getValue(i));
+ popState();
+ pushState(State.SUBJECT);
+ pushSubject(currentObject);
+ } else if (checkRdfQName("ID", qName)) {
+ // Reify the statement
+ reifiedRef = resolve(attributes.getValue(i), true);
+ } else if ("xml:lang".equals(qName)) {
+ this.language.add(Language.valueOf(attributes.getValue(i)));
+ } else {
+ if (!qName.startsWith("xmlns")) {
+ // Add arcs.
+ String[] arc = { qName, attributes.getValue(i) };
+ arcs.add(arc);
+ }
+ }
+ }
+ if (currentObject != null) {
+ link(currentSubject, this.currentPredicate, currentObject);
+ }
+
+ if (!arcs.isEmpty()) {
+ // Create arcs that starts from a blank node and ends to
+ // literal values. This blank node is the object of the
+ // current statement.
+
+ boolean found = false;
+ Reference blankNode = LinkReference.createBlank(ContentReader
+ .newBlankNodeId());
+ for (String[] arc : arcs) {
+ Reference pRef = resolve(null, arc[0]);
+ // Silently remove unrecognized attributes
+ if (pRef != null) {
+ found = true;
+ this.graphHandler.link(blankNode, pRef, new Literal(
+ arc[1]));
+ }
+ }
+ if (found) {
+ link(currentSubject, this.currentPredicate, blankNode);
+ popState();
+ pushState(State.OBJECT);
+ }
+ }
+ if (this.consumeContent) {
+ builder = new StringBuilder();
+ }
+ } else if (state == State.PREDICATE) {
+ this.consumeContent = false;
+ // Parse the current object, create the current link
+ Reference object = parseNode(uri, localName, name, attributes);
+ this.currentObject = object;
+ link();
+ pushSubject(object);
+ pushState(State.SUBJECT);
+ } else if (state == State.OBJECT) {
+ } else if (state == State.LITERAL) {
+ // Glean the XML content
+ nodeDepth++;
+ this.builder.append("<");
+ if (uri != null && !"".equals(uri)) {
+ this.builder.append(uri).append(":");
+ }
+ this.builder.append(localName).append(">");
+ }
+ }
+
+ @Override
+ public void startPrefixMapping(String prefix, String uri)
+ throws SAXException {
+ this.rdfDefaultNamespace = this.rdfDefaultNamespace
+ || ((prefix == null || "".equals(prefix)
+ && RdfConstants.RDF_SYNTAX.toString(true, true).equals(
+ uri)));
+
+ if (!uri.endsWith("#") && !uri.endsWith("/")) {
+ this.prefixes.put(prefix, uri + "/");
+ } else {
+ this.prefixes.put(prefix, uri);
+ }
+ }
+}
\ No newline at end of file
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 c5309f9bc0..7629798903 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
@@ -1,839 +1,120 @@
+/**
+ * Copyright 2005-2009 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
package org.restlet.ext.rdf.internal.xml;
import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import org.restlet.data.Language;
import org.restlet.data.Reference;
import org.restlet.ext.rdf.Graph;
import org.restlet.ext.rdf.GraphHandler;
-import org.restlet.ext.rdf.LinkReference;
import org.restlet.ext.rdf.Literal;
-import org.restlet.ext.rdf.RdfRepresentation;
-import org.restlet.ext.rdf.internal.RdfConstants;
import org.restlet.representation.Representation;
import org.restlet.representation.SaxRepresentation;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
+/**
+ * Handler of RDF content according to the RDF/XML format.
+ *
+ * @author Thierry Boileau
+ */
public class RdfXmlParsingContentHandler extends GraphHandler {
- /**
- * Content reader part.
- */
- private static class ContentReader extends DefaultHandler {
- public enum State {
- LITERAL, NONE, OBJECT, PREDICATE, SUBJECT
- }
-
- /** Increment used to identify inner blank nodes. */
- private static int blankNodeId = 0;
-
- /**
- * Returns the identifier of a new blank node.
- *
- * @return The identifier of a new blank node.
- */
- private static String newBlankNodeId() {
- return "#_bn" + blankNodeId++;
- }
-
- /** The value of the "base" URI. */
- private ScopedProperty<Reference> base;
-
- /** Container for string content. */
- private StringBuilder builder;
-
- /** Indicates if the string content must be consumed. */
- private boolean consumeContent;
-
- /** Current data type. */
- private String currentDataType;
-
- /** Current language. */
- private ScopedProperty<Language> language;
-
- /** Current object. */
- private Object currentObject;
-
- /** Current predicate. */
- private Reference currentPredicate;
-
- /** The graph handler to call when a link is detected. */
- private GraphHandler graphHandler;
-
- /** Used to get the content of XMl literal. */
- private int nodeDepth;
-
- /** The list of known prefixes. */
- private Map<String, String> prefixes;
-
- /**
- * True if {@link RdfRepresentation#RDF_SYNTAX} is the default
- * namespace.
- */
- private boolean rdfDefaultNamespace;
-
- /** Used when a statement must be reified. */
- private Reference reifiedRef;
-
- /** Heap of states. */
- private List<State> states;
-
- /** Heap of subjects. */
- private List<Reference> subjects;
-
- /**
- *
- *
- * @param graphHandler
- *
- */
- /**
- * Constructor.
- *
- * @param graphHandler
- * The graph handler to call when a link is detected.
- * @param representation
- * The input representation.
- */
- public ContentReader(GraphHandler graphHandler,
- Representation representation) {
- super();
- this.graphHandler = graphHandler;
- this.base = new ScopedProperty<Reference>();
- this.language = new ScopedProperty<Language>();
- if (representation.getIdentifier() != null) {
- this.base.add(representation.getIdentifier().getTargetRef());
- this.base.incrDepth();
- }
- if (representation.getLanguages().size() == 1) {
- this.language.add(representation.getLanguages().get(1));
- this.language.incrDepth();
- }
- }
-
- @Override
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- if (consumeContent) {
- builder.append(ch, start, length);
- }
- }
-
- /**
- * Returns true if the given qualified name is in the RDF namespace and
- * is equal to the given local name.
- *
- * @param localName
- * The local name to compare to.
- * @param qName
- * The qualified name
- */
- private boolean checkRdfQName(String localName, String qName) {
- boolean result = qName.equals("rdf:" + localName);
- if (!result) {
- int index = qName.indexOf(":");
- // The qualified name has no prefix.
- result = rdfDefaultNamespace && (index == -1)
- && localName.equals(qName);
- }
-
- return result;
- }
-
- @Override
- public void endDocument() throws SAXException {
- this.builder = null;
- this.currentObject = null;
- this.currentPredicate = null;
- this.graphHandler = null;
- this.prefixes.clear();
- this.prefixes = null;
- this.states.clear();
- this.states = null;
- this.subjects.clear();
- this.subjects = null;
- this.nodeDepth = 0;
- }
-
- @Override
- public void endElement(String uri, String localName, String name)
- throws SAXException {
- State state = popState();
-
- if (state == State.SUBJECT) {
- popSubject();
- } else if (state == State.PREDICATE) {
- if (this.consumeContent) {
- link(getCurrentSubject(), this.currentPredicate,
- getLiteral(builder.toString(), null, this.language
- .getValue()));
- this.consumeContent = false;
- }
- } else if (state == State.OBJECT) {
- } else if (state == State.LITERAL) {
- if (nodeDepth == 0) {
- // End of the XML literal
- link(getCurrentSubject(), this.currentPredicate,
- getLiteral(builder.toString(),
- this.currentDataType, this.language
- .getValue()));
- } else {
- // Still gleaning the content of an XML literal
- // Glean the XML content
- this.builder.append("</");
- if (uri != null && !"".equals(uri)) {
- this.builder.append(uri).append(":");
- }
- this.builder.append(localName).append(">");
- nodeDepth--;
- pushState(state);
- }
- }
- this.base.decrDepth();
- this.language.decrDepth();
- }
-
- @Override
- public void endPrefixMapping(String prefix) throws SAXException {
- this.prefixes.remove(prefix);
- }
-
- /**
- * Returns the state at the top of the heap.
- *
- * @return The state at the top of the heap.
- */
- private State getCurrentState() {
- State result = null;
- int size = this.states.size();
-
- if (size > 0) {
- result = this.states.get(size - 1);
- }
-
- return result;
- }
-
- /**
- * Returns the subject at the top of the heap.
- *
- * @return The subject at the top of the heap.
- */
- private Reference getCurrentSubject() {
- Reference result = null;
- int size = this.subjects.size();
-
- if (size > 0) {
- result = this.subjects.get(size - 1);
- }
-
- return result;
- }
-
- /**
- * Returns a Literal object according to the given parameters.
- *
- * @param value
- * The value of the literal.
- * @param datatype
- * The datatype of the literal.
- * @param language
- * The language of the literal.
- * @return A Literal object
- */
- private Literal getLiteral(String value, String datatype,
- Language language) {
- Literal literal = new Literal(value);
- if (datatype != null) {
- literal.setDatatypeRef(new Reference(datatype));
- }
- if (language != null) {
- literal.setLanguage(language);
- }
- return literal;
- }
-
- /**
- * A new statement has been detected with the current subject, predicate
- * and object.
- */
- private void link() {
- Reference currentSubject = getCurrentSubject();
- if (currentSubject instanceof Reference) {
- if (this.currentObject instanceof Reference) {
- link(currentSubject, this.currentPredicate,
- (Reference) this.currentObject);
- } else if (this.currentObject instanceof Literal) {
- link(currentSubject, this.currentPredicate,
- (Literal) this.currentObject);
- } else {
- // TODO Error.
- }
- } else {
- // TODO Error.
- }
- }
-
- /**
- * Creates a statement and reify it, if necessary.
- *
- * @param subject
- * The subject of the statement.
- * @param predicate
- * The predicate of the statement.
- * @param object
- * The object of the statement.
- */
- private void link(Reference subject, Reference predicate, Literal object) {
- this.graphHandler.link(subject, predicate, object);
- if (this.reifiedRef != null) {
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_SUBJECT, subject);
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_PREDICATE, predicate);
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_OBJECT, object);
- this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE,
- RdfConstants.PREDICATE_STATEMENT);
- this.reifiedRef = null;
- }
- }
-
- /**
- * Creates a statement and reify it, if necessary.
- *
- * @param subject
- * The subject of the statement.
- * @param predicate
- * The predicate of the statement.
- * @param object
- * The object of the statement.
- */
- private void link(Reference subject, Reference predicate,
- Reference object) {
- this.graphHandler.link(subject, predicate, object);
-
- if (this.reifiedRef != null) {
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_SUBJECT, subject);
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_PREDICATE, predicate);
- this.graphHandler.link(this.reifiedRef,
- RdfConstants.PREDICATE_OBJECT, object);
- this.graphHandler.link(reifiedRef, RdfConstants.PREDICATE_TYPE,
- RdfConstants.PREDICATE_STATEMENT);
- this.reifiedRef = null;
- }
- }
-
- /**
- * Returns the RDF URI of the given node represented by its namespace
- * uri, local name, name, and attributes. It also generates the
- * available statements, thanks to some shortcuts provided by the RDF
- * XML syntax.
- *
- * @param uri
- * @param localName
- * @param name
- * @param attributes
- * @return The RDF URI of the given node.
- */
- private Reference parseNode(String uri, String localName, String name,
- Attributes attributes) {
- Reference result = null;
- // Stores the arcs
- List<String[]> arcs = new ArrayList<String[]>();
- boolean found = false;
- if (attributes.getIndex("xml:base") != -1) {
- this.base.add(new Reference(attributes.getValue("xml:base")));
- }
- // Get the RDF URI of this node
- for (int i = 0; i < attributes.getLength(); i++) {
- String qName = attributes.getQName(i);
- if (checkRdfQName("about", qName)) {
- found = true;
- result = resolve(attributes.getValue(i), false);
- } else if (checkRdfQName("nodeID", qName)) {
- found = true;
- result = LinkReference.createBlank(attributes.getValue(i));
- } else if (checkRdfQName("ID", qName)) {
- found = true;
- result = resolve(attributes.getValue(i), true);
- } else if ("xml:lang".equals(qName)) {
- this.language.add(Language.valueOf(attributes.getValue(i)));
- } else if ("xml:base".equals(qName)) {
- // Already stored
- } else {
- if (!qName.startsWith("xmlns")) {
- String[] arc = { qName, attributes.getValue(i) };
- arcs.add(arc);
- }
- }
- }
- if (!found) {
- // Blank node with no given ID
- result = LinkReference.createBlank(ContentReader
- .newBlankNodeId());
- }
-
- // Create the available statements
- if (!checkRdfQName("Description", name)) {
- // Handle typed node
- this.graphHandler.link(result, RdfConstants.PREDICATE_TYPE,
- resolve(uri, name));
- }
- for (String[] arc : arcs) {
- this.graphHandler.link(result, resolve(null, arc[0]),
- getLiteral(arc[1], null, this.language.getValue()));
- }
-
- return result;
- }
-
- /**
- * Returns the state at the top of the heap and removes it from the
- * heap.
- *
- * @return The state at the top of the heap.
- */
- private State popState() {
- State result = null;
- int size = this.states.size();
-
- if (size > 0) {
- result = this.states.remove(size - 1);
- }
-
- return result;
- }
-
- /**
- * Returns the subject at the top of the heap and removes it from the
- * heap.
- *
- * @return The subject at the top of the heap.
- */
- private Reference popSubject() {
- Reference result = null;
- int size = this.subjects.size();
-
- if (size > 0) {
- result = this.subjects.remove(size - 1);
- }
-
- return result;
- }
-
- /**
- * Adds a new state at the top of the heap.
- *
- * @param state
- * The state to add.
- */
- private void pushState(State state) {
- this.states.add(state);
- }
-
- /**
- * Adds a new subject at the top of the heap.
- *
- * @param subject
- * The subject to add.
- */
- private void pushSubject(Reference subject) {
- this.subjects.add(subject);
- }
-
- /**
- * Returns the absolute reference for a given value. If this value is
- * not an absolute URI, then the base URI is used.
- *
- * @param value
- * The value.
- * @param fragment
- * True if the value is a fragment to add to the base
- * reference.
- * @return Returns the absolute reference for a given value.
- */
- private Reference resolve(String value, boolean fragment) {
- Reference result = null;
-
- if (fragment) {
- result = new Reference(this.base.getValue());
- result.setFragment(value);
- } else {
- result = new Reference(value);
- if (result.isRelative()) {
- result = new Reference(this.base.getValue(), value);
- }
- }
- return result.getTargetRef();
- }
-
- /**
- * Returns the absolute reference of a parsed element according to its
- * URI, qualified name. In case the base URI is null or empty, then an
- * attempt is made to look for the mapped URI according to the qName.
- *
- * @param uri
- * The base URI.
- * @param qName
- * The qualified name of the parsed element.
- * @return Returns the absolute reference of a parsed element.
- */
- private Reference resolve(String uri, String qName) {
- Reference result = null;
-
- int index = qName.indexOf(":");
- String prefix = null;
- String localName = null;
- if (index != -1) {
- prefix = qName.substring(0, index);
- localName = qName.substring(index + 1);
- } else {
- localName = qName;
- prefix = "";
- }
-
- if (uri != null && !"".equals(uri)) {
- if (!uri.endsWith("#") && !uri.endsWith("/")) {
- result = new Reference(uri + "/" + localName);
- } else {
- result = new Reference(uri + localName);
- }
- } else {
- String baseUri = this.prefixes.get(prefix);
- if (baseUri != null) {
- result = new Reference(baseUri + localName);
- }
- }
-
- return (result == null) ? null : result.getTargetRef();
- }
-
- @Override
- public void startDocument() throws SAXException {
- this.prefixes = new HashMap<String, String>();
- this.builder = new StringBuilder();
- this.states = new ArrayList<State>();
- this.subjects = new ArrayList<Reference>();
- nodeDepth = 0;
- pushState(State.NONE);
- }
-
- @Override
- public void startElement(String uri, String localName, String name,
- Attributes attributes) throws SAXException {
- State state = getCurrentState();
- this.base.incrDepth();
- this.language.incrDepth();
- if (!this.consumeContent && this.builder != null) {
- this.builder = null;
- }
- if (state == State.NONE) {
- if (checkRdfQName("RDF", name)) {
- // Top element
- String base = attributes.getValue("xml:base");
- if (base != null) {
- this.base.add(new Reference(base));
- }
- } else {
- // Parse the current subject
- pushSubject(parseNode(uri, localName, name, attributes));
- pushState(State.SUBJECT);
- }
- } else if (state == State.SUBJECT) {
- // Parse the current predicate
- List<String[]> arcs = new ArrayList<String[]>();
- pushState(State.PREDICATE);
- this.consumeContent = true;
- Reference currentSubject = getCurrentSubject();
- this.currentPredicate = resolve(uri, name);
- Reference currentObject = null;
- for (int i = 0; i < attributes.getLength(); i++) {
- String qName = attributes.getQName(i);
- if (checkRdfQName("resource", qName)) {
- this.consumeContent = false;
- currentObject = resolve(attributes.getValue(i), false);
- popState();
- pushState(State.OBJECT);
- } else if (checkRdfQName("datatype", qName)) {
- // The object is a literal
- this.consumeContent = true;
- popState();
- pushState(State.LITERAL);
- this.currentDataType = attributes.getValue(i);
- } else if (checkRdfQName("parseType", qName)) {
- String value = attributes.getValue(i);
- if ("Literal".equals(value)) {
- this.consumeContent = true;
- // The object is an XML literal
- popState();
- pushState(State.LITERAL);
- this.currentDataType = RdfConstants.RDF_SYNTAX
- + "XMLLiteral";
- nodeDepth = 0;
- } else if ("Resource".equals(value)) {
- this.consumeContent = false;
- // Create a new blank node
- currentObject = LinkReference
- .createBlank(ContentReader.newBlankNodeId());
- popState();
- pushState(State.SUBJECT);
- pushSubject(currentObject);
- } else {
- this.consumeContent = false;
- // Error
- }
- } else if (checkRdfQName("nodeID", qName)) {
- this.consumeContent = false;
- currentObject = LinkReference.createBlank(attributes
- .getValue(i));
- popState();
- pushState(State.SUBJECT);
- pushSubject(currentObject);
- } else if (checkRdfQName("ID", qName)) {
- // Reify the statement
- reifiedRef = resolve(attributes.getValue(i), true);
- } else if ("xml:lang".equals(qName)) {
- this.language.add(Language.valueOf(attributes
- .getValue(i)));
- } else {
- if (!qName.startsWith("xmlns")) {
- // Add arcs.
- String[] arc = { qName, attributes.getValue(i) };
- arcs.add(arc);
- }
- }
- }
- if (currentObject != null) {
- link(currentSubject, this.currentPredicate, currentObject);
- }
-
- if (!arcs.isEmpty()) {
- // Create arcs that starts from a blank node and ends to
- // literal values. This blank node is the object of the
- // current statement.
-
- boolean found = false;
- Reference blankNode = LinkReference
- .createBlank(ContentReader.newBlankNodeId());
- for (String[] arc : arcs) {
- Reference pRef = resolve(null, arc[0]);
- // Silently remove unrecognized attributes
- if (pRef != null) {
- found = true;
- this.graphHandler.link(blankNode, pRef,
- new Literal(arc[1]));
- }
- }
- if (found) {
- link(currentSubject, this.currentPredicate, blankNode);
- popState();
- pushState(State.OBJECT);
- }
- }
- if (this.consumeContent) {
- builder = new StringBuilder();
- }
- } else if (state == State.PREDICATE) {
- this.consumeContent = false;
- // Parse the current object, create the current link
- Reference object = parseNode(uri, localName, name, attributes);
- this.currentObject = object;
- link();
- pushSubject(object);
- pushState(State.SUBJECT);
- } else if (state == State.OBJECT) {
- } else if (state == State.LITERAL) {
- // Glean the XML content
- nodeDepth++;
- this.builder.append("<");
- if (uri != null && !"".equals(uri)) {
- this.builder.append(uri).append(":");
- }
- this.builder.append(localName).append(">");
- }
- }
-
- @Override
- public void startPrefixMapping(String prefix, String uri)
- throws SAXException {
- this.rdfDefaultNamespace = this.rdfDefaultNamespace
- || ((prefix == null || "".equals(prefix)
- && RdfConstants.RDF_SYNTAX.toString(true, true)
- .equals(uri)));
-
- if (!uri.endsWith("#") && !uri.endsWith("/")) {
- this.prefixes.put(prefix, uri + "/");
- } else {
- this.prefixes.put(prefix, uri);
- }
- }
- }
-
- /**
- * Used to handle properties that have a scope such as the base URI, the
- * xml:lang property.
- *
- * @param <E>
- * The type of the property.
- */
- private static class ScopedProperty<E> {
- private int[] depths;
- private List<E> values;
- private int size;
-
- /**
- * Constructor.
- */
- public ScopedProperty() {
- super();
- this.depths = new int[10];
- this.values = new ArrayList<E>();
- this.size = 0;
- }
-
- /**
- * Constructor.
- *
- * @param value
- * Value.
- */
- public ScopedProperty(E value) {
- this();
- add(value);
- incrDepth();
- }
-
- /**
- * Add a new value.
- *
- * @param value
- * The value to be added.
- */
- public void add(E value) {
- this.values.add(value);
- if (this.size == this.depths.length) {
- int[] temp = new int[2 * this.depths.length];
- System.arraycopy(this.depths, 0, temp, 0, this.depths.length);
- this.depths = temp;
- }
- this.size++;
- this.depths[size - 1] = 0;
- }
-
- /**
- * Decrements the depth of the current value, and remove it if
- * necessary.
- */
- public void decrDepth() {
- if (this.size > 0) {
- this.depths[size - 1]--;
- if (this.depths[size - 1] < 0) {
- this.size--;
- this.values.remove(size);
- }
- }
- }
-
- /**
- * Returns the current value.
- *
- * @return The current value.
- */
- public E getValue() {
- if (this.size > 0) {
- return this.values.get(this.size - 1);
- }
- return null;
- }
-
- /**
- * Increments the depth of the current value.
- */
- public void incrDepth() {
- if (this.size > 0) {
- this.depths[size - 1]++;
- }
- }
- }
-
- /** The set of links to update when parsing, or to read when writing. */
- private Graph linkSet;
-
- /** The representation to read. */
- private SaxRepresentation rdfXmlRepresentation;
-
- /**
- * Constructor.
- *
- * @param linkSet
- * The set of links to update during the parsing.
- * @param rdfXmlRepresentation
- * The representation to read.
- * @throws IOException
- */
- public RdfXmlParsingContentHandler(Graph linkSet,
- Representation rdfXmlRepresentation) throws IOException {
- super();
- this.linkSet = linkSet;
- if (rdfXmlRepresentation instanceof SaxRepresentation) {
- this.rdfXmlRepresentation = (SaxRepresentation) rdfXmlRepresentation;
- } else {
- this.rdfXmlRepresentation = new SaxRepresentation(
- rdfXmlRepresentation);
- // Transmit the identifier used as a base for the resolution of
- // relative URIs.
- this.rdfXmlRepresentation.setIdentifier(rdfXmlRepresentation
- .getIdentifier());
- }
-
- parse();
- }
-
- @Override
- public void link(Graph source, Reference typeRef, Literal target) {
- if (source != null && typeRef != null && target != null) {
- this.linkSet.add(source, typeRef, target);
- }
- }
-
- @Override
- public void link(Graph source, Reference typeRef, Reference target) {
- if (source != null && typeRef != null && target != null) {
- this.linkSet.add(source, typeRef, target);
- }
- }
-
- @Override
- public void link(Reference source, Reference typeRef, Literal target) {
- if (source != null && typeRef != null && target != null) {
- this.linkSet.add(source, typeRef, target);
- }
- }
-
- @Override
- public void link(Reference source, Reference typeRef, Reference target) {
- if (source != null && typeRef != null && target != null) {
- this.linkSet.add(source, typeRef, target);
- }
- }
-
- /**
- * Parses the current representation.
- *
- * @throws IOException
- */
- private void parse() throws IOException {
- this.rdfXmlRepresentation.parse(new ContentReader(this,
- rdfXmlRepresentation));
- }
+ /** The set of links to update when parsing, or to read when writing. */
+ private Graph linkSet;
+
+ /** The representation to read. */
+ private SaxRepresentation rdfXmlRepresentation;
+
+ /**
+ * Constructor.
+ *
+ * @param linkSet
+ * The set of links to update during the parsing.
+ * @param rdfXmlRepresentation
+ * The representation to read.
+ * @throws IOException
+ */
+ public RdfXmlParsingContentHandler(Graph linkSet,
+ Representation rdfXmlRepresentation) throws IOException {
+ super();
+ this.linkSet = linkSet;
+ if (rdfXmlRepresentation instanceof SaxRepresentation) {
+ this.rdfXmlRepresentation = (SaxRepresentation) rdfXmlRepresentation;
+ } else {
+ this.rdfXmlRepresentation = new SaxRepresentation(
+ rdfXmlRepresentation);
+ // Transmit the identifier used as a base for the resolution of
+ // relative URIs.
+ this.rdfXmlRepresentation.setIdentifier(rdfXmlRepresentation
+ .getIdentifier());
+ }
+
+ parse();
+ }
+
+ @Override
+ public void link(Graph source, Reference typeRef, Literal target) {
+ if (source != null && typeRef != null && target != null) {
+ this.linkSet.add(source, typeRef, target);
+ }
+ }
+
+ @Override
+ public void link(Graph source, Reference typeRef, Reference target) {
+ if (source != null && typeRef != null && target != null) {
+ this.linkSet.add(source, typeRef, target);
+ }
+ }
+
+ @Override
+ public void link(Reference source, Reference typeRef, Literal target) {
+ if (source != null && typeRef != null && target != null) {
+ this.linkSet.add(source, typeRef, target);
+ }
+ }
+
+ @Override
+ public void link(Reference source, Reference typeRef, Reference target) {
+ if (source != null && typeRef != null && target != null) {
+ this.linkSet.add(source, typeRef, target);
+ }
+ }
+
+ /**
+ * Parses the current representation.
+ *
+ * @throws IOException
+ */
+ private void parse() throws IOException {
+ this.rdfXmlRepresentation.parse(new ContentReader(this,
+ rdfXmlRepresentation));
+ }
}
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlWritingContentHandler.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlWritingContentHandler.java
index fb7cb9629a..98077b2dc1 100644
--- a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlWritingContentHandler.java
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/RdfXmlWritingContentHandler.java
@@ -42,11 +42,13 @@
/**
* Handler of RDF content according to the RDF XML syntax.
+ *
+ * @author Thierry Boileau
*/
public class RdfXmlWritingContentHandler extends GraphHandler {
/** Buffered writer. */
- // TODO plutôt un XMLWriter?
+ // TODO better to use a XMLWriter?
BufferedWriter bw;
/**
diff --git a/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ScopedProperty.java b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ScopedProperty.java
new file mode 100644
index 0000000000..c6fe2bdada
--- /dev/null
+++ b/modules/org.restlet.ext.rdf/src/org/restlet/ext/rdf/internal/xml/ScopedProperty.java
@@ -0,0 +1,123 @@
+/**
+ * Copyright 2005-2009 Noelios Technologies.
+ *
+ * The contents of this file are subject to the terms of one of the following
+ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
+ * "Licenses"). You can select the license that you prefer but you may not use
+ * this file except in compliance with one of these Licenses.
+ *
+ * You can obtain a copy of the LGPL 3.0 license at
+ * http://www.opensource.org/licenses/lgpl-3.0.html
+ *
+ * You can obtain a copy of the LGPL 2.1 license at
+ * http://www.opensource.org/licenses/lgpl-2.1.php
+ *
+ * You can obtain a copy of the CDDL 1.0 license at
+ * http://www.opensource.org/licenses/cddl1.php
+ *
+ * You can obtain a copy of the EPL 1.0 license at
+ * http://www.opensource.org/licenses/eclipse-1.0.php
+ *
+ * See the Licenses for the specific language governing permissions and
+ * limitations under the Licenses.
+ *
+ * Alternatively, you can obtain a royalty free commercial license with less
+ * limitations, transferable or non-transferable, directly at
+ * http://www.noelios.com/products/restlet-engine
+ *
+ * Restlet is a registered trademark of Noelios Technologies.
+ */
+
+package org.restlet.ext.rdf.internal.xml;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Used to handle properties that have a scope such as the base URI, the
+ * xml:lang property.
+ *
+ * @param <E>
+ * The type of the property.
+ * @author Thierry Boileau
+ */
+class ScopedProperty<E> {
+ private int[] depths;
+
+ private List<E> values;
+
+ private int size;
+
+ /**
+ * Constructor.
+ */
+ public ScopedProperty() {
+ super();
+ this.depths = new int[10];
+ this.values = new ArrayList<E>();
+ this.size = 0;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param value
+ * Value.
+ */
+ public ScopedProperty(E value) {
+ this();
+ add(value);
+ incrDepth();
+ }
+
+ /**
+ * Add a new value.
+ *
+ * @param value
+ * The value to be added.
+ */
+ public void add(E value) {
+ this.values.add(value);
+ if (this.size == this.depths.length) {
+ int[] temp = new int[2 * this.depths.length];
+ System.arraycopy(this.depths, 0, temp, 0, this.depths.length);
+ this.depths = temp;
+ }
+ this.size++;
+ this.depths[size - 1] = 0;
+ }
+
+ /**
+ * Decrements the depth of the current value, and remove it if necessary.
+ */
+ public void decrDepth() {
+ if (this.size > 0) {
+ this.depths[size - 1]--;
+ if (this.depths[size - 1] < 0) {
+ this.size--;
+ this.values.remove(size);
+ }
+ }
+ }
+
+ /**
+ * Returns the current value.
+ *
+ * @return The current value.
+ */
+ public E getValue() {
+ if (this.size > 0) {
+ return this.values.get(this.size - 1);
+ }
+ return null;
+ }
+
+ /**
+ * Increments the depth of the current value.
+ */
+ public void incrDepth() {
+ if (this.size > 0) {
+ this.depths[size - 1]++;
+ }
+ }
+}
\ No newline at end of file
|
6b8123d7265158c62e4be7aaa20d7b70e3703c10
|
elasticsearch
|
Don't allow unallocated indexes to be closed.--Closes -3313-
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java
index 403f7c0f3cd96..9c9272ec84237 100644
--- a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java
+++ b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java
@@ -27,6 +27,8 @@
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.block.ClusterBlocks;
+import org.elasticsearch.cluster.routing.IndexRoutingTable;
+import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
@@ -37,6 +39,7 @@
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.indices.IndexMissingException;
+import org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException;
import org.elasticsearch.rest.RestStatus;
import java.util.ArrayList;
@@ -87,6 +90,13 @@ public ClusterState execute(ClusterState currentState) {
if (indexMetaData == null) {
throw new IndexMissingException(new Index(index));
}
+ IndexRoutingTable indexRoutingTable = currentState.routingTable().index(index);
+ for (IndexShardRoutingTable shard : indexRoutingTable) {
+ if (!shard.primaryAllocatedPostApi()) {
+ throw new IndexPrimaryShardNotAllocatedException(new Index(index));
+ }
+ }
+
if (indexMetaData.state() != IndexMetaData.State.CLOSE) {
indicesToClose.add(index);
}
diff --git a/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java b/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java
new file mode 100644
index 0000000000000..9523a90a50c4d
--- /dev/null
+++ b/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java
@@ -0,0 +1,40 @@
+/*
+ * 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.indices;
+
+import org.elasticsearch.index.Index;
+import org.elasticsearch.index.IndexException;
+import org.elasticsearch.rest.RestStatus;
+
+/**
+ * Thrown when some action cannot be performed because the primary shard of
+ * some shard group in an index has not been allocated post api action.
+ */
+public class IndexPrimaryShardNotAllocatedException extends IndexException {
+
+ public IndexPrimaryShardNotAllocatedException(Index index) {
+ super(index, "primary not allocated post api");
+ }
+
+ @Override
+ public RestStatus status() {
+ return RestStatus.CONFLICT;
+ }
+}
diff --git a/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java b/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java
index 6fd838bc9c954..f2e95e6284095 100644
--- a/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java
+++ b/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java
@@ -20,7 +20,9 @@
package org.elasticsearch.test.integration.indices.settings;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.test.integration.AbstractSharedClusterTest;
import org.junit.Test;
@@ -63,6 +65,10 @@ public void testOpenCloseUpdateSettings() throws Exception {
// now close the index, change the non dynamic setting, and see that it applies
+ // Wait for the index to turn green before attempting to close it
+ ClusterHealthResponse health = client().admin().cluster().prepareHealth().setTimeout("30s").setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
+ assertThat(health.isTimedOut(), equalTo(false));
+
client().admin().indices().prepareClose("test").execute().actionGet();
client().admin().indices().prepareUpdateSettings("test")
diff --git a/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java b/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java
index ddc36292b0483..752b57fa6100f 100644
--- a/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java
+++ b/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java
@@ -19,9 +19,13 @@
package org.elasticsearch.test.integration.indices.state;
+import junit.framework.Assert;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
+import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
+import org.elasticsearch.action.admin.indices.settings.UpdateSettingsResponse;
import org.elasticsearch.action.admin.indices.status.IndicesStatusResponse;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
@@ -29,8 +33,10 @@
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
+import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.SettingsException;
import org.elasticsearch.indices.IndexMissingException;
+import org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.junit.After;
import org.junit.Test;
@@ -107,6 +113,45 @@ public void testSimpleOpenClose() {
client("node1").prepareIndex("test", "type1", "1").setSource("field1", "value1").execute().actionGet();
}
+ @Test
+ public void testFastCloseAfterCreateDoesNotClose() {
+ logger.info("--> starting two nodes....");
+ startNode("node1");
+ startNode("node2");
+
+ logger.info("--> creating test index that cannot be allocated");
+ client("node1").admin().indices().prepareCreate("test").setSettings(ImmutableSettings.settingsBuilder()
+ .put("index.routing.allocation.include.tag", "no_such_node")
+ .put("index.number_of_replicas", 1).build()).execute().actionGet();
+
+ ClusterHealthResponse health = client("node1").admin().cluster().prepareHealth("test").setWaitForNodes("2").execute().actionGet();
+ assertThat(health.isTimedOut(), equalTo(false));
+ assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED));
+
+ try {
+ client().admin().indices().prepareClose("test").execute().actionGet();
+ Assert.fail("Exception should have been thrown");
+ } catch(IndexPrimaryShardNotAllocatedException e) {
+ // expected
+ }
+
+ logger.info("--> updating test index settings to allow allocation");
+ client("node1").admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.settingsBuilder()
+ .put("index.routing.allocation.include.tag", "").build()).execute().actionGet();
+
+ logger.info("--> waiting for green status");
+ health = client("node1").admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("2").execute().actionGet();
+ assertThat(health.isTimedOut(), equalTo(false));
+
+ ClusterStateResponse stateResponse = client("node1").admin().cluster().prepareState().execute().actionGet();
+ assertThat(stateResponse.getState().metaData().index("test").state(), equalTo(IndexMetaData.State.OPEN));
+ assertThat(stateResponse.getState().routingTable().index("test").shards().size(), equalTo(5));
+ assertThat(stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(), equalTo(10));
+
+ logger.info("--> indexing a simple document");
+ client("node1").prepareIndex("test", "type1", "1").setSource("field1", "value1").execute().actionGet();
+ }
+
@Test
public void testConsistencyAfterIndexCreationFailure() {
logger.info("--> starting one node....");
|
3bed0b4348c2c87052e51618fb8cbd5afa58e2db
|
ReactiveX-RxJava
|
Refactored TakeUntil to use TakeWhile.--
|
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 7e37e38a72..a7a868bcd9 100644
--- a/rxjava-core/src/main/java/rx/Observable.java
+++ b/rxjava-core/src/main/java/rx/Observable.java
@@ -968,7 +968,7 @@ public static <T> Observable<T> merge(Observable<T>... source) {
* @return An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public static <T, E> Observable<T> takeUntil(final Observable<T> source, final Observable<E> other) {
- return _create(OperatorTakeUntil.takeUntil(source, other));
+ return OperatorTakeUntil.takeUntil(source, other);
}
diff --git a/rxjava-core/src/main/java/rx/operators/OperatorTakeUntil.java b/rxjava-core/src/main/java/rx/operators/OperatorTakeUntil.java
index 669ca794fc..77affc27a3 100644
--- a/rxjava-core/src/main/java/rx/operators/OperatorTakeUntil.java
+++ b/rxjava-core/src/main/java/rx/operators/OperatorTakeUntil.java
@@ -16,15 +16,11 @@
package rx.operators;
import org.junit.Test;
-import rx.Notification;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
-import rx.util.AtomicObservableSubscription;
-import rx.util.Pair;
import rx.util.functions.Func1;
-import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class OperatorTakeUntil {
@@ -38,92 +34,101 @@ public class OperatorTakeUntil {
* @param <E> the other type.
* @return An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
- public static <T, E> Func1<Observer<T>, Subscription> takeUntil(final Observable<T> source, final Observable<E> other) {
- return new TakeUntil<T, E>(source, other);
+ public static <T, E> Observable<T> takeUntil(final Observable<T> source, final Observable<E> other) {
+ Observable<Notification<T>> s = Observable.create(new SourceObservable<T>(source));
+ Observable<Notification<T>> o = Observable.create(new OtherObservable<T, E>(other));
+ Observable<Notification<T>> result = Observable.merge(s, o);
+
+ return result.takeWhile(new Func1<Notification<T>, Boolean>() {
+ @Override
+ public Boolean call(Notification<T> notification) {
+ return !notification.halt;
+ }
+ }).map(new Func1<Notification<T>, T>() {
+ @Override
+ public T call(Notification<T> notification) {
+ return notification.value;
+ }
+ });
}
- private static class TakeUntil<T, E> implements Func1<Observer<T>, Subscription> {
+ private static class Notification<T> {
+ private final boolean halt;
+ private final T value;
- private final Observable<T> source;
- private final Observable<E> other;
- private final AtomicObservableSubscription subscription = new AtomicObservableSubscription();
+ public static <T> Notification<T> value(T value) {
+ return new Notification<T>(false, value);
+ }
- private TakeUntil(Observable<T> source, Observable<E> other) {
- this.source = source;
- this.other = other;
+ public static <T> Notification<T> halt() {
+ return new Notification<T>(true, null);
}
- @Override
- public Subscription call(final Observer<T> observer) {
- Observable<Pair<Type, Notification<T>>> result = mergeWithIdentifier(source, other);
+ private Notification(boolean halt, T value) {
+ this.halt = halt;
+ this.value = value;
+ }
+
+ }
+
+ private static class SourceObservable<T> implements Func1<Observer<Notification<T>>, Subscription> {
+ private final Observable<T> sequence;
- return subscription.wrap(result.subscribe(new Observer<Pair<Type, Notification<T>>>() {
+ private SourceObservable(Observable<T> sequence) {
+ this.sequence = sequence;
+ }
+
+ @Override
+ public Subscription call(final Observer<Notification<T>> notificationObserver) {
+ return sequence.subscribe(new Observer<T>() {
@Override
public void onCompleted() {
- // ignore
+ notificationObserver.onNext(Notification.<T>halt());
}
@Override
public void onError(Exception e) {
- // ignore
+ notificationObserver.onError(e);
}
@Override
- public void onNext(Pair<Type, Notification<T>> pair) {
- Type type = pair.getFirst();
- Notification<T> notification = pair.getSecond();
-
- if (notification.isOnError()) {
- observer.onError(notification.getException());
- } else if (type == Type.SOURCE && notification.isOnNext()) {
- observer.onNext(notification.getValue());
- } else if ((type == Type.OTHER && notification.isOnNext()) || (type == Type.SOURCE && notification.isOnCompleted())) {
- observer.onCompleted();
- }
-
+ public void onNext(T args) {
+ notificationObserver.onNext(Notification.value(args));
}
- }));
+ });
+ }
+ }
+
+ private static class OtherObservable<T, E> implements Func1<Observer<Notification<T>>, Subscription> {
+ private final Observable<E> sequence;
+
+ private OtherObservable(Observable<E> sequence) {
+ this.sequence = sequence;
}
- @SuppressWarnings("unchecked")
- private static <T, E> Observable<Pair<Type, Notification<T>>> mergeWithIdentifier(Observable<T> source, Observable<E> other) {
- Observable<Pair<Type, Notification<T>>> s = source.materialize().map(new Func1<Notification<T>, Pair<Type, Notification<T>>>() {
+ @Override
+ public Subscription call(final Observer<Notification<T>> notificationObserver) {
+ return sequence.subscribe(new Observer<E>() {
@Override
- public Pair<Type, Notification<T>> call(Notification<T> arg) {
- return Pair.create(Type.SOURCE, arg);
+ public void onCompleted() {
+ // Ignore
}
- });
- Observable<Pair<Type, Notification<T>>> o = other.materialize().map(new Func1<Notification<E>, Pair<Type, Notification<T>>>() {
@Override
- public Pair<Type, Notification<T>> call(Notification<E> arg) {
- Notification<T> n = null;
- if (arg.isOnNext()) {
- n = new Notification<T>((T)null);
- }
- if (arg.isOnCompleted()) {
- n = new Notification<T>();
- }
- if (arg.isOnError()) {
- n = new Notification<T>(arg.getException());
- }
- return Pair.create(Type.OTHER, n);
+ public void onError(Exception e) {
+ notificationObserver.onError(e);
}
- });
-
- return Observable.merge(s, o);
- }
- private static enum Type {
- SOURCE, OTHER
+ @Override
+ public void onNext(E args) {
+ notificationObserver.onNext(Notification.<T>halt());
+ }
+ });
}
-
}
-
public static class UnitTest {
-
@Test
public void testTakeUntil() {
Subscription sSource = mock(Subscription.class);
@@ -132,7 +137,7 @@ public void testTakeUntil() {
TestObservable other = new TestObservable(sOther);
Observer<String> result = mock(Observer.class);
- Observable<String> stringObservable = Observable.create(new TakeUntil<String, String>(source, other));
+ Observable<String> stringObservable = takeUntil(source, other);
stringObservable.subscribe(result);
source.sendOnNext("one");
source.sendOnNext("two");
@@ -158,7 +163,7 @@ public void testTakeUntilSourceCompleted() {
TestObservable other = new TestObservable(sOther);
Observer<String> result = mock(Observer.class);
- Observable<String> stringObservable = Observable.create(new TakeUntil<String, String>(source, other));
+ Observable<String> stringObservable = takeUntil(source, other);
stringObservable.subscribe(result);
source.sendOnNext("one");
source.sendOnNext("two");
@@ -177,17 +182,18 @@ public void testTakeUntilSourceError() {
Subscription sOther = mock(Subscription.class);
TestObservable source = new TestObservable(sSource);
TestObservable other = new TestObservable(sOther);
+ Exception error = new Exception();
Observer<String> result = mock(Observer.class);
- Observable<String> stringObservable = Observable.create(new TakeUntil<String, String>(source, other));
+ Observable<String> stringObservable = takeUntil(source, other);
stringObservable.subscribe(result);
source.sendOnNext("one");
source.sendOnNext("two");
- source.sendOnError(new TestException());
+ source.sendOnError(error);
verify(result, times(1)).onNext("one");
verify(result, times(1)).onNext("two");
- verify(result, times(1)).onError(any(TestException.class));
+ verify(result, times(1)).onError(error);
verify(sSource, times(1)).unsubscribe();
verify(sOther, times(1)).unsubscribe();
@@ -199,18 +205,19 @@ public void testTakeUntilOtherError() {
Subscription sOther = mock(Subscription.class);
TestObservable source = new TestObservable(sSource);
TestObservable other = new TestObservable(sOther);
+ Exception error = new Exception();
Observer<String> result = mock(Observer.class);
- Observable<String> stringObservable = Observable.create(new TakeUntil<String, String>(source, other));
+ Observable<String> stringObservable = takeUntil(source, other);
stringObservable.subscribe(result);
source.sendOnNext("one");
source.sendOnNext("two");
- other.sendOnError(new TestException());
+ other.sendOnError(error);
verify(result, times(1)).onNext("one");
verify(result, times(1)).onNext("two");
// ignore other exception
- verify(result, times(1)).onError(any(TestException.class));
+ verify(result, times(1)).onError(error);
verify(result, times(0)).onCompleted();
verify(sSource, times(1)).unsubscribe();
verify(sOther, times(1)).unsubscribe();
@@ -225,7 +232,7 @@ public void testTakeUntilOtherCompleted() {
TestObservable other = new TestObservable(sOther);
Observer<String> result = mock(Observer.class);
- Observable<String> stringObservable = Observable.create(new TakeUntil<String, String>(source, other));
+ Observable<String> stringObservable = takeUntil(source, other);
stringObservable.subscribe(result);
source.sendOnNext("one");
source.sendOnNext("two");
@@ -271,9 +278,5 @@ public Subscription subscribe(final Observer<String> observer) {
}
}
- private static class TestException extends RuntimeException {
-
- }
-
}
}
diff --git a/rxjava-core/src/main/java/rx/util/Pair.java b/rxjava-core/src/main/java/rx/util/Pair.java
deleted file mode 100644
index ea06f571c4..0000000000
--- a/rxjava-core/src/main/java/rx/util/Pair.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Copyright 2013 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;
-
-public final class Pair<A, B> {
- private final A first;
- private final B second;
-
- public static <A, B> Pair<A, B> create(A first, B second) {
- return new Pair<A, B>(first, second);
- }
-
- private Pair(A first, B second) {
- this.first = first;
- this.second = second;
- }
-
- public A getFirst() {
- return first;
- }
-
- public B getSecond() {
- return second;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Pair pair = (Pair) o;
-
- if (first != null ? !first.equals(pair.first) : pair.first != null) return false;
- if (second != null ? !second.equals(pair.second) : pair.second != null) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = first != null ? first.hashCode() : 0;
- result = 31 * result + (second != null ? second.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "Pair{" +
- "first=" + first +
- ", second=" + second +
- '}';
- }
-}
|
b657bdfa1a9467848cc1844b5c732087e5eae1ca
|
elasticsearch
|
Optimize aliases processing--Closes- 2832-
|
p
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
index 09d607bf9d63b..47b1de66fd6d5 100644
--- a/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
+++ b/src/main/java/org/elasticsearch/index/aliases/IndexAliasesService.java
@@ -39,6 +39,7 @@
import org.elasticsearch.indices.InvalidAliasNameException;
import java.io.IOException;
+import java.util.Map;
import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder;
@@ -67,10 +68,20 @@ public IndexAlias alias(String alias) {
return aliases.get(alias);
}
+ public IndexAlias create(String alias, @Nullable CompressedString filter) {
+ return new IndexAlias(alias, filter, parse(alias, filter));
+ }
+
public void add(String alias, @Nullable CompressedString filter) {
add(new IndexAlias(alias, filter, parse(alias, filter)));
}
+ public void addAll(Map<String, IndexAlias> aliases) {
+ synchronized (mutex) {
+ this.aliases = newMapBuilder(this.aliases).putAll(aliases).immutableMap();
+ }
+ }
+
/**
* Returns the filter associated with listed filtering aliases.
* <p/>
diff --git a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
index f7cbd4e12be14..d7ca96d866701 100644
--- a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
+++ b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java
@@ -62,10 +62,13 @@
import org.elasticsearch.indices.recovery.StartRecoveryRequest;
import org.elasticsearch.threadpool.ThreadPool;
+import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
+import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.newHashSet;
import static org.elasticsearch.ExceptionsHelper.detailedMessage;
@@ -433,9 +436,7 @@ private void applyAliases(ClusterChangedEvent event) {
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
IndexAliasesService indexAliasesService = indexService.aliasesService();
- for (AliasMetaData aliasesMd : indexMetaData.aliases().values()) {
- processAlias(index, aliasesMd.alias(), aliasesMd.filter(), indexAliasesService);
- }
+ processAliases(index, indexMetaData.aliases().values(), indexAliasesService);
// go over and remove aliases
for (IndexAlias indexAlias : indexAliasesService) {
if (!indexMetaData.aliases().containsKey(indexAlias.alias())) {
@@ -450,26 +451,31 @@ private void applyAliases(ClusterChangedEvent event) {
}
}
- private void processAlias(String index, String alias, CompressedString filter, IndexAliasesService indexAliasesService) {
- try {
- if (!indexAliasesService.hasAlias(alias)) {
- if (logger.isDebugEnabled()) {
- logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
- }
- indexAliasesService.add(alias, filter);
- } else {
- if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
- (filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
+ private void processAliases(String index, Collection<AliasMetaData> aliases, IndexAliasesService indexAliasesService) {
+ HashMap<String, IndexAlias> newAliases = newHashMap();
+ for (AliasMetaData aliasMd : aliases) {
+ String alias = aliasMd.alias();
+ CompressedString filter = aliasMd.filter();
+ try {
+ if (!indexAliasesService.hasAlias(alias)) {
if (logger.isDebugEnabled()) {
- logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
+ logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
+ }
+ newAliases.put(alias, indexAliasesService.create(alias, filter));
+ } else {
+ if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
+ (filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
+ }
+ newAliases.put(alias, indexAliasesService.create(alias, filter));
}
- indexAliasesService.add(alias, filter);
}
+ } catch (Exception e) {
+ logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
- } catch (Exception e) {
- logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
-
+ indexAliasesService.addAll(newAliases);
}
private void applyNewOrUpdatedShards(final ClusterChangedEvent event) throws ElasticSearchException {
|
bd5dbb665e1af5b3ac2f63eaea49b36377bb8b1a
|
kotlin
|
Fix header scope for secondary constructors--Add companion object's scope and nested classes-- -KT-6996 fixed-
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
index 051caf4b5a1a2..e8a947b69a0f2 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java
@@ -277,20 +277,22 @@ private JetScope computeScopeForMemberDeclarationResolution() {
thisScope.setImplicitReceiver(this.getThisAsReceiverParameter());
thisScope.changeLockLevel(WritableScope.LockLevel.READING);
- ClassDescriptor companionObjectDescriptor = getCompanionObjectDescriptor();
- JetScope companionObjectAdapterScope = (companionObjectDescriptor != null) ? new CompanionObjectMixinScope(companionObjectDescriptor) : JetScope.Empty.INSTANCE$;
-
return new ChainedScope(
this,
"ScopeForMemberDeclarationResolution: " + getName(),
thisScope,
getScopeForMemberLookup(),
getScopeForClassHeaderResolution(),
- companionObjectAdapterScope,
+ getCompanionObjectScope(),
getStaticScope()
);
}
+ private JetScope getCompanionObjectScope() {
+ ClassDescriptor companionObjectDescriptor = getCompanionObjectDescriptor();
+ return (companionObjectDescriptor != null) ? new CompanionObjectMixinScope(companionObjectDescriptor) : JetScope.Empty.INSTANCE$;
+ }
+
@Override
@NotNull
public JetScope getScopeForInitializerResolution() {
@@ -346,6 +348,8 @@ private JetScope computeScopeForSecondaryConstructorHeaderResolution() {
this,
"ScopeForSecondaryConstructorHeaderResolution: " + getName(),
getScopeForClassHeaderResolution(),
+ getCompanionObjectScope(),
+ DescriptorUtils.getStaticNestedClassesScope(this),
getStaticScope()
);
}
diff --git a/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt b/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt
new file mode 100644
index 0000000000000..ec5e0bbb1e656
--- /dev/null
+++ b/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt
@@ -0,0 +1,21 @@
+class A(val result: Int) {
+ companion object {
+ fun foo(): Int = 1
+ val prop = 2
+ val C = 3
+ }
+ object B {
+ fun bar(): Int = 4
+ val prop = 5
+ }
+ object C {
+ }
+
+ constructor() : this(foo() + prop + B.bar() + B.prop + C) {}
+}
+
+fun box(): String {
+ val result = A().result
+ if (result != 15) return "fail: $result"
+ return "OK"
+}
diff --git a/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt
new file mode 100644
index 0000000000000..43a40a6e941eb
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt
@@ -0,0 +1,17 @@
+// !DIAGNOSTICS: -UNUSED_PARAMETER
+class A {
+ companion object {
+ fun foo(): Int = 1
+ val prop = 2
+ val C = 3
+ }
+ object B {
+ fun bar(): Int = 4
+ val prop = 5
+ }
+ object C {
+ }
+
+ constructor(x: Int) {}
+ constructor() : this(foo() + prop + B.bar() + B.prop + C) {}
+}
diff --git a/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt
new file mode 100644
index 0000000000000..ce9dc54bddce6
--- /dev/null
+++ b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt
@@ -0,0 +1,35 @@
+package
+
+internal final class A {
+ public constructor A()
+ public constructor A(/*0*/ x: kotlin.Int)
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+
+ internal object B {
+ private constructor B()
+ internal final val prop: kotlin.Int = 5
+ internal final fun bar(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ }
+
+ internal object C {
+ private constructor C()
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ }
+
+ internal companion object Companion {
+ private constructor Companion()
+ internal final val C: kotlin.Int = 3
+ internal final val prop: kotlin.Int = 2
+ public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean
+ internal final fun foo(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int
+ public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String
+ }
+}
diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
index c8798054dfa18..0e194f976a1c5 100644
--- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java
@@ -10587,6 +10587,12 @@ public void testClassInitializersWithoutPrimary() throws Exception {
doTest(fileName);
}
+ @TestMetadata("companionObjectScope.kt")
+ public void testCompanionObjectScope() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt");
+ doTest(fileName);
+ }
+
@TestMetadata("constructorCallType.kt")
public void testConstructorCallType() throws Exception {
String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/secondaryConstructors/constructorCallType.kt");
diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
index cff58a0734824..a6be7a9c3352f 100644
--- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
+++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java
@@ -6317,6 +6317,12 @@ public void testSyntheticVsReal() throws Exception {
@TestDataPath("$PROJECT_ROOT")
@RunWith(JUnit3RunnerWithInners.class)
public static class SecondaryConstructors extends AbstractBlackBoxCodegenTest {
+ @TestMetadata("accessToCompanion.kt")
+ public void testAccessToCompanion() throws Exception {
+ String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt");
+ doTest(fileName);
+ }
+
public void testAllFilesPresentInSecondaryConstructors() throws Exception {
JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/box/secondaryConstructors"), Pattern.compile("^(.+)\\.kt$"), true);
}
|
5ed80c40d229a48837639d717344599f60203884
|
drools
|
-fixed compilation issues, due to incorrect use of- PropagationContextImpl constructor.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@19847 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/test/java/org/drools/reteoo/ReteTest.java b/drools-core/src/test/java/org/drools/reteoo/ReteTest.java
index 644436b3dc3..77bcd408a6d 100644
--- a/drools-core/src/test/java/org/drools/reteoo/ReteTest.java
+++ b/drools-core/src/test/java/org/drools/reteoo/ReteTest.java
@@ -131,7 +131,6 @@ public void testCache() throws FactException {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -140,7 +139,7 @@ public void testCache() throws FactException {
rete.assertObject( h1,
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
- null,
+
null,
null ),
workingMemory );
@@ -183,7 +182,6 @@ public void testAssertObject() throws Exception {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -199,7 +197,6 @@ public void testAssertObject() throws Exception {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -327,7 +324,6 @@ public void testRetractObject() throws Exception {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
assertLength( 0,
@@ -345,7 +341,6 @@ public void testRetractObject() throws Exception {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -353,7 +348,6 @@ public void testRetractObject() throws Exception {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -390,7 +384,6 @@ public void testIsShadowed() {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
@@ -438,7 +431,6 @@ public void testNotShadowed() {
new PropagationContextImpl( 0,
PropagationContext.ASSERTION,
null,
- null,
null ),
workingMemory );
|
0e8fb56199a9a0d6538dab53a1edbb6f800ffd13
|
drools
|
[DROOLS-818] register declared listeners on- StatelessKieSession--
|
c
|
https://github.com/kiegroup/drools
|
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 033a34808c3..24b24aa0bbe 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
@@ -574,11 +574,10 @@ public KieSession newKieSession(String kSessionName, Environment environment, Ki
log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
return null;
}
+
KieSession kSession = kBase.newKieSession( conf != null ? conf : getKnowledgeSessionConfiguration(kSessionModel), environment );
wireListnersAndWIHs(kSessionModel, kSession);
-
registerLoggers(kSessionModel, kSession);
-
kSessions.put(kSessionName, kSession);
return kSession;
}
@@ -616,7 +615,9 @@ public StatelessKieSession newStatelessKieSession(String kSessionName, KieSessio
log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
return null;
}
+
StatelessKieSession statelessKieSession = kBase.newStatelessKieSession( conf != null ? conf : getKnowledgeSessionConfiguration(kSessionModel) );
+ wireListnersAndWIHs(kSessionModel, statelessKieSession);
registerLoggers(kSessionModel, statelessKieSession);
statelessKSessions.put(kSessionName, statelessKieSession);
return statelessKieSession;
diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/CDIHelper.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/CDIHelper.java
index f69031e2dc0..e2ea652720e 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/CDIHelper.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/kie/util/CDIHelper.java
@@ -1,14 +1,5 @@
package org.drools.compiler.kie.util;
-import java.lang.annotation.Annotation;
-import java.util.Map;
-import java.util.Set;
-
-import javax.enterprise.inject.spi.Bean;
-import javax.enterprise.inject.spi.BeanManager;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.util.MVELSafeHelper;
import org.kie.api.builder.model.KieSessionModel;
@@ -19,11 +10,20 @@
import org.kie.api.event.rule.AgendaEventListener;
import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.runtime.KieSession;
+import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.process.WorkItemHandler;
import org.mvel2.MVEL;
import org.mvel2.ParserConfiguration;
import org.mvel2.ParserContext;
+import javax.enterprise.inject.spi.Bean;
+import javax.enterprise.inject.spi.BeanManager;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import java.lang.annotation.Annotation;
+import java.util.Map;
+import java.util.Set;
+
public class CDIHelper {
public static void wireListnersAndWIHs(KieSessionModel model, KieSession kSession) {
@@ -43,17 +43,7 @@ private static void wireListnersAndWIHs(BeanCreator beanCreator, KieSessionModel
ClassLoader cl = ((InternalKnowledgeBase)kSession.getKieBase()).getRootClassLoader();
for (ListenerModel listenerModel : model.getListenerModels()) {
- Object listener;
- try {
- listener = beanCreator.createBean(cl, listenerModel.getType(), listenerModel.getQualifierModel());
- } catch (Exception e) {
- try {
- listener = fallbackBeanCreator.createBean(cl, listenerModel.getType(), listenerModel.getQualifierModel());
- } catch (Exception ex) {
- throw new RuntimeException("Cannot instance listener " + listenerModel.getType(), e);
- }
-
- }
+ Object listener = createListener( beanCreator, fallbackBeanCreator, cl, listenerModel );
switch(listenerModel.getKind()) {
case AGENDA_EVENT_LISTENER:
kSession.addEventListener((AgendaEventListener)listener);
@@ -79,7 +69,53 @@ private static void wireListnersAndWIHs(BeanCreator beanCreator, KieSessionModel
}
kSession.getWorkItemManager().registerWorkItemHandler(wihModel.getName(), wih );
}
+ }
+
+ public static void wireListnersAndWIHs(KieSessionModel model, StatelessKieSession kSession) {
+ wireListnersAndWIHs(BeanCreatorHolder.beanCreator, model, kSession);
+ }
+
+ public static void wireListnersAndWIHs(BeanManager beanManager, KieSessionModel model, StatelessKieSession kSession) {
+ wireListnersAndWIHs(new CDIBeanCreator(beanManager), model, kSession);
+ }
+
+ public static void wireListnersAndWIHs(KieSessionModel model, StatelessKieSession kSession, Map<String, Object> parameters) {
+ wireListnersAndWIHs(new MVELBeanCreator(parameters), model, kSession);
+ }
+
+ private static void wireListnersAndWIHs(BeanCreator beanCreator, KieSessionModel model, StatelessKieSession kSession) {
+ BeanCreator fallbackBeanCreator = new ReflectionBeanCreator();
+ ClassLoader cl = ((InternalKnowledgeBase)kSession.getKieBase()).getRootClassLoader();
+
+ for (ListenerModel listenerModel : model.getListenerModels()) {
+ Object listener = createListener( beanCreator, fallbackBeanCreator, cl, listenerModel );
+ switch(listenerModel.getKind()) {
+ case AGENDA_EVENT_LISTENER:
+ kSession.addEventListener((AgendaEventListener)listener);
+ break;
+ case RULE_RUNTIME_EVENT_LISTENER:
+ kSession.addEventListener((RuleRuntimeEventListener)listener);
+ break;
+ case PROCESS_EVENT_LISTENER:
+ kSession.addEventListener((ProcessEventListener)listener);
+ break;
+ }
+ }
+ }
+ private static Object createListener( BeanCreator beanCreator, BeanCreator fallbackBeanCreator, ClassLoader cl, ListenerModel listenerModel ) {
+ Object listener;
+ try {
+ listener = beanCreator.createBean(cl, listenerModel.getType(), listenerModel.getQualifierModel());
+ } catch (Exception e) {
+ try {
+ listener = fallbackBeanCreator.createBean(cl, listenerModel.getType(), listenerModel.getQualifierModel());
+ } catch (Exception ex) {
+ throw new RuntimeException("Cannot instance listener " + listenerModel.getType(), e);
+ }
+
+ }
+ return listener;
}
private static class BeanCreatorHolder {
|
a141ff2a7973b379f6b4d1aa9178f0750d6502fd
|
hbase
|
HBASE-4460 Support running an embedded- ThriftServer within a RegionServer (jgray)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1186586 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 3c242760ca14..4fa58f8e4d4b 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,5 +1,8 @@
HBase Change Log
Release 0.93.0 - Unreleased
+ NEW FEATURE
+ HBASE-4460 Support running an embedded ThriftServer within a RegionServer (jgray)
+
IMPROVEMENT
HBASE-4132 Extend the WALActionsListener API to accomodate log archival
(dhruba borthakur)
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 a7c352f27252..8e9ba6ba556f 100644
--- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -300,6 +300,9 @@ public class HRegionServer implements HRegionInterface, HBaseRPCErrorHandler,
// Cache configuration and block cache reference
private final CacheConfig cacheConfig;
+ // reference to the Thrift Server.
+ volatile private HRegionThriftServer thriftServer;
+
/**
* The server name the Master sees us as. Its made from the hostname the
* master passes us, port, and server startcode. Gets set after registration
@@ -617,6 +620,13 @@ private void initializeThreads() throws IOException {
HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD),
this.threadWakeFrequency);
+
+ // Create the thread for the ThriftServer.
+ if (conf.getBoolean("hbase.regionserver.export.thrift", false)) {
+ thriftServer = new HRegionThriftServer(this, conf);
+ thriftServer.start();
+ LOG.info("Started Thrift API from Region Server.");
+ }
}
/**
@@ -685,6 +695,7 @@ public void run() {
}
}
// Run shutdown.
+ if (this.thriftServer != null) this.thriftServer.shutdown();
this.leases.closeAfterLeasesExpire();
this.rpcServer.stop();
if (this.splitLogWorker != null) {
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionThriftServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionThriftServer.java
new file mode 100644
index 000000000000..09cd90e9600e
--- /dev/null
+++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionThriftServer.java
@@ -0,0 +1,229 @@
+/**
+ * Copyright 2011 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 java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HRegionLocation;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.NotServingRegionException;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.thrift.ThriftServer;
+import org.apache.hadoop.hbase.thrift.ThriftUtilities;
+import org.apache.hadoop.hbase.thrift.generated.Hbase;
+import org.apache.hadoop.hbase.thrift.generated.IOError;
+import org.apache.hadoop.hbase.thrift.generated.TRowResult;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.protocol.TCompactProtocol;
+import org.apache.thrift.protocol.TProtocolFactory;
+import org.apache.thrift.server.TNonblockingServer;
+import org.apache.thrift.server.TServer;
+import org.apache.thrift.server.TThreadPoolServer;
+import org.apache.thrift.transport.TFramedTransport;
+import org.apache.thrift.transport.TNonblockingServerSocket;
+import org.apache.thrift.transport.TNonblockingServerTransport;
+import org.apache.thrift.transport.TServerSocket;
+import org.apache.thrift.transport.TServerTransport;
+import org.apache.thrift.transport.TTransportFactory;
+
+/**
+ * HRegionThriftServer - this class starts up a Thrift server in the same
+ * JVM where the RegionServer is running. It inherits most of the
+ * functionality from the standard ThriftServer. This is good because
+ * we can maintain compatibility with applications that use the
+ * standard Thrift interface. For performance reasons, we can override
+ * methods to directly invoke calls into the HRegionServer and avoid the hop.
+ * <p>
+ * This can be enabled with <i>hbase.regionserver.export.thrift</i> set to true.
+ */
+public class HRegionThriftServer extends Thread {
+
+ public static final Log LOG = LogFactory.getLog(HRegionThriftServer.class);
+ public static final int DEFAULT_LISTEN_PORT = 9090;
+
+ private HRegionServer rs;
+ private Configuration conf;
+
+ private int port;
+ private boolean nonblocking;
+ private String bindIpAddress;
+ private String transport;
+ private String protocol;
+ volatile private TServer tserver;
+
+ /**
+ * Create an instance of the glue object that connects the
+ * RegionServer with the standard ThriftServer implementation
+ */
+ HRegionThriftServer(HRegionServer regionServer, Configuration conf) {
+ this.rs = regionServer;
+ this.conf = conf;
+ }
+
+ /**
+ * Inherit the Handler from the standard ThriftServer. This allows us
+ * to use the default implementation for most calls. We override certain calls
+ * for performance reasons
+ */
+ private class HBaseHandlerRegion extends ThriftServer.HBaseHandler {
+
+ HBaseHandlerRegion(final Configuration conf) throws IOException {
+ super(conf);
+ initialize(conf);
+ }
+
+ // TODO: Override more methods to short-circuit for performance
+
+ /**
+ * Get a record. Short-circuit to get better performance.
+ */
+ @Override
+ public List<TRowResult> getRowWithColumnsTs(ByteBuffer tableName,
+ ByteBuffer rowb,
+ List<ByteBuffer> columns,
+ long timestamp)
+ throws IOError {
+ try {
+ byte [] row = rowb.array();
+ HTable table = getTable(tableName.array());
+ HRegionLocation location = table.getRegionLocation(row);
+ byte[] regionName = location.getRegionInfo().getEncodedNameAsBytes();
+
+ if (columns == null) {
+ Get get = new Get(row);
+ get.setTimeRange(Long.MIN_VALUE, timestamp);
+ Result result = rs.get(regionName, get);
+ return ThriftUtilities.rowResultFromHBase(result);
+ }
+ ByteBuffer[] columnArr = columns.toArray(
+ new ByteBuffer[columns.size()]);
+ Get get = new Get(row);
+ for(ByteBuffer column : columnArr) {
+ byte [][] famAndQf = KeyValue.parseColumn(column.array());
+ if (famAndQf.length == 1) {
+ get.addFamily(famAndQf[0]);
+ } else {
+ get.addColumn(famAndQf[0], famAndQf[1]);
+ }
+ }
+ get.setTimeRange(Long.MIN_VALUE, timestamp);
+ Result result = rs.get(regionName, get);
+ return ThriftUtilities.rowResultFromHBase(result);
+ } catch (NotServingRegionException e) {
+ LOG.info("ThriftServer redirecting getRowWithColumnsTs");
+ return super.getRowWithColumnsTs(tableName, rowb, columns, timestamp);
+ } catch (IOException e) {
+ throw new IOError(e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Read and initialize config parameters
+ */
+ private void initialize(Configuration conf) {
+ this.port = conf.getInt("hbase.regionserver.thrift.port",
+ DEFAULT_LISTEN_PORT);
+ this.bindIpAddress = conf.get("hbase.regionserver.thrift.ipaddress");
+ this.protocol = conf.get("hbase.regionserver.thrift.protocol");
+ this.transport = conf.get("hbase.regionserver.thrift.transport");
+ this.nonblocking = conf.getBoolean("hbase.regionserver.thrift.nonblocking",
+ false);
+ }
+
+ /**
+ * Stop ThriftServer
+ */
+ void shutdown() {
+ if (tserver != null) {
+ tserver.stop();
+ tserver = null;
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ HBaseHandlerRegion handler = new HBaseHandlerRegion(this.conf);
+ Hbase.Processor processor = new Hbase.Processor(handler);
+
+ TProtocolFactory protocolFactory;
+ if (this.protocol != null && this.protocol.equals("compact")) {
+ protocolFactory = new TCompactProtocol.Factory();
+ } else {
+ protocolFactory = new TBinaryProtocol.Factory();
+ }
+
+ if (this.nonblocking) {
+ TNonblockingServerTransport serverTransport =
+ new TNonblockingServerSocket(this.port);
+ TFramedTransport.Factory transportFactory =
+ new TFramedTransport.Factory();
+
+ TNonblockingServer.Args serverArgs =
+ new TNonblockingServer.Args(serverTransport);
+ serverArgs.processor(processor);
+ serverArgs.transportFactory(transportFactory);
+ serverArgs.protocolFactory(protocolFactory);
+ LOG.info("starting HRegionServer Nonblocking Thrift server on " +
+ this.port);
+ LOG.info("HRegionServer Nonblocking Thrift server does not " +
+ "support address binding.");
+ tserver = new TNonblockingServer(serverArgs);
+ } else {
+ InetAddress listenAddress = null;
+ if (this.bindIpAddress != null) {
+ listenAddress = InetAddress.getByName(this.bindIpAddress);
+ } else {
+ listenAddress = InetAddress.getLocalHost();
+ }
+ TServerTransport serverTransport = new TServerSocket(
+ new InetSocketAddress(listenAddress, port));
+
+ TTransportFactory transportFactory;
+ if (this.transport != null && this.transport.equals("framed")) {
+ transportFactory = new TFramedTransport.Factory();
+ } else {
+ transportFactory = new TTransportFactory();
+ }
+
+ TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport);
+ serverArgs.processor(processor);
+ serverArgs.protocolFactory(protocolFactory);
+ serverArgs.transportFactory(transportFactory);
+ LOG.info("starting HRegionServer ThreadPool Thrift server on " +
+ listenAddress + ":" + this.port);
+ tserver = new TThreadPoolServer(serverArgs);
+ }
+ tserver.serve();
+ } catch (Exception e) {
+ LOG.warn("Unable to start HRegionServerThrift interface.", e);
+ }
+ }
+}
diff --git a/src/main/java/org/apache/hadoop/hbase/thrift/ThriftServer.java b/src/main/java/org/apache/hadoop/hbase/thrift/ThriftServer.java
index b4b49d579522..9d312f241943 100644
--- a/src/main/java/org/apache/hadoop/hbase/thrift/ThriftServer.java
+++ b/src/main/java/org/apache/hadoop/hbase/thrift/ThriftServer.java
@@ -195,12 +195,12 @@ protected synchronized ResultScanner removeScanner(int id) {
* Constructs an HBaseHandler object.
* @throws IOException
*/
- HBaseHandler()
+ protected HBaseHandler()
throws IOException {
this(HBaseConfiguration.create());
}
- HBaseHandler(final Configuration c)
+ protected HBaseHandler(final Configuration c)
throws IOException {
this.conf = c;
admin = new HBaseAdmin(conf);
|
f6bfcd9709fac61e3c4efe537f0b634bd9f6a09f
|
restlet-framework-java
|
- Continued NIO connector--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
index 79ba5f667b..5a69bb8dda 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/InboundWay.java
@@ -232,7 +232,7 @@ public void onSelected() {
if (getIoState() == IoState.READ_INTEREST) {
int result = readSocketBytes();
- while (getBuffer().hasRemaining()
+ while (getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
if (getMessageState() == MessageState.START_LINE) {
readStartLine();
@@ -241,7 +241,7 @@ public void onSelected() {
}
// Attempt to read more available bytes
- if (!getBuffer().hasRemaining()
+ if (!getByteBuffer().hasRemaining()
&& (getMessageState() != MessageState.BODY)) {
result = readSocketBytes();
}
@@ -268,8 +268,8 @@ public void onSelected() {
* @throws IOException
*/
protected Parameter readHeader() throws IOException {
- Parameter header = HeaderReader.readHeader(getBuilder());
- getBuilder().delete(0, getBuilder().length());
+ Parameter header = HeaderReader.readHeader(getLineBuilder());
+ getLineBuilder().delete(0, getLineBuilder().length());
return header;
}
@@ -349,11 +349,11 @@ protected boolean readLine() throws IOException {
boolean result = false;
int next;
- while (!result && getBuffer().hasRemaining()) {
- next = (int) getBuffer().get();
+ while (!result && getByteBuffer().hasRemaining()) {
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isCarriageReturn(next)) {
- next = (int) getBuffer().get();
+ next = (int) getByteBuffer().get();
if (HeaderUtils.isLineFeed(next)) {
result = true;
@@ -362,7 +362,7 @@ protected boolean readLine() throws IOException {
"Missing carriage return character at the end of HTTP line");
}
} else {
- getBuilder().append((char) next);
+ getLineBuilder().append((char) next);
}
}
@@ -376,9 +376,9 @@ protected boolean readLine() throws IOException {
* @throws IOException
*/
protected int readSocketBytes() throws IOException {
- getBuffer().clear();
- int result = getConnection().getSocketChannel().read(getBuffer());
- getBuffer().flip();
+ getByteBuffer().clear();
+ int result = getConnection().getSocketChannel().read(getByteBuffer());
+ getByteBuffer().flip();
return result;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
index dc6e4532d2..d2f35bda1a 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/MessageState.java
@@ -44,6 +44,9 @@ public enum MessageState {
HEADERS,
/** The body is being processed. */
- BODY;
+ BODY,
+
+ /** The end has been reached. */
+ END;
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
index a06ef2ff30..74a4f294c0 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/OutboundWay.java
@@ -237,48 +237,82 @@ public int getSocketInterestOps() {
@Override
public void onSelected() {
try {
- if (getIoState() == IoState.WRITE_INTEREST) {
- Response message = getMessage();
+ Response message = getMessage();
- if (message != null) {
- boolean canWrite = true;
+ if (message != null) {
+ boolean canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ boolean filling = getByteBuffer().hasRemaining();
- while (canWrite) {
- if (getBuffer().hasRemaining()
- && (getMessageState() != MessageState.BODY)) {
- if (getBuilder().length() == 0) {
+ while (canWrite) {
+ if (filling) {
+ // Before writing the byte buffer, we need to try
+ // to fill it as much as possible
+
+ if (getMessageState() == MessageState.BODY) {
+ // Writing the body doesn't rely on the line builder
+ // ...
+ } else {
+ // Write the start line or the headers relies on the
+ // line builder
+ if (getLineBuilder().length() == 0) {
+ // A new line can be written in the builder
writeLine();
}
- if (getBuilder().length() > 0) {
- int remaining = getBuffer().remaining();
+ if (getLineBuilder().length() > 0) {
+ // We can fill the byte buffer with the
+ // remaining line builder
+ int remaining = getByteBuffer().remaining();
- if (remaining >= getBuilder().length()) {
+ if (remaining >= getLineBuilder().length()) {
// Put the whole builder line in the buffer
- getBuffer()
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.toString()));
- getBuilder().delete(0,
- getBuilder().length());
+ getLineBuilder().delete(0,
+ getLineBuilder().length());
} else {
- // Fill the buffer with part of the builder
- // line
- getBuffer()
+ // Put the maximum number of characters
+ // into the byte buffer
+ getByteBuffer()
.put(
StringUtils
- .getLatin1Bytes(getBuilder()
+ .getLatin1Bytes(getLineBuilder()
.substring(
0,
remaining)));
- getBuilder().delete(0, remaining);
+ getLineBuilder().delete(0, remaining);
}
}
+ }
+
+ canWrite = (getIoState() == IoState.WRITE_INTEREST);
+ filling = (getMessageState() != MessageState.END)
+ && getByteBuffer().hasRemaining();
+ } else {
+ // After filling the byte buffer, we can now flip it
+ // and start draining it.
+ getByteBuffer().flip();
+ int bytesWritten = getConnection().getSocketChannel()
+ .write(getByteBuffer());
+
+ if (bytesWritten == 0) {
+ // The byte buffer hasn't been written, the socket
+ // channel can't write more. We needs to put the
+ // byte buffer in the filling state again and wait
+ // for a new NIO selection.
+ getByteBuffer().flip();
+ canWrite = false;
+ } else if (getByteBuffer().hasRemaining()) {
+ // All the buffer couldn't be written. Compact the
+ // remaining
+ // bytes so that filling can happen again.
+ getByteBuffer().compact();
} else {
- getBuffer().flip();
- canWrite = (getConnection().getSocketChannel()
- .write(getBuffer()) > 0);
+ // The byte buffer has been fully written, but the
+ // socket channel wants more.
}
}
@@ -493,18 +527,18 @@ protected boolean writeLine() throws IOException {
if (getHeaderIndex() < getHeaders().size()) {
// Write header
Parameter header = getHeaders().get(getHeaderIndex());
- getBuilder().append(header.getName());
- getBuilder().append(": ");
- getBuilder().append(header.getValue());
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append(header.getName());
+ getLineBuilder().append(": ");
+ getLineBuilder().append(header.getValue());
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Move to the next header
setHeaderIndex(getHeaderIndex() + 1);
} else {
// Write the end of the headers section
- getBuilder().append('\r'); // CR
- getBuilder().append('\n'); // LF
+ getLineBuilder().append('\r'); // CR
+ getLineBuilder().append('\n'); // LF
// Change state
setMessageState(MessageState.BODY);
@@ -530,18 +564,19 @@ protected void writeStartLine() throws IOException {
String protocolVersion = protocol.getVersion();
String version = protocol.getTechnicalName() + '/'
+ ((protocolVersion == null) ? "1.1" : protocolVersion);
- getBuilder().append(version);
- getBuilder().append(' ');
- getBuilder().append(getMessage().getStatus().getCode());
- getBuilder().append(' ');
+ getLineBuilder().append(version);
+ getLineBuilder().append(' ');
+ getLineBuilder().append(getMessage().getStatus().getCode());
+ getLineBuilder().append(' ');
if (getMessage().getStatus().getDescription() != null) {
- getBuilder().append(getMessage().getStatus().getDescription());
+ getLineBuilder().append(getMessage().getStatus().getDescription());
} else {
- getBuilder().append("Status " + getMessage().getStatus().getCode());
+ getLineBuilder().append(
+ "Status " + getMessage().getStatus().getCode());
}
- getBuilder().append("\r\n");
+ getLineBuilder().append("\r\n");
}
}
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
index 27cdf3577f..f903b7a56b 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/ServerInboundWay.java
@@ -67,7 +67,7 @@ protected void readStartLine() throws IOException {
int i = 0;
int start = 0;
- int size = getBuilder().length();
+ int size = getLineBuilder().length();
char next;
if (size == 0) {
@@ -75,10 +75,10 @@ protected void readStartLine() throws IOException {
} else {
// Parse the request method
for (i = start; (requestMethod == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestMethod = getBuilder().substring(start, i);
+ requestMethod = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -90,10 +90,10 @@ protected void readStartLine() throws IOException {
// Parse the request URI
for (i = start; (requestUri == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
if (HeaderUtils.isSpace(next)) {
- requestUri = getBuilder().substring(start, i);
+ requestUri = getLineBuilder().substring(start, i);
start = i + 1;
}
}
@@ -109,11 +109,11 @@ protected void readStartLine() throws IOException {
// Parse the protocol version
for (i = start; (version == null) && (i < size); i++) {
- next = getBuilder().charAt(i);
+ next = getLineBuilder().charAt(i);
}
if (i == size) {
- version = getBuilder().substring(start, i);
+ version = getLineBuilder().substring(start, i);
start = i + 1;
}
@@ -129,7 +129,7 @@ protected void readStartLine() throws IOException {
setMessage(response);
setMessageState(MessageState.HEADERS);
- getBuilder().delete(0, getBuilder().length());
+ getLineBuilder().delete(0, getLineBuilder().length());
}
} else {
// We need more characters before parsing
diff --git a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
index 05f73ebf0d..be76f5b3a9 100644
--- a/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
+++ b/incubator/org.restlet.engine.nio/src/org/restlet/engine/nio/Way.java
@@ -51,10 +51,7 @@
public abstract class Way {
/** The byte buffer. */
- private final ByteBuffer buffer;
-
- /** The line builder. */
- private final StringBuilder builder;
+ private final ByteBuffer byteBuffer;
/** The parent connection. */
private final Connection<?> connection;
@@ -62,6 +59,9 @@ public abstract class Way {
/** The IO state. */
private volatile IoState ioState;
+ /** The line builder. */
+ private final StringBuilder lineBuilder;
+
/** The current message exchanged. */
private volatile Response message;
@@ -84,8 +84,8 @@ public abstract class Way {
* The parent connection.
*/
public Way(Connection<?> connection) {
- this.buffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
- this.builder = new StringBuilder();
+ this.byteBuffer = ByteBuffer.allocate(NioUtils.BUFFER_SIZE);
+ this.lineBuilder = new StringBuilder();
this.connection = connection;
this.messageState = MessageState.START_LINE;
this.ioState = IoState.IDLE;
@@ -99,17 +99,8 @@ public Way(Connection<?> connection) {
*
* @return The byte buffer.
*/
- protected ByteBuffer getBuffer() {
- return buffer;
- }
-
- /**
- * Returns the line builder.
- *
- * @return The line builder.
- */
- protected StringBuilder getBuilder() {
- return builder;
+ protected ByteBuffer getByteBuffer() {
+ return byteBuffer;
}
/**
@@ -139,6 +130,15 @@ protected IoState getIoState() {
return ioState;
}
+ /**
+ * Returns the line builder.
+ *
+ * @return The line builder.
+ */
+ protected StringBuilder getLineBuilder() {
+ return lineBuilder;
+ }
+
/**
* Returns the logger.
*
|
595cdf05e962299c19c34bbfb370316636d074f2
|
spring-framework
|
Polishing--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java
index a4eea3e1e614..4c7b5fcfa7fb 100644
--- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java
+++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/JtaTransactionAspectsTests.java
@@ -17,7 +17,6 @@
package org.springframework.transaction.aspectj;
import java.io.IOException;
-
import javax.transaction.Transactional;
import org.junit.Before;
@@ -132,6 +131,7 @@ public void echo(Throwable t) throws Throwable {
}
+
protected static class JtaAnnotationProtectedAnnotatedMember {
public void doSomething() {
@@ -143,6 +143,7 @@ protected void doInTransaction() {
}
}
+
protected static class JtaAnnotationPrivateAnnotatedMember {
public void doSomething() {
@@ -154,6 +155,7 @@ private void doInTransaction() {
}
}
+
@Configuration
protected static class Config {
@@ -168,7 +170,6 @@ public JtaAnnotationTransactionAspect transactionAspect() {
aspect.setTransactionManager(transactionManager());
return aspect;
}
-
}
}
diff --git a/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
index 855ef022fdf8..2a6c53e08767 100644
--- a/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
+++ b/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java
@@ -22,6 +22,7 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
+import java.lang.reflect.UndeclaredThrowableException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -1179,7 +1180,12 @@ public Object run() throws Exception {
throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
}
else {
- throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
+ Throwable cause = ex.getTargetException();
+ if (cause instanceof UndeclaredThrowableException) {
+ // May happen e.g. with Groovy-generated methods
+ cause = cause.getCause();
+ }
+ throw new MethodInvocationException(propertyChangeEvent, cause);
}
}
catch (Exception ex) {
diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/EnableCaching.java b/spring-context/src/main/java/org/springframework/cache/annotation/EnableCaching.java
index 5be298494293..5086c1a1df46 100644
--- a/spring-context/src/main/java/org/springframework/cache/annotation/EnableCaching.java
+++ b/spring-context/src/main/java/org/springframework/cache/annotation/EnableCaching.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 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.
@@ -162,13 +162,12 @@
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}. <strong>
* Applicable only if {@link #mode()} is set to {@link AdviceMode#PROXY}</strong>.
- *
* <p>Note that setting this attribute to {@code true} will affect <em>all</em>
- * Spring-managed beans requiring proxying, not just those marked with
- * {@code @Cacheable}. For example, other beans marked with Spring's
- * {@code @Transactional} annotation will be upgraded to subclass proxying at the same
- * time. This approach has no negative impact in practice unless one is explicitly
- * expecting one type of proxy vs another, e.g. in tests.
+ * Spring-managed beans requiring proxying, not just those marked with {@code @Cacheable}.
+ * For example, other beans marked with Spring's {@code @Transactional} annotation will
+ * be upgraded to subclass proxying at the same time. This approach has no negative
+ * impact in practice unless one is explicitly expecting one type of proxy vs another,
+ * e.g. in tests.
*/
boolean proxyTargetClass() default false;
@@ -185,4 +184,5 @@
* The default is {@link Ordered#LOWEST_PRECEDENCE}.
*/
int order() default Ordered.LOWEST_PRECEDENCE;
+
}
diff --git a/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java
index fdaa876c0808..b13527543c27 100644
--- a/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java
+++ b/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2013 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.
@@ -24,7 +24,6 @@
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
-import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
@@ -102,7 +101,7 @@ public GroovyScriptFactory(String scriptSourceLocator, GroovyObjectCustomizer gr
@Override
- public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
+ public void setBeanFactory(BeanFactory beanFactory) {
if (beanFactory instanceof ConfigurableListableBeanFactory) {
((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);
}
diff --git a/spring-context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java b/spring-context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java
index 01e3c2069231..156e322e0252 100644
--- a/spring-context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java
+++ b/spring-context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2013 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.
@@ -94,7 +94,7 @@
* <property name="message" value="Hello World!"/>
* </bean>
*
- * <bean id="groovyMessenger" class="org.springframework.scripting.bsh.GroovyScriptFactory">
+ * <bean id="groovyMessenger" class="org.springframework.scripting.groovy.GroovyScriptFactory">
* <constructor-arg value="classpath:mypackage/Messenger.groovy"/>
* <property name="message" value="Hello World!"/>
* </bean></pre>
@@ -346,17 +346,16 @@ public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName
* @param scriptedObjectBeanName the name of the internal scripted object bean
*/
protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanName, String scriptedObjectBeanName) {
-
// Avoid recreation of the script bean definition in case of a prototype.
synchronized (this.scriptBeanFactory) {
if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {
- this.scriptBeanFactory.registerBeanDefinition(scriptFactoryBeanName,
- createScriptFactoryBeanDefinition(bd));
- ScriptFactory scriptFactory = this.scriptBeanFactory
- .getBean(scriptFactoryBeanName, ScriptFactory.class);
- ScriptSource scriptSource = getScriptSource(scriptFactoryBeanName,
- scriptFactory.getScriptSourceLocator());
+ this.scriptBeanFactory.registerBeanDefinition(
+ scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
+ ScriptFactory scriptFactory =
+ this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
+ ScriptSource scriptSource =
+ getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
Class<?>[] interfaces = scriptFactory.getScriptInterfaces();
Class<?>[] scriptedInterfaces = interfaces;
@@ -365,8 +364,8 @@ protected void prepareScriptBeans(BeanDefinition bd, String scriptFactoryBeanNam
scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface);
}
- BeanDefinition objectBd = createScriptedObjectBeanDefinition(bd, scriptFactoryBeanName, scriptSource,
- scriptedInterfaces);
+ BeanDefinition objectBd = createScriptedObjectBeanDefinition(
+ bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
long refreshCheckDelay = resolveRefreshCheckDelay(bd);
if (refreshCheckDelay >= 0) {
objectBd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
@@ -569,7 +568,7 @@ protected Object createRefreshableProxy(TargetSource ts, Class<?>[] interfaces,
proxyFactory.setInterfaces(interfaces);
if (proxyTargetClass) {
classLoader = null; // force use of Class.getClassLoader()
- proxyFactory.setProxyTargetClass(proxyTargetClass);
+ proxyFactory.setProxyTargetClass(true);
}
DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
|
895ccff4f350d1e8c7acc121bb9bb118e164adfa
|
hbase
|
Fixing broken build... forgot to add- JVMClusterUtil, etc.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@939848 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/contrib/stargate/core/src/test/java/org/apache/hadoop/hbase/stargate/MiniClusterTestBase.java b/contrib/stargate/core/src/test/java/org/apache/hadoop/hbase/stargate/MiniClusterTestBase.java
index 939d2475f491..24600c5bc552 100644
--- a/contrib/stargate/core/src/test/java/org/apache/hadoop/hbase/stargate/MiniClusterTestBase.java
+++ b/contrib/stargate/core/src/test/java/org/apache/hadoop/hbase/stargate/MiniClusterTestBase.java
@@ -35,6 +35,7 @@
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.util.FSUtils;
+import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.util.StringUtils;
import org.apache.log4j.Level;
diff --git a/contrib/transactional/src/test/java/org/apache/hadoop/hbase/regionserver/transactional/TestTHLogRecovery.java b/contrib/transactional/src/test/java/org/apache/hadoop/hbase/regionserver/transactional/TestTHLogRecovery.java
index 09b7d983495b..192ce69775a9 100644
--- a/contrib/transactional/src/test/java/org/apache/hadoop/hbase/regionserver/transactional/TestTHLogRecovery.java
+++ b/contrib/transactional/src/test/java/org/apache/hadoop/hbase/regionserver/transactional/TestTHLogRecovery.java
@@ -47,6 +47,7 @@
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.JVMClusterUtil;
public class TestTHLogRecovery extends HBaseClusterTestCase {
private static final Log LOG = LogFactory.getLog(TestTHLogRecovery.class);
@@ -141,8 +142,8 @@ public void testWithFlushBeforeCommit() throws IOException,
// }
private void flushRegionServer() {
- List<LocalHBaseCluster.RegionServerThread> regionThreads = cluster
- .getRegionThreads();
+ List<JVMClusterUtil.RegionServerThread> regionThreads = cluster
+ .getRegionServerThreads();
HRegion region = null;
int server = -1;
@@ -171,8 +172,8 @@ private void flushRegionServer() {
* just shut down.
*/
private void stopOrAbortRegionServer(final boolean abort) {
- List<LocalHBaseCluster.RegionServerThread> regionThreads = cluster
- .getRegionThreads();
+ List<JVMClusterUtil.RegionServerThread> regionThreads = cluster
+ .getRegionServerThreads();
int server = -1;
for (int i = 0; i < regionThreads.size(); i++) {
diff --git a/core/src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java b/core/src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java
new file mode 100644
index 000000000000..40e993764aef
--- /dev/null
+++ b/core/src/main/java/org/apache/hadoop/hbase/util/JVMClusterUtil.java
@@ -0,0 +1,162 @@
+/**
+ * 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.util;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.master.HMaster;
+import org.apache.hadoop.hbase.regionserver.HRegionServer;
+
+/**
+ * Utility used running a cluster all in the one JVM.
+ */
+public class JVMClusterUtil {
+ private static final Log LOG = LogFactory.getLog(JVMClusterUtil.class);
+
+ /**
+ * Datastructure to hold RegionServer Thread and RegionServer instance
+ */
+ public static class RegionServerThread extends Thread {
+ private final HRegionServer regionServer;
+
+ public RegionServerThread(final HRegionServer r, final int index) {
+ super(r, "RegionServer:" + index);
+ this.regionServer = r;
+ }
+
+ /** @return the region server */
+ public HRegionServer getRegionServer() {
+ return this.regionServer;
+ }
+
+ /**
+ * Block until the region server has come online, indicating it is ready
+ * to be used.
+ */
+ public void waitForServerOnline() {
+ while (!regionServer.isOnline()) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // continue waiting
+ }
+ }
+ }
+ }
+
+ /**
+ * Creates a {@link RegionServerThread}.
+ * Call 'start' on the returned thread to make it run.
+ * @param c Configuration to use.
+ * @param hrsc Class to create.
+ * @param index Used distingushing the object returned.
+ * @throws IOException
+ * @return Region server added.
+ */
+ public static JVMClusterUtil.RegionServerThread createRegionServerThread(final HBaseConfiguration c,
+ final Class<? extends HRegionServer> hrsc, final int index)
+ throws IOException {
+ HRegionServer server;
+ try {
+ server = hrsc.getConstructor(HBaseConfiguration.class).newInstance(c);
+ } catch (Exception e) {
+ IOException ioe = new IOException();
+ ioe.initCause(e);
+ throw ioe;
+ }
+ return new JVMClusterUtil.RegionServerThread(server, index);
+ }
+
+ /**
+ * Start the cluster.
+ * @param m
+ * @param regionServers
+ * @return Address to use contacting master.
+ */
+ public static String startup(final HMaster m,
+ final List<JVMClusterUtil.RegionServerThread> regionservers) {
+ if (m != null) m.start();
+ if (regionservers != null) {
+ for (JVMClusterUtil.RegionServerThread t: regionservers) {
+ t.start();
+ }
+ }
+ return m == null? null: m.getMasterAddress().toString();
+ }
+
+ /**
+ * @param master
+ * @param regionservers
+ */
+ public static void shutdown(final HMaster master,
+ final List<RegionServerThread> regionservers) {
+ LOG.debug("Shutting down HBase Cluster");
+ // Be careful how the hdfs shutdown thread runs in context where more than
+ // one regionserver in the mix.
+ Thread hdfsClientFinalizer = null;
+ for (JVMClusterUtil.RegionServerThread t: regionservers) {
+ Thread tt = t.getRegionServer().setHDFSShutdownThreadOnExit(null);
+ if (hdfsClientFinalizer == null && tt != null) {
+ hdfsClientFinalizer = tt;
+ }
+ }
+ if (master != null) {
+ master.shutdown();
+ }
+ // regionServerThreads can never be null because they are initialized when
+ // the class is constructed.
+ for(Thread t: regionservers) {
+ if (t.isAlive()) {
+ try {
+ t.join();
+ } catch (InterruptedException e) {
+ // continue
+ }
+ }
+ }
+ if (master != null) {
+ while (master.isAlive()) {
+ try {
+ // The below has been replaced to debug sometime hangs on end of
+ // tests.
+ // this.master.join():
+ Threads.threadDumpingIsAlive(master);
+ } catch(InterruptedException e) {
+ // continue
+ }
+ }
+ }
+ if (hdfsClientFinalizer != null) {
+ // Don't run the shutdown thread. Plays havoc if we try to start a
+ // minihbasecluster immediately after this one has gone down (In
+ // Filesystem, the shutdown thread is kept in a static and is created
+ // on classloading. Can only run it once).
+ // hdfsClientFinalizer.start();
+ // Threads.shutdown(hdfsClientFinalizer);
+ }
+ LOG.info("Shutdown " +
+ ((regionservers != null)? master.getName(): "0 masters") +
+ " " + regionservers.size() + " region server(s)");
+ }
+}
\ No newline at end of file
|
7cd667c0e3e17f0362153cd15536e26eeb4f97a0
|
kotlin
|
Removed unused methods from KtScope.--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt
index eae59af6bf7f1..ec3f3d210fca2 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt
+++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tasks/dynamicCalls.kt
@@ -28,7 +28,6 @@ import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.calls.tasks.collectors.CallableDescriptorCollector
import org.jetbrains.kotlin.resolve.calls.tasks.collectors.CallableDescriptorCollectors
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
-import org.jetbrains.kotlin.resolve.scopes.KtScope
import org.jetbrains.kotlin.resolve.scopes.KtScopeImpl
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.receivers.TransientReceiver
diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt
index efda8105e7c14..9cc3cfc0e74c6 100644
--- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt
+++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaClassMemberScope.kt
@@ -19,14 +19,16 @@ package org.jetbrains.kotlin.load.java.lazy.descriptors
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
-import org.jetbrains.kotlin.descriptors.impl.*
+import org.jetbrains.kotlin.descriptors.impl.ConstructorDescriptorImpl
+import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor
+import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.*
-import org.jetbrains.kotlin.load.java.BuiltinSpecialProperties.getBuiltinSpecialPropertyGetterName
-import org.jetbrains.kotlin.load.java.BuiltinMethodsWithDifferentJvmName.sameAsRenamedInJvmBuiltin
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithDifferentJvmName.isRemoveAtByIndex
+import org.jetbrains.kotlin.load.java.BuiltinMethodsWithDifferentJvmName.sameAsRenamedInJvmBuiltin
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature.sameAsBuiltinMethodWithErasedValueParameters
+import org.jetbrains.kotlin.load.java.BuiltinSpecialProperties.getBuiltinSpecialPropertyGetterName
import org.jetbrains.kotlin.load.java.components.DescriptorResolverUtils
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.descriptors.JavaConstructorDescriptor
@@ -38,7 +40,6 @@ import org.jetbrains.kotlin.load.java.lazy.child
import org.jetbrains.kotlin.load.java.lazy.resolveAnnotations
import org.jetbrains.kotlin.load.java.lazy.types.RawSubstitution
import org.jetbrains.kotlin.load.java.lazy.types.toAttributes
-import org.jetbrains.kotlin.load.java.sources.JavaSourceElement
import org.jetbrains.kotlin.load.java.structure.JavaArrayType
import org.jetbrains.kotlin.load.java.structure.JavaClass
import org.jetbrains.kotlin.load.java.structure.JavaConstructor
@@ -630,10 +631,6 @@ public class LazyJavaClassMemberScope(
}
}
- // TODO
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> = listOf()
-
-
override fun getContainingDeclaration() = super.getContainingDeclaration() as ClassDescriptor
// namespaces should be resolved elsewhere
diff --git a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaStaticScope.kt b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaStaticScope.kt
index d9522fafdfbe5..f1925e07977e2 100644
--- a/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaStaticScope.kt
+++ b/core/descriptor.loader.java/src/org/jetbrains/kotlin/load/java/lazy/descriptors/LazyJavaStaticScope.kt
@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.load.java.lazy.descriptors
import org.jetbrains.kotlin.descriptors.ClassOrPackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
-import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext
import org.jetbrains.kotlin.load.java.structure.JavaMethod
@@ -37,8 +36,6 @@ public abstract class LazyJavaStaticScope(
override fun getPackage(name: Name) = null
abstract fun getSubPackages(): Collection<FqName>
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> = listOf()
-
override fun resolveMethodSignature(
method: JavaMethod, methodTypeParameters: List<TypeParameterDescriptor>, returnType: KotlinType,
valueParameters: LazyJavaScope.ResolvedValueParameters
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt
index 19ca372ab8a77..c9c14a05b512a 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/AbstractScopeAdapter.kt
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.Printer
/**
@@ -34,10 +33,6 @@ public abstract class AbstractScopeAdapter : KtScope {
else
workerScope
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> {
- return workerScope.getImplicitReceiversHierarchy()
- }
-
override fun getFunctions(name: Name, location: LookupLocation): Collection<FunctionDescriptor> {
return workerScope.getFunctions(name, location)
}
@@ -54,34 +49,10 @@ public abstract class AbstractScopeAdapter : KtScope {
return workerScope.getProperties(name, location)
}
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor> {
- return workerScope.getSyntheticExtensionProperties(receiverTypes, name, location)
- }
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor> {
- return workerScope.getSyntheticExtensionFunctions(receiverTypes, name, location)
- }
-
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor> {
- return workerScope.getSyntheticExtensionProperties(receiverTypes)
- }
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor> {
- return workerScope.getSyntheticExtensionFunctions(receiverTypes)
- }
-
- override fun getLocalVariable(name: Name): VariableDescriptor? {
- return workerScope.getLocalVariable(name)
- }
-
override fun getContainingDeclaration(): DeclarationDescriptor {
return workerScope.getContainingDeclaration()
}
- override fun getDeclarationsByLabel(labelName: Name): Collection<DeclarationDescriptor> {
- return workerScope.getDeclarationsByLabel(labelName)
- }
-
override fun getDescriptors(kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> {
return workerScope.getDescriptors(kindFilter, nameFilter)
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedScope.kt
index 050756d1691b2..6c8e2f83ea5f4 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedScope.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/ChainedScope.kt
@@ -19,11 +19,9 @@ package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.collectionUtils.getFirstMatch
import org.jetbrains.kotlin.util.collectionUtils.getFromAllScopes
import org.jetbrains.kotlin.utils.Printer
-import java.util.ArrayList
public open class ChainedScope(
private val containingDeclaration: DeclarationDescriptor?/* it's nullable as a hack for TypeUtils.intersect() */,
@@ -31,7 +29,6 @@ public open class ChainedScope(
vararg scopes: KtScope
) : KtScope {
private val scopeChain = scopes.clone()
- private var implicitReceiverHierarchy: List<ReceiverParameterDescriptor>? = null
override fun getClassifier(name: Name, location: LookupLocation): ClassifierDescriptor?
= getFirstMatch(scopeChain) { it.getClassifier(name, location) }
@@ -42,38 +39,11 @@ public open class ChainedScope(
override fun getProperties(name: Name, location: LookupLocation): Collection<VariableDescriptor>
= getFromAllScopes(scopeChain) { it.getProperties(name, location) }
- override fun getLocalVariable(name: Name): VariableDescriptor?
- = getFirstMatch(scopeChain) { it.getLocalVariable(name) }
-
override fun getFunctions(name: Name, location: LookupLocation): Collection<FunctionDescriptor>
= getFromAllScopes(scopeChain) { it.getFunctions(name, location) }
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor>
- = getFromAllScopes(scopeChain) { it.getSyntheticExtensionProperties(receiverTypes, name, location) }
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor>
- = getFromAllScopes(scopeChain) { it.getSyntheticExtensionFunctions(receiverTypes, name, location) }
-
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor>
- = getFromAllScopes(scopeChain) { it.getSyntheticExtensionProperties(receiverTypes) }
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor>
- = getFromAllScopes(scopeChain) { it.getSyntheticExtensionFunctions(receiverTypes) }
-
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> {
- if (implicitReceiverHierarchy == null) {
- val result = ArrayList<ReceiverParameterDescriptor>()
- scopeChain.flatMapTo(result) { it.getImplicitReceiversHierarchy() }
- result.trimToSize()
- implicitReceiverHierarchy = result
- }
- return implicitReceiverHierarchy!!
- }
-
override fun getContainingDeclaration(): DeclarationDescriptor = containingDeclaration!!
- override fun getDeclarationsByLabel(labelName: Name) = scopeChain.flatMap { it.getDeclarationsByLabel(labelName) }
-
override fun getDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean)
= getFromAllScopes(scopeChain) { it.getDescriptors(kindFilter, nameFilter) }
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/FilteringScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/FilteringScope.kt
index a210b6e050479..8cf152027dbdd 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/FilteringScope.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/FilteringScope.kt
@@ -17,11 +17,8 @@
package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
-import org.jetbrains.kotlin.descriptors.FunctionDescriptor
-import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.Printer
public class FilteringScope(private val workerScope: KtScope, private val predicate: (DeclarationDescriptor) -> Boolean) : KtScope {
@@ -39,27 +36,9 @@ public class FilteringScope(private val workerScope: KtScope, private val predic
override fun getProperties(name: Name, location: LookupLocation) = workerScope.getProperties(name, location).filter(predicate)
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor>
- = workerScope.getSyntheticExtensionProperties(receiverTypes, name, location).filter(predicate)
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor>
- = workerScope.getSyntheticExtensionFunctions(receiverTypes, name, location).filter(predicate)
-
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor>
- = workerScope.getSyntheticExtensionProperties(receiverTypes).filter(predicate)
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor>
- = workerScope.getSyntheticExtensionFunctions(receiverTypes).filter(predicate)
-
- override fun getLocalVariable(name: Name) = filterDescriptor(workerScope.getLocalVariable(name))
-
override fun getDescriptors(kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean) = workerScope.getDescriptors(kindFilter, nameFilter).filter(predicate)
- override fun getImplicitReceiversHierarchy() = workerScope.getImplicitReceiversHierarchy()
-
- override fun getDeclarationsByLabel(labelName: Name) = workerScope.getDeclarationsByLabel(labelName).filter(predicate)
-
override fun getOwnDeclaredDescriptors() = workerScope.getOwnDeclaredDescriptors().filter(predicate)
override fun printScopeStructure(p: Printer) {
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScope.kt
index 9358183c8f028..c67f88c5e500c 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScope.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScope.kt
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.toReadOnlyList
import java.lang.reflect.Modifier
@@ -28,24 +27,15 @@ public interface KtScope {
public fun getClassifier(name: Name, location: LookupLocation): ClassifierDescriptor?
+ @Deprecated("Should be removed soon")
public fun getPackage(name: Name): PackageViewDescriptor?
public fun getProperties(name: Name, location: LookupLocation): Collection<VariableDescriptor>
- public fun getLocalVariable(name: Name): VariableDescriptor?
-
public fun getFunctions(name: Name, location: LookupLocation): Collection<FunctionDescriptor>
- public fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor>
- public fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor>
-
- public fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor>
- public fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor>
-
public fun getContainingDeclaration(): DeclarationDescriptor
- public fun getDeclarationsByLabel(labelName: Name): Collection<DeclarationDescriptor>
-
/**
* All visible descriptors from current scope.
*
@@ -62,11 +52,7 @@ public interface KtScope {
nameFilter: (Name) -> Boolean = ALL_NAME_FILTER
): Collection<DeclarationDescriptor>
- /**
- * Adds receivers to the list in order of locality, so that the closest (the most local) receiver goes first
- */
- public fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor>
-
+ // todo merge with getAllDescriptors()
public fun getOwnDeclaredDescriptors(): Collection<DeclarationDescriptor>
/**
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScopeImpl.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScopeImpl.kt
index 2c3ae58325a6f..b8a366a50b135 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScopeImpl.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/KtScopeImpl.kt
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.Printer
abstract class KtScopeImpl : KtScope {
@@ -27,25 +26,13 @@ abstract class KtScopeImpl : KtScope {
override fun getProperties(name: Name, location: LookupLocation): Collection<VariableDescriptor> = emptyList()
- override fun getLocalVariable(name: Name): VariableDescriptor? = null
-
override fun getPackage(name: Name): PackageViewDescriptor? = null
override fun getFunctions(name: Name, location: LookupLocation): Collection<FunctionDescriptor> = emptyList()
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor> = emptyList()
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor> = emptyList()
-
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor> = emptyList()
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor> = emptyList()
-
- override fun getDeclarationsByLabel(labelName: Name): Collection<DeclarationDescriptor> = emptyList()
-
override fun getDescriptors(kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean): Collection<DeclarationDescriptor> = emptyList()
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> = emptyList()
-
override fun getOwnDeclaredDescriptors(): Collection<DeclarationDescriptor> = emptyList()
// This method should not be implemented here by default: every scope class has its unique structure pattern
diff --git a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt
index 2f2c146d4ea58..52d402f4f4e1d 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt
+++ b/core/descriptors/src/org/jetbrains/kotlin/resolve/scopes/SubstitutingScope.kt
@@ -17,16 +17,12 @@
package org.jetbrains.kotlin.resolve.scopes
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
-import org.jetbrains.kotlin.descriptors.FunctionDescriptor
-import org.jetbrains.kotlin.descriptors.PropertyDescriptor
-import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
-import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.utils.Printer
import org.jetbrains.kotlin.utils.newHashSetWithExpectedSize
-import java.util.HashMap
+import java.util.*
public class SubstitutingScope(private val workerScope: KtScope, private val substitutor: TypeSubstitutor) : KtScope {
@@ -65,36 +61,14 @@ public class SubstitutingScope(private val workerScope: KtScope, private val sub
override fun getProperties(name: Name, location: LookupLocation) = substitute(workerScope.getProperties(name, location))
- override fun getLocalVariable(name: Name) = substitute(workerScope.getLocalVariable(name))
-
override fun getClassifier(name: Name, location: LookupLocation) = substitute(workerScope.getClassifier(name, location))
override fun getFunctions(name: Name, location: LookupLocation) = substitute(workerScope.getFunctions(name, location))
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<PropertyDescriptor>
- = substitute(workerScope.getSyntheticExtensionProperties(receiverTypes, name, location))
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>, name: Name, location: LookupLocation): Collection<FunctionDescriptor>
- = substitute(workerScope.getSyntheticExtensionFunctions(receiverTypes, name, location))
-
- override fun getSyntheticExtensionProperties(receiverTypes: Collection<KotlinType>): Collection<PropertyDescriptor>
- = substitute(workerScope.getSyntheticExtensionProperties(receiverTypes))
-
- override fun getSyntheticExtensionFunctions(receiverTypes: Collection<KotlinType>): Collection<FunctionDescriptor>
- = substitute(workerScope.getSyntheticExtensionFunctions(receiverTypes))
-
override fun getPackage(name: Name) = workerScope.getPackage(name)
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> {
- throw UnsupportedOperationException() // TODO
- }
-
override fun getContainingDeclaration() = workerScope.getContainingDeclaration()
- override fun getDeclarationsByLabel(labelName: Name): Collection<DeclarationDescriptor> {
- throw UnsupportedOperationException() // TODO
- }
-
override fun getDescriptors(kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean) = _allDescriptors
diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/ErrorUtils.java b/core/descriptors/src/org/jetbrains/kotlin/types/ErrorUtils.java
index 1dd9c55152c0d..9eda07eefd8d9 100644
--- a/core/descriptors/src/org/jetbrains/kotlin/types/ErrorUtils.java
+++ b/core/descriptors/src/org/jetbrains/kotlin/types/ErrorUtils.java
@@ -179,54 +179,11 @@ public Set<VariableDescriptor> getProperties(@NotNull Name name, @NotNull Lookup
return ERROR_VARIABLE_GROUP;
}
- @NotNull
- @Override
- public Collection<PropertyDescriptor> getSyntheticExtensionProperties(
- @NotNull Collection<? extends KotlinType> receiverTypes, @NotNull Name name,
- @NotNull LookupLocation location
- ) {
- return ERROR_PROPERTY_GROUP;
- }
-
- @NotNull
- @Override
- public Collection<FunctionDescriptor> getSyntheticExtensionFunctions(
- @NotNull Collection<? extends KotlinType> receiverTypes, @NotNull Name name,
- @NotNull LookupLocation location
- ) {
- return Collections.<FunctionDescriptor>singleton(createErrorFunction(this));
- }
-
- @NotNull
- @Override
- public Collection<PropertyDescriptor> getSyntheticExtensionProperties(@NotNull Collection<? extends KotlinType> receiverTypes) {
- return ERROR_PROPERTY_GROUP;
- }
-
- @NotNull
- @Override
- public Collection<FunctionDescriptor> getSyntheticExtensionFunctions(
- @NotNull Collection<? extends KotlinType> receiverTypes
- ) {
- return Collections.<FunctionDescriptor>singleton(createErrorFunction(this));
- }
-
- @Override
- public VariableDescriptor getLocalVariable(@NotNull Name name) {
- return ERROR_PROPERTY;
- }
-
@Override
public PackageViewDescriptor getPackage(@NotNull Name name) {
return null;
}
- @NotNull
- @Override
- public List<ReceiverParameterDescriptor> getImplicitReceiversHierarchy() {
- return Collections.emptyList();
- }
-
@NotNull
@Override
public Set<FunctionDescriptor> getFunctions(@NotNull Name name, @NotNull LookupLocation location) {
@@ -239,12 +196,6 @@ public DeclarationDescriptor getContainingDeclaration() {
return ERROR_MODULE;
}
- @NotNull
- @Override
- public Collection<DeclarationDescriptor> getDeclarationsByLabel(@NotNull Name labelName) {
- return Collections.emptyList();
- }
-
@NotNull
@Override
public Collection<DeclarationDescriptor> getDescriptors(
@@ -301,62 +252,18 @@ public Collection<VariableDescriptor> getProperties(@NotNull Name name, @NotNull
throw new IllegalStateException();
}
- @Nullable
- @Override
- public VariableDescriptor getLocalVariable(@NotNull Name name) {
- throw new IllegalStateException();
- }
-
@NotNull
@Override
public Collection<FunctionDescriptor> getFunctions(@NotNull Name name, @NotNull LookupLocation location) {
throw new IllegalStateException();
}
- @NotNull
- @Override
- public Collection<PropertyDescriptor> getSyntheticExtensionProperties(
- @NotNull Collection<? extends KotlinType> receiverTypes, @NotNull Name name,
- @NotNull LookupLocation location
- ) {
- throw new IllegalStateException();
- }
-
- @NotNull
- @Override
- public Collection<FunctionDescriptor> getSyntheticExtensionFunctions(
- @NotNull Collection<? extends KotlinType> receiverTypes, @NotNull Name name,
- @NotNull LookupLocation location
- ) {
- throw new IllegalStateException();
- }
-
- @NotNull
- @Override
- public Collection<PropertyDescriptor> getSyntheticExtensionProperties(@NotNull Collection<? extends KotlinType> receiverTypes) {
- throw new IllegalStateException();
- }
-
- @NotNull
- @Override
- public Collection<FunctionDescriptor> getSyntheticExtensionFunctions(
- @NotNull Collection<? extends KotlinType> receiverTypes
- ) {
- throw new IllegalStateException();
- }
-
@NotNull
@Override
public DeclarationDescriptor getContainingDeclaration() {
return ERROR_MODULE;
}
- @NotNull
- @Override
- public Collection<DeclarationDescriptor> getDeclarationsByLabel(@NotNull Name labelName) {
- throw new IllegalStateException();
- }
-
@NotNull
@Override
public Collection<DeclarationDescriptor> getDescriptors(
@@ -371,12 +278,6 @@ public Collection<DeclarationDescriptor> getAllDescriptors() {
throw new IllegalStateException();
}
- @NotNull
- @Override
- public List<ReceiverParameterDescriptor> getImplicitReceiversHierarchy() {
- throw new IllegalStateException();
- }
-
@NotNull
@Override
public Collection<DeclarationDescriptor> getOwnDeclaredDescriptors() {
@@ -461,7 +362,6 @@ public static KtScope createErrorScope(@NotNull String debugMessage, boolean thr
private static final PropertyDescriptor ERROR_PROPERTY = createErrorProperty();
private static final Set<VariableDescriptor> ERROR_VARIABLE_GROUP = Collections.<VariableDescriptor>singleton(ERROR_PROPERTY);
- private static final Set<PropertyDescriptor> ERROR_PROPERTY_GROUP = Collections.singleton(ERROR_PROPERTY);
@NotNull
private static PropertyDescriptorImpl createErrorProperty() {
diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt
index a29fb1ca70964..b9bab399fd54e 100644
--- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt
+++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedClassDescriptor.kt
@@ -242,8 +242,6 @@ public class DeserializedClassDescriptor(
}
}
- override fun getImplicitReceiver() = classDescriptor.getThisAsReceiverParameter()
-
override fun getClassDescriptor(name: Name): ClassifierDescriptor? =
classDescriptor.enumEntries.findEnumEntry(name) ?: classDescriptor.nestedClasses.findNestedClass(name)
diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt
index 6ae67fb5645ea..85fdf9568c011 100644
--- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt
+++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedMemberScope.kt
@@ -175,13 +175,6 @@ public abstract class DeserializedMemberScope protected constructor(
protected abstract fun addEnumEntryDescriptors(result: MutableCollection<DeclarationDescriptor>, nameFilter: (Name) -> Boolean)
- override fun getImplicitReceiversHierarchy(): List<ReceiverParameterDescriptor> {
- val receiver = getImplicitReceiver()
- return if (receiver != null) listOf(receiver) else listOf()
- }
-
- protected abstract fun getImplicitReceiver(): ReceiverParameterDescriptor?
-
override fun getOwnDeclaredDescriptors() = getAllDescriptors()
override fun printScopeStructure(p: Printer) {
diff --git a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedPackageMemberScope.kt b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedPackageMemberScope.kt
index 68057cefc2e74..edd98b2139170 100644
--- a/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedPackageMemberScope.kt
+++ b/core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/descriptors/DeserializedPackageMemberScope.kt
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.serialization.deserialization.descriptors
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
-import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.ClassId
@@ -69,6 +68,4 @@ public open class DeserializedPackageMemberScope(
override fun addEnumEntryDescriptors(result: MutableCollection<DeclarationDescriptor>, nameFilter: (Name) -> Boolean) {
// Do nothing
}
-
- override fun getImplicitReceiver(): ReceiverParameterDescriptor? = null
}
|
d074c686b3ba0ba6843d0a25dca5ac991f919e68
|
hadoop
|
HADOOP-6139. Fix the FsShell help messages for rm- and rmr. Contributed by Jakob Homan--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@793098 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 9979aefe66ab8..c70d07c0fbf23 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1011,6 +1011,9 @@ Release 0.20.1 - Unreleased
HADOOP-5920. Fixes a testcase failure for TestJobHistory.
(Amar Kamat via ddas)
+ HADOOP-6139. Fix the FsShell help messages for rm and rmr. (Jakob Homan
+ via szetszwo)
+
Release 0.20.0 - 2009-04-15
INCOMPATIBLE CHANGES
diff --git a/src/java/org/apache/hadoop/fs/FsShell.java b/src/java/org/apache/hadoop/fs/FsShell.java
index 3af28dc13e441..634da87da000e 100644
--- a/src/java/org/apache/hadoop/fs/FsShell.java
+++ b/src/java/org/apache/hadoop/fs/FsShell.java
@@ -1679,7 +1679,6 @@ private static void printUsage(String cmd) {
" [-D <[property=value>]");
} else if ("-ls".equals(cmd) || "-lsr".equals(cmd) ||
"-du".equals(cmd) || "-dus".equals(cmd) ||
- "-rm".equals(cmd) || "-rmr".equals(cmd) ||
"-touchz".equals(cmd) || "-mkdir".equals(cmd) ||
"-text".equals(cmd)) {
System.err.println("Usage: java FsShell" +
@@ -1689,6 +1688,9 @@ private static void printUsage(String cmd) {
" [" + cmd + " [<path>]]");
} else if (Count.matches(cmd)) {
System.err.println(prefix + " [" + Count.USAGE + "]");
+ } else if ("-rm".equals(cmd) || "-rmr".equals(cmd)) {
+ System.err.println("Usage: java FsShell [" + cmd +
+ " [-skipTrash] <src>]");
} else if ("-mv".equals(cmd) || "-cp".equals(cmd)) {
System.err.println("Usage: java FsShell" +
" [" + cmd + " <src> <dst>]");
|
cf4b20cbd433e31b242ef5b88c63c7e949e5d79a
|
restlet-framework-java
|
- Refactored the JdbcClient to return XML result- sets (using a new RowSetRepresentation class). In addition, the XML- request can now contain several SQL statements to be executed as a batch.- Contributed by Thierry Boileau.--
|
a
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/build.number b/build/build.number
index 0a585a2bc5..cb849a2a19 100644
--- a/build/build.number
+++ b/build/build.number
@@ -1,3 +1,3 @@
#Build Number for ANT. Do not edit!
-#Mon Nov 27 14:41:38 CET 2006
-build.number=532
+#Wed Nov 29 09:11:29 CET 2006
+build.number=535
diff --git a/build/tmpl/changes.txt b/build/tmpl/changes.txt
index 6c4aff6ab7..384ced4a90 100644
--- a/build/tmpl/changes.txt
+++ b/build/tmpl/changes.txt
@@ -16,6 +16,8 @@ Changes log
- Add new constructor to Tag for weak tags taking an unquoted opaque value. Fixes #201.
Suggested by Chris Grindstaff
- Updated Spring library to 2.0.1
+ - Refactored the JdbcClient to return XML result sets (using a new RowSetRepresentation class). In addition, the
+ XML request can now contain several SQL statements to be executed as a batch. Contributed by Thierry Boileau.
1.0 beta 21 (2006-11-26)
[Bugs fixed]
diff --git a/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/JdbcClientHelper.java b/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/JdbcClientHelper.java
index 24a827274a..c3029bd7ec 100644
--- a/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/JdbcClientHelper.java
+++ b/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/JdbcClientHelper.java
@@ -47,7 +47,7 @@
import org.restlet.data.Protocol;
import org.restlet.data.Request;
import org.restlet.data.Response;
-import org.restlet.resource.ObjectRepresentation;
+import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -59,18 +59,18 @@
import com.noelios.restlet.Factory;
/**
- * Client connector to a JDBC database. To send a request to the server create a
- * new instance of JdbcCall and invoke the handle() method. Alteratively you can
- * create a new Call with the JDBC URI as the resource reference and use an XML
- * request as the entity.<br/><br/> Database connections are optionally pooled
- * using Apache Commons DBCP. In this case, a different connection pool is
- * created for each unique combination of JDBC URI and connection properties.<br/><br/>
- * Do not forget to register your JDBC drivers before using this client. See <a
+ * Client connector to a JDBC database.<br/> To send a request to the server,
+ * create a new instance of a client supporting the JDBC Protocol and invoke the
+ * handle() method.<br/> Alternatively, you can create a new Call with the JDBC
+ * URI as the resource reference and use an XML request as the entity.<br/><br/>
+ * Database connections are optionally pooled using Apache Commons DBCP. In this
+ * case, a different connection pool is created for each unique combination of
+ * JDBC URI and connection properties.<br/><br/> Do not forget to register
+ * your JDBC drivers before using this client. See <a
* href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/DriverManager.html">
- * JDBC DriverManager API</a> for details<br/> <br/> Sample XML request:<br/>
- * <br/> {@code <?xml version="1.0" encoding="ISO-8859-1" ?>}<br/>
- * {@code <request>}<br/> {@code <header>}<br/>
- * {@code <connection>}<br/>
+ * JDBC DriverManager API</a> for details<br/><br/> Sample XML request:<br/><br/>
+ * {@code <?xml version="1.0" encoding="ISO-8859-1" ?>}<br/> {@code <request>}<br/>
+ * {@code <header>}<br/> {@code <connection>}<br/>
* {@code <usePooling>true</usePooling>}<br/>
* {@code <property name="user">scott</property >}<br/>
* {@code <property name="password">tiger</property >}<br/>
@@ -78,10 +78,16 @@
* {@code <property name="...">true</property >}<br/>
* {@code </connection>}<br/> {@code <returnGeneratedKeys>true</returnGeneratedKeys>}<br/>
* {@code </header>}<br/> {@code <body>}<br/>
- * {@code SELECT * FROM customers}<br/> {@code </body>}<br/>
- * {@code </request>}
+ * {@code <statement>UPDATE myTable SET myField1="value1" </statement>}<br/>
+ * {@code <statement>SELECT msField1, myField2 FROM myTable</statement>}<br/>
+ * {@code </body>}<br/> {@code </request>}<br/><br/>Several SQL Statements
+ * can be specified.<br/> A RowSetRepresentation of the last correctly executed
+ * SQL request is returned to the Client.</br>
+ *
+ * @see com.noelios.restlet.ext.jdbc.RowSetRepresentation
*
* @author Jerome Louvel ([email protected])
+ * @author Thierry Boileau
*/
public class JdbcClientHelper extends ClientHelper {
/** Map of connection factories. */
@@ -131,87 +137,136 @@ public static Request create(String jdbcURI, Representation request) {
public void handle(Request request, Response response) {
Connection connection = null;
- try {
- // Parse the JDBC URI
- String connectionURI = request.getResourceRef().toString();
-
- // Parse the request to extract necessary info
- DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
- .newDocumentBuilder();
- Document requestDoc = docBuilder.parse(request.getEntity()
- .getStream());
-
- Element rootElt = (Element) requestDoc.getElementsByTagName(
- "request").item(0);
- Element headerElt = (Element) rootElt
- .getElementsByTagName("header").item(0);
- Element connectionElt = (Element) headerElt.getElementsByTagName(
- "connection").item(0);
-
- // Read the connection pooling setting
- Node usePoolingNode = connectionElt.getElementsByTagName(
- "usePooling").item(0);
- boolean usePooling = usePoolingNode.getTextContent().equals("true") ? true
- : false;
-
- // Read the connection properties
- NodeList propertyNodes = connectionElt
- .getElementsByTagName("property");
- Node propertyNode = null;
- Properties properties = null;
- String name = null;
- String value = null;
- for (int i = 0; i < propertyNodes.getLength(); i++) {
- propertyNode = propertyNodes.item(i);
-
- if (properties == null)
- properties = new Properties();
- name = propertyNode.getAttributes().getNamedItem("name")
- .getTextContent();
- value = propertyNode.getTextContent();
- properties.setProperty(name, value);
- }
-
- Node returnGeneratedKeysNode = headerElt.getElementsByTagName(
- "returnGeneratedKeys").item(0);
- boolean returnGeneratedKeys = returnGeneratedKeysNode
- .getTextContent().equals("true") ? true : false;
+ if (request.getMethod().equals(Method.POST)) {
+ try {
+ // Parse the JDBC URI
+ String connectionURI = request.getResourceRef().toString();
+
+ // Parse the request to extract necessary info
+ DocumentBuilder docBuilder = DocumentBuilderFactory
+ .newInstance().newDocumentBuilder();
+ Document requestDoc = docBuilder.parse(request.getEntity()
+ .getStream());
+
+ Element rootElt = (Element) requestDoc.getElementsByTagName(
+ "request").item(0);
+ Element headerElt = (Element) rootElt.getElementsByTagName(
+ "header").item(0);
+ Element connectionElt = (Element) headerElt
+ .getElementsByTagName("connection").item(0);
+
+ // Read the connection pooling setting
+ Node usePoolingNode = connectionElt.getElementsByTagName(
+ "usePooling").item(0);
+ boolean usePooling = usePoolingNode.getTextContent().equals(
+ "true") ? true : false;
+
+ // Read the connection properties
+ NodeList propertyNodes = connectionElt
+ .getElementsByTagName("property");
+ Node propertyNode = null;
+ Properties properties = null;
+ String name = null;
+ String value = null;
+ for (int i = 0; i < propertyNodes.getLength(); i++) {
+ propertyNode = propertyNodes.item(i);
+
+ if (properties == null)
+ properties = new Properties();
+ name = propertyNode.getAttributes().getNamedItem("name")
+ .getTextContent();
+ value = propertyNode.getTextContent();
+ properties.setProperty(name, value);
+ }
- // Read the SQL body
- Node sqlRequestNode = rootElt.getElementsByTagName("body").item(0);
- String sqlRequest = sqlRequestNode.getTextContent();
+ Node returnGeneratedKeysNode = headerElt.getElementsByTagName(
+ "returnGeneratedKeys").item(0);
+ boolean returnGeneratedKeys = returnGeneratedKeysNode
+ .getTextContent().equals("true") ? true : false;
+
+ // Read the SQL body and get the list of sql statements
+ Element bodyElt = (Element) rootElt
+ .getElementsByTagName("body").item(0);
+ NodeList statementNodes = bodyElt
+ .getElementsByTagName("statement");
+ List<String> sqlRequests = new ArrayList<String>();
+ for (int i = 0; i < statementNodes.getLength(); i++) {
+ String sqlRequest = statementNodes.item(i).getTextContent();
+ sqlRequests.add(sqlRequest);
+ }
- if (request.getMethod().equals(Method.POST)) {
- // Execute the SQL request
+ // Execute the List of SQL requests
connection = getConnection(connectionURI, properties,
usePooling);
- Statement statement = connection.createStatement();
+ JdbcResult result = handleSqlRequests(connection,
+ returnGeneratedKeys, sqlRequests);
+ response.setEntity(new RowSetRepresentation(result));
+
+ } catch (SQLException se) {
+ getLogger().log(Level.WARNING,
+ "Error while processing the SQL request", se);
+ response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL,
+ "Error while processing the SQL request"));
+ } catch (ParserConfigurationException pce) {
+ getLogger().log(Level.WARNING,
+ "Error with XML parser configuration", pce);
+ response.setStatus(new Status(Status.CLIENT_ERROR_BAD_REQUEST,
+ "Error with XML parser configuration"));
+ } catch (SAXException se) {
+ getLogger().log(Level.WARNING,
+ "Error while parsing the XML document", se);
+ response.setStatus(new Status(Status.CLIENT_ERROR_BAD_REQUEST,
+ "Error while parsing the XML document"));
+ } catch (IOException ioe) {
+ getLogger().log(Level.WARNING, "Input/Output exception", ioe);
+ response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL,
+ "Input/Output exception"));
+ }
+ } else {
+ throw new IllegalArgumentException(
+ "Only the POST method is supported");
+ }
+ }
+
+ /**
+ * Helper
+ *
+ * @param connection
+ * @param returnGeneratedKeys
+ * @param sqlRequests
+ * @return the result of the last executed SQL request
+ */
+ private JdbcResult handleSqlRequests(Connection connection,
+ boolean returnGeneratedKeys, List<String> sqlRequests) {
+ JdbcResult result = null;
+ try {
+ connection.setAutoCommit(true);
+ Statement statement = connection.createStatement();
+ for (String sqlRequest : sqlRequests) {
statement.execute(sqlRequest,
returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS
: Statement.NO_GENERATED_KEYS);
- JdbcResult result = new JdbcResult(statement);
- response.setEntity(new ObjectRepresentation(result));
+ result = new JdbcResult(statement);
+ }
- // Commit any changes to the database
- if (!connection.getAutoCommit()) {
- connection.commit();
- }
- } else {
- throw new IllegalArgumentException(
- "Only the POST method is supported");
+ // Commit any changes to the database
+ if (!connection.getAutoCommit()) {
+ connection.commit();
}
} catch (SQLException se) {
getLogger().log(Level.WARNING,
- "Error while processing the SQL request", se);
- } catch (ParserConfigurationException pce) {
- getLogger().log(Level.WARNING,
- "Error with XML parser configuration", pce);
- } catch (SAXException se) {
- getLogger().log(Level.WARNING,
- "Error while parsing the XML document", se);
- } catch (IOException ioe) {
- getLogger().log(Level.WARNING, "Input/Output exception", ioe);
+ "Error while processing the SQL requests", se);
+ try {
+ if (!connection.getAutoCommit()) {
+ connection.rollback();
+ }
+ } catch (SQLException se2) {
+ getLogger().log(Level.WARNING,
+ "Error while rollbacking the transaction", se);
+ }
}
+ return result;
+
}
/**
@@ -241,8 +296,8 @@ protected Connection getConnection(String uri, Properties properties,
for (Object key : c.getProperties().keySet()) {
if (equal && properties.containsKey(key)) {
equal = equal
- && (properties.get(key) == c
- .getProperties().get(key));
+ && (properties.get(key).equals(c
+ .getProperties().get(key)));
} else {
equal = false;
}
@@ -364,5 +419,4 @@ public Properties getProperties() {
return properties;
}
}
-
}
diff --git a/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/RowSetRepresentation.java b/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/RowSetRepresentation.java
new file mode 100644
index 0000000000..95c736c013
--- /dev/null
+++ b/module/com.noelios.restlet.ext.jdbc_3.0/src/com/noelios/restlet/ext/jdbc/RowSetRepresentation.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2005-2006 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 com.noelios.restlet.ext.jdbc;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.sql.SQLException;
+
+import javax.sql.rowset.WebRowSet;
+
+import org.restlet.data.MediaType;
+import org.restlet.resource.OutputRepresentation;
+
+import com.sun.rowset.WebRowSetImpl;
+
+/**
+ * XML Representation of a ResultSet instance wrapped either in a JdbcResult
+ * instance or in a WebRowSet. Leverage the WebRowSet API to create the Response
+ * entity.<br/> Give access the JdbcResult instance and to the WebRowSet for
+ * retrieval of the connected ResultSet in the same JVM (for advanced use
+ * cases).<br/>
+ *
+ * @see <a
+ * href="http://java.sun.com/j2se/1.5.0/docs/api/javax/sql/rowset/WebRowSet.html">WebRowSet
+ * Interface</a>
+ * @author Thierry Boileau
+ * @author Jerome Louvel ([email protected])
+ */
+public class RowSetRepresentation extends OutputRepresentation {
+ /**
+ * Creates a WebRowSet from a JdbcResult.
+ *
+ * @param jdbcResult
+ * The JdbcResult instance to wrap.
+ * @return A WebRowSet from a JdbcResult.
+ * @throws SQLException
+ */
+ private static WebRowSet create(JdbcResult jdbcResult) throws SQLException {
+ WebRowSet result = new WebRowSetImpl();
+
+ if (jdbcResult.getResultSet() != null) {
+ result.populate(jdbcResult.getResultSet());
+ }
+
+ return result;
+ }
+
+ /** Inner WebRowSet Instance. */
+ private WebRowSet webRowSet;
+
+ /** JdbcResult instance that gives access to the resultSet. */
+ private JdbcResult jdbcResult;
+
+ /**
+ * Constructor.
+ *
+ * @param jdbcResult
+ * The inner JdbcResult.
+ * @throws SQLException
+ */
+ public RowSetRepresentation(JdbcResult jdbcResult) throws SQLException {
+ this(create(jdbcResult));
+ this.jdbcResult = jdbcResult;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param webRowSet
+ * The inner WebRowSet.
+ */
+ public RowSetRepresentation(WebRowSet webRowSet) {
+ super(MediaType.TEXT_XML);
+ this.webRowSet = webRowSet;
+ }
+
+ /**
+ * Returns the inner JdbcResult instance or null.
+ *
+ * @return The inner JdbcResult instance or null.
+ */
+ public JdbcResult getJdbcResult() {
+ return jdbcResult;
+ }
+
+ /**
+ * Returns the inner WebRowSet instance.
+ *
+ * @return The inner WebRowSet instance.
+ */
+ public WebRowSet getWebRowSet() {
+ return this.webRowSet;
+ }
+
+ @Override
+ public void write(OutputStream outputStream) throws IOException {
+ try {
+ webRowSet.writeXml(outputStream);
+ } catch (SQLException se) {
+ throw new IOException(se.getMessage());
+ }
+ }
+}
|
c9a360e36059aa46d7090e879762d44d54fa2782
|
hbase
|
HBASE-7197. Add multi get to RemoteHTable- (Elliott Clark)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1422143 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java
index beebe960b05b..92fe09202f61 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java
@@ -148,6 +148,29 @@ protected String buildRowSpec(final byte[] row, final Map familyMap,
return sb.toString();
}
+ protected String buildMultiRowSpec(final byte[][] rows, int maxVersions) {
+ StringBuilder sb = new StringBuilder();
+ sb.append('/');
+ sb.append(Bytes.toStringBinary(name));
+ sb.append("/multiget/");
+ if (rows == null || rows.length == 0) {
+ return sb.toString();
+ }
+ sb.append("?");
+ for(int i=0; i<rows.length; i++) {
+ byte[] rk = rows[i];
+ if (i != 0) {
+ sb.append('&');
+ }
+ sb.append("row=");
+ sb.append(Bytes.toStringBinary(rk));
+ }
+ sb.append("&v=");
+ sb.append(maxVersions);
+
+ return sb.toString();
+ }
+
protected Result[] buildResultFromModel(final CellSetModel model) {
List<Result> results = new ArrayList<Result>();
for (RowModel row: model.getRows()) {
@@ -273,31 +296,66 @@ public Result get(Get get) throws IOException {
if (get.getFilter() != null) {
LOG.warn("filters not supported on gets");
}
+ Result[] results = getResults(spec);
+ if (results.length > 0) {
+ if (results.length > 1) {
+ LOG.warn("too many results for get (" + results.length + ")");
+ }
+ return results[0];
+ } else {
+ return new Result();
+ }
+ }
+
+ public Result[] get(List<Get> gets) throws IOException {
+ byte[][] rows = new byte[gets.size()][];
+ int maxVersions = 1;
+ int count = 0;
+
+ for(Get g:gets) {
+
+ if ( count == 0 ) {
+ maxVersions = g.getMaxVersions();
+ } else if (g.getMaxVersions() != maxVersions) {
+ LOG.warn("MaxVersions on Gets do not match, using the first in the list ("+maxVersions+")");
+ }
+
+ if (g.getFilter() != null) {
+ LOG.warn("filters not supported on gets");
+ }
+
+ rows[count] = g.getRow();
+ count ++;
+ }
+
+ String spec = buildMultiRowSpec(rows, maxVersions);
+
+ return getResults(spec);
+ }
+
+ private Result[] getResults(String spec) throws IOException {
for (int i = 0; i < maxRetries; i++) {
Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF);
int code = response.getCode();
switch (code) {
- case 200:
- CellSetModel model = new CellSetModel();
- model.getObjectFromMessage(response.getBody());
- Result[] results = buildResultFromModel(model);
- if (results.length > 0) {
- if (results.length > 1) {
- LOG.warn("too many results for get (" + results.length + ")");
+ case 200:
+ CellSetModel model = new CellSetModel();
+ model.getObjectFromMessage(response.getBody());
+ Result[] results = buildResultFromModel(model);
+ if ( results.length > 0) {
+ return results;
}
- return results[0];
- }
- // fall through
- case 404:
- return new Result();
+ // fall through
+ case 404:
+ return new Result[0];
- case 509:
- try {
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) { }
- break;
- default:
- throw new IOException("get request returned " + code);
+ case 509:
+ try {
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) { }
+ break;
+ default:
+ throw new IOException("get request returned " + code);
}
}
throw new IOException("get request timed out");
@@ -708,11 +766,6 @@ public <R> Object[] batchCallback(List<? extends Row> actions, Batch.Callback<R>
throw new IOException("batchCallback not supported");
}
- @Override
- public Result[] get(List<Get> gets) throws IOException {
- throw new IOException("get(List<Get>) not supported");
- }
-
@Override
public <T extends CoprocessorProtocol> T coprocessorProxy(Class<T> protocol,
byte[] row) {
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java
index 01e23d99a0ed..b52a167fbbc9 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java
@@ -216,6 +216,45 @@ public void testGet() throws IOException {
assertEquals(2, count);
}
+ @Test
+ public void testMultiGet() throws Exception {
+ ArrayList<Get> gets = new ArrayList<Get>();
+ gets.add(new Get(ROW_1));
+ gets.add(new Get(ROW_2));
+ Result[] results = remoteTable.get(gets);
+ assertNotNull(results);
+ assertEquals(2, results.length);
+ assertEquals(1, results[0].size());
+ assertEquals(2, results[1].size());
+
+ //Test Versions
+ gets = new ArrayList<Get>();
+ Get g = new Get(ROW_1);
+ g.setMaxVersions(3);
+ gets.add(g);
+ gets.add(new Get(ROW_2));
+ results = remoteTable.get(gets);
+ assertNotNull(results);
+ assertEquals(2, results.length);
+ assertEquals(1, results[0].size());
+ assertEquals(3, results[1].size());
+
+ //404
+ gets = new ArrayList<Get>();
+ gets.add(new Get(Bytes.toBytes("RESALLYREALLYNOTTHERE")));
+ results = remoteTable.get(gets);
+ assertNotNull(results);
+ assertEquals(0, results.length);
+
+ gets = new ArrayList<Get>();
+ gets.add(new Get(Bytes.toBytes("RESALLYREALLYNOTTHERE")));
+ gets.add(new Get(ROW_1));
+ gets.add(new Get(ROW_2));
+ results = remoteTable.get(gets);
+ assertNotNull(results);
+ assertEquals(0, results.length);
+ }
+
@Test
public void testPut() throws IOException {
Put put = new Put(ROW_3);
|
a7704c8cceb2e2c04c6a843f575463f32674299d
|
spring-framework
|
Polish Javadoc for PropertySource implementations--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.core/src/main/java/org/springframework/core/env/MapPropertySource.java b/org.springframework.core/src/main/java/org/springframework/core/env/MapPropertySource.java
index 3fbc6378ffce..05eec722614a 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/env/MapPropertySource.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/env/MapPropertySource.java
@@ -19,15 +19,15 @@
import java.util.Map;
/**
- * {@link PropertySource} that reads keys and values from a {@code Map<String,String>} object.
+ * {@link PropertySource} that reads keys and values from a {@code Map} object.
*
* @author Chris Beams
* @since 3.1
* @see PropertiesPropertySource
*/
-public class MapPropertySource extends EnumerablePropertySource<Map<String, ? super Object>> {
+public class MapPropertySource extends EnumerablePropertySource<Map<String, Object>> {
- protected MapPropertySource(String name, Map<String, ? super Object> source) {
+ protected MapPropertySource(String name, Map<String, Object> source) {
super(name, source);
}
diff --git a/org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java b/org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java
index 418d7572b194..b05f78c1a67a 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/env/MutablePropertySources.java
@@ -87,7 +87,7 @@ public void addLast(PropertySource<?> propertySource) {
}
/**
- * Add the given property source object with precedence immediately greater
+ * Add the given property source object with precedence immediately higher
* than the named relative property source.
*/
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
@@ -98,7 +98,7 @@ public void addBefore(String relativePropertySourceName, PropertySource<?> prope
}
/**
- * Add the given property source object with precedence immediately less than
+ * Add the given property source object with precedence immediately lower than
* than the named relative property source.
*/
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
|
05a497f35ade5b00ad049cf18873068379ef7ccd
|
hadoop
|
HADOOP-7034. Add TestPath tests to cover dot, dot- dot, and slash normalization. Contributed by Eli Collins--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1035142 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index b5b25a919200b..3557fdf491a7e 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -171,9 +171,9 @@ Trunk (unreleased changes)
HADOOP-7024. Create a test method for adding file systems during tests.
(Kan Zhang via jghoman)
- HADOOP-6903 Make AbstractFSileSystem methods and some FileContext methods to be public
- (Sanjay Radia via Sanjay Radia)
+ HADOOP-6903. Make AbstractFSileSystem methods and some FileContext methods to be public. (Sanjay Radia via Sanjay Radia)
+ HADOOP-7034. Add TestPath tests to cover dot, dot dot, and slash normalization. (eli)
OPTIMIZATIONS
diff --git a/src/test/core/org/apache/hadoop/fs/TestPath.java b/src/test/core/org/apache/hadoop/fs/TestPath.java
index 3a49b4930b19a..703e769184887 100644
--- a/src/test/core/org/apache/hadoop/fs/TestPath.java
+++ b/src/test/core/org/apache/hadoop/fs/TestPath.java
@@ -61,6 +61,9 @@ private void toStringTest(String pathString) {
}
public void testNormalize() {
+ assertEquals("", new Path(".").toString());
+ assertEquals("..", new Path("..").toString());
+ assertEquals("/", new Path("/").toString());
assertEquals("/", new Path("//").toString());
assertEquals("/", new Path("///").toString());
assertEquals("//foo/", new Path("//foo/").toString());
|
a5b30fd0743195dd2d80dcec2c5e131d8bbc62ef
|
spring-framework
|
polishing--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java
index 854082aed533..510c2f16a010 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/SelectedValueComparator.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2008 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.
@@ -112,7 +112,7 @@ private static boolean collectionCompare(Collection boundCollection, Object cand
}
}
catch (ClassCastException ex) {
- // Probably from a - ignore.
+ // Probably from a TreeSet - ignore.
}
return exhaustiveCollectionCompare(boundCollection, candidateValue, bindStatus);
}
@@ -181,7 +181,7 @@ else if (ObjectUtils.getDisplayString(boundValue).equals(candidateDisplayString)
else if (editor != null && candidate instanceof String) {
// Try PE-based comparison (PE should *not* be allowed to escape creating thread)
String candidateAsString = (String) candidate;
- Object candidateAsValue = null;
+ Object candidateAsValue;
if (convertedValueCache != null && convertedValueCache.containsKey(editor)) {
candidateAsValue = convertedValueCache.get(editor);
}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
index 1146a7ea4886..0a358221420c 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java
@@ -135,6 +135,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport
private List<ViewResolver> viewResolvers;
+
public void setOrder(int order) {
this.order = order;
}
@@ -312,7 +313,8 @@ protected List<MediaType> getMediaTypes(HttpServletRequest request) {
}
if (this.defaultContentType != null) {
if (logger.isDebugEnabled()) {
- logger.debug("Requested media types is " + defaultContentType + " (based on defaultContentType property)");
+ logger.debug("Requested media types is " + this.defaultContentType +
+ " (based on defaultContentType property)");
}
return Collections.singletonList(this.defaultContentType);
}
@@ -323,9 +325,9 @@ protected List<MediaType> getMediaTypes(HttpServletRequest request) {
/**
* Determines the {@link MediaType} for the given filename.
- * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types} property first for a
- * defined mapping. If not present, and if the Java Activation Framework can be found on the class path, it will call
- * {@link FileTypeMap#getContentType(String)}
+ * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types}
+ * property first for a defined mapping. If not present, and if the Java Activation Framework
+ * can be found on the classpath, it will call {@link FileTypeMap#getContentType(String)}
* <p>This method can be overriden to provide a different algorithm.
* @param filename the current request file name (i.e. {@code hotels.html})
* @return the media type, if any
@@ -337,7 +339,7 @@ protected MediaType getMediaTypeFromFilename(String filename) {
}
extension = extension.toLowerCase(Locale.ENGLISH);
MediaType mediaType = this.mediaTypes.get(extension);
- if (mediaType == null && useJaf && jafPresent) {
+ if (mediaType == null && this.useJaf && jafPresent) {
mediaType = ActivationMediaTypeFactory.getMediaType(filename);
if (mediaType != null) {
this.mediaTypes.putIfAbsent(extension, mediaType);
@@ -361,18 +363,14 @@ protected MediaType getMediaTypeFromParameter(String parameterValue) {
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
-
List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
-
List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
-
View bestView = getBestView(candidateViews, requestedMediaTypes);
-
if (bestView != null) {
return bestView;
}
else {
- if (useNotAcceptableStatusCode) {
+ if (this.useNotAcceptableStatusCode) {
if (logger.isDebugEnabled()) {
logger.debug("No acceptable view found; returning 406 (Not Acceptable) status code");
}
@@ -389,8 +387,8 @@ public View resolveViewName(String viewName, Locale locale) throws Exception {
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)
throws Exception {
- List<View> candidateViews = new ArrayList<View>();
+ List<View> candidateViews = new ArrayList<View>();
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
@@ -408,7 +406,6 @@ private List<View> getCandidateViews(String viewName, Locale locale, List<MediaT
}
}
-
if (!CollectionUtils.isEmpty(this.defaultViews)) {
candidateViews.addAll(this.defaultViews);
}
@@ -452,6 +449,7 @@ private View getBestView(List<View> candidateViews, List<MediaType> requestedMed
}
+
/**
* Inner class to avoid hard-coded JAF dependency.
*/
@@ -501,6 +499,7 @@ public static MediaType getMediaType(String fileName) {
}
}
+
private static final View NOT_ACCEPTABLE_VIEW = new View() {
public String getContentType() {
@@ -512,4 +511,5 @@ public void render(Map<String, ?> model, HttpServletRequest request, HttpServlet
response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
}
};
+
}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java
index 4233461b8ac0..25b20e317915 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/view/RedirectView.java
@@ -261,7 +261,7 @@ protected void appendQueryProperties(StringBuilder targetUrl, Map<String, Object
boolean first = (getUrl().indexOf('?') < 0);
for (Map.Entry<String, Object> entry : queryProperties(model).entrySet()) {
Object rawValue = entry.getValue();
- Iterator valueIter = null;
+ Iterator valueIter;
if (rawValue != null && rawValue.getClass().isArray()) {
valueIter = Arrays.asList(ObjectUtils.toObjectArray(rawValue)).iterator();
}
@@ -398,14 +398,18 @@ protected void sendRedirect(
/**
* Determines the status code to use for HTTP 1.1 compatible requests.
* <p>The default implemenetation returns the {@link #setStatusCode(HttpStatus) statusCode}
- * property if set, or the value of the {@link #RESPONSE_STATUS_ATTRIBUTE} attribute. If neither are
- * set, it defaults to {@link HttpStatus#SEE_OTHER} (303).
+ * property if set, or the value of the {@link #RESPONSE_STATUS_ATTRIBUTE} attribute.
+ * If neither are set, it defaults to {@link HttpStatus#SEE_OTHER} (303).
* @param request the request to inspect
- * @return the response
+ * @param response the servlet response
+ * @param targetUrl the target URL
+ * @return the response status
*/
- protected HttpStatus getHttp11StatusCode(HttpServletRequest request, HttpServletResponse response, String targetUrl) {
- if (statusCode != null) {
- return statusCode;
+ protected HttpStatus getHttp11StatusCode(
+ HttpServletRequest request, HttpServletResponse response, String targetUrl) {
+
+ if (this.statusCode != null) {
+ return this.statusCode;
}
HttpStatus attributeStatusCode = (HttpStatus) request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE);
if (attributeStatusCode != null) {
|
b33db73c932cd41bc19b9f5018c94c673dbe23d0
|
spring-framework
|
SPR-5251: URI Templates for @InitBinder--
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java
index 45a781c2a9f9..3d4f08da0114 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java
@@ -280,6 +280,7 @@ private Object[] resolveInitBinderArguments(Object handler,
String paramName = null;
boolean paramRequired = false;
String paramDefaultValue = null;
+ String pathVarName = null;
Object[] paramAnns = methodParam.getParameterAnnotations();
for (Object paramAnn : paramAnns) {
@@ -294,9 +295,13 @@ else if (ModelAttribute.class.isInstance(paramAnn)) {
throw new IllegalStateException(
"@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod);
}
+ else if (PathVariable.class.isInstance(paramAnn)) {
+ PathVariable pathVar = (PathVariable) paramAnn;
+ pathVarName = pathVar.value();
+ }
}
- if (paramName == null) {
+ if (paramName == null && pathVarName == null) {
Object argValue = resolveCommonArgument(methodParam, webRequest);
if (argValue != WebArgumentResolver.UNRESOLVED) {
initBinderArgs[i] = argValue;
@@ -319,6 +324,8 @@ else if (BeanUtils.isSimpleProperty(paramType)) {
if (paramName != null) {
initBinderArgs[i] =
resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
+ } else if (pathVarName != null) {
+ initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null);
}
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
index bcf535702fd3..d234cf1efa33 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
@@ -40,7 +40,6 @@
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
-import org.springframework.beans.BeansException;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
@@ -64,7 +63,6 @@
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
-import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@@ -798,24 +796,6 @@ protected WebApplicationContext createWebApplicationContext(WebApplicationContex
}
}
- @Test
- public void uriTemplates() throws Exception {
- DispatcherServlet servlet = new DispatcherServlet() {
- @Override
- protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException {
- GenericWebApplicationContext wac = new GenericWebApplicationContext();
- wac.registerBeanDefinition("controller", new RootBeanDefinition(UriTemplateController.class));
- wac.refresh();
- return wac;
- }
- };
- servlet.init(new MockServletConfig());
-
- MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21");
- MockHttpServletResponse response = new MockHttpServletResponse();
- servlet.service(request, response);
- assertEquals("test-42-21", response.getContentAsString());
- }
/*
* Controllers
@@ -1338,15 +1318,5 @@ public void get() {
}
}
- @Controller
- public static class UriTemplateController {
-
- @RequestMapping("/hotels/{hotel}/bookings/{booking}")
- public void handle(@PathVariable("hotel") int hotel, @PathVariable int booking, HttpServletResponse response)
- throws IOException {
- response.getWriter().write("test-" + hotel + "-" + booking);
- }
-
- }
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
new file mode 100644
index 000000000000..dcbad780a13a
--- /dev/null
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
@@ -0,0 +1,112 @@
+package org.springframework.web.servlet.mvc.annotation;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.support.RootBeanDefinition;
+import org.springframework.beans.propertyeditors.CustomDateEditor;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockServletConfig;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.WebDataBinder;
+import org.springframework.web.bind.annotation.InitBinder;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.support.GenericWebApplicationContext;
+import org.springframework.web.servlet.DispatcherServlet;
+
+/** @author Arjen Poutsma */
+public class UriTemplateServletAnnotationControllerTests {
+
+ private DispatcherServlet servlet;
+
+ @Test
+ public void simple() throws Exception {
+ initServlet(SimpleUriTemplateController.class);
+
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("test-42-21", response.getContentAsString());
+ }
+
+ @Test
+ public void binding() throws Exception {
+ initServlet(BindingUriTemplateController.class);
+
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-11-18");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("test-42", response.getContentAsString());
+ }
+
+ private void initServlet(final Class<?> controllerclass) throws ServletException {
+ servlet = new DispatcherServlet() {
+ @Override
+ protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
+ throws BeansException {
+ GenericWebApplicationContext wac = new GenericWebApplicationContext();
+ wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass));
+ wac.refresh();
+ return wac;
+ }
+ };
+ servlet.init(new MockServletConfig());
+ }
+
+ @Controller
+ public static class SimpleUriTemplateController {
+
+ @RequestMapping("/hotels/{hotel}/bookings/{booking}")
+ public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, Writer writer) throws IOException {
+ assertEquals("Invalid path variable value", "42", hotel);
+ assertEquals("Invalid path variable value", 21, booking);
+ writer.write("test-" + hotel + "-" + booking);
+ }
+
+ }
+
+ @Controller
+ public static class BindingUriTemplateController {
+
+ @InitBinder
+ public void initBinder(WebDataBinder binder, @PathVariable("hotel") String hotel) {
+ assertEquals("Invalid path variable value", "42", hotel);
+ binder.initBeanPropertyAccess();
+ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ dateFormat.setLenient(false);
+ binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
+ }
+
+ @RequestMapping("/hotels/{hotel}/dates/{date}")
+ public void handle(@PathVariable("hotel") String hotel, @PathVariable Date date, Writer writer) throws IOException {
+ assertEquals("Invalid path variable value", "42", hotel);
+ assertEquals("Invalid path variable value", new Date(108, 10, 18), date);
+ writer.write("test-" + hotel);
+ }
+
+ }
+
+ @Controller
+ @RequestMapping("/hotels/{hotel}/**")
+ public static class RelativePathUriTemplateController {
+
+ @RequestMapping("/bookings/{booking}")
+ public void handle(@PathVariable("hotel") int hotel, @PathVariable int booking, HttpServletResponse response)
+ throws IOException {
+ response.getWriter().write("test-" + hotel + "-" + booking);
+ }
+
+ }
+
+}
|
a467e88ae4c1dacb022288fe6d4805a7f719cd12
|
hadoop
|
YARN-1883. TestRMAdminService fails due to- inconsistent entries in UserGroups (Mit Desai via jeagles)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1582865 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 2a850e01e22d7..48fe1e261710a 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -33,6 +33,9 @@ Release 2.5.0 - UNRELEASED
YARN-1136. Replace junit.framework.Assert with org.junit.Assert (Chen He
via jeagles)
+ YARN-1883. TestRMAdminService fails due to inconsistent entries in
+ UserGroups (Mit Desai via jeagles)
+
OPTIMIZATIONS
BUG FIXES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java
index ab199d1d39ebe..32e78ebf1828a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java
@@ -90,6 +90,9 @@ public void setup() throws IOException {
fs.delete(tmpDir, true);
fs.mkdirs(workingPath);
fs.mkdirs(tmpDir);
+
+ // reset the groups to what it default test settings
+ MockUnixGroupsMapping.resetGroups();
}
@After
@@ -785,12 +788,7 @@ private void uploadDefaultConfiguration() throws IOException {
private static class MockUnixGroupsMapping implements
GroupMappingServiceProvider {
- @SuppressWarnings("serial")
- private static List<String> group = new ArrayList<String>() {{
- add("test_group_A");
- add("test_group_B");
- add("test_group_C");
- }};
+ private static List<String> group = new ArrayList<String>();
@Override
public List<String> getGroups(String user) throws IOException {
@@ -813,6 +811,13 @@ public static void updateGroups() {
group.add("test_group_E");
group.add("test_group_F");
}
+
+ public static void resetGroups() {
+ group.clear();
+ group.add("test_group_A");
+ group.add("test_group_B");
+ group.add("test_group_C");
+ }
}
}
|
9d8ae0a8feb951f799df29fc9f10ba07f4b0b255
|
intellij-community
|
additional null check--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java b/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
index 56c4f69599974..762ba6c554002 100644
--- a/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
+++ b/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
@@ -335,7 +335,10 @@ private Map<String, String> getMacroMap() {
if (application != null) {
final PathMacros pathMacros = PathMacros.getInstance();
for (String name : pathMacros.getUserMacroNames()) {
- myMacroMap.put("${" + name + "}", pathMacros.getValue(name));
+ final String value = pathMacros.getValue(name);
+ if (value != null) {
+ myMacroMap.put("${" + name + "}", value);
+ }
}
final Map<String, String> env = EnvironmentUtil.getEnviromentProperties();
for (String name : env.keySet()) {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.