commit_id
stringlengths 40
40
| project
stringclasses 91
values | commit_message
stringlengths 9
4.65k
| type
stringclasses 3
values | url
stringclasses 91
values | git_diff
stringlengths 555
2.23M
|
|---|---|---|---|---|---|
3181d96ec864a467d4259e31c64f2b7554afc3d4
|
hbase
|
HBASE-2397 Bytes.toStringBinary escapes printable- chars--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@951840 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 280daa7fb5ce..8ad8e5601edf 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -23,6 +23,7 @@ Release 0.21.0 - Unreleased
HBASE-2541 Remove transactional contrib (Clint Morgan via Stack)
HBASE-2542 Fold stargate contrib into core
HBASE-2565 Remove contrib module from hbase
+ HBASE-2397 Bytes.toStringBinary escapes printable chars
BUG FIXES
HBASE-1791 Timeout in IndexRecordWriter (Bradford Stephens via Andrew
diff --git a/src/main/java/org/apache/hadoop/hbase/util/Bytes.java b/src/main/java/org/apache/hadoop/hbase/util/Bytes.java
index bed859f48e62..1b46f2d892a4 100644
--- a/src/main/java/org/apache/hadoop/hbase/util/Bytes.java
+++ b/src/main/java/org/apache/hadoop/hbase/util/Bytes.java
@@ -320,16 +320,7 @@ public static String toStringBinary(final byte [] b, int off, int len) {
if ( (ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
- || ch == ','
- || ch == '_'
- || ch == '-'
- || ch == ':'
- || ch == ' '
- || ch == '<'
- || ch == '>'
- || ch == '='
- || ch == '/'
- || ch == '.') {
+ || " `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".indexOf(ch) >= 0 ) {
result.append(first.charAt(i));
} else {
result.append(String.format("\\x%02X", ch));
|
e24b71e70035f9a9baf7ec19c279311eceec31a9
|
spring-framework
|
Shutdown Reactor env when relay handler is- stopped--The Reactor Environment (that's used by the TcpClient) manages a-number of threads. To ensure that these threads are cleaned up-Environment.shutdown() must be called when the Environment is no-longer needed.-
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
index 2e1d31d42947..ef2d9eaaea48 100644
--- a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
+++ b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java
@@ -73,6 +73,8 @@ public class StompRelayPubSubMessageHandler extends AbstractPubSubMessageHandler
private MessageConverter payloadConverter;
+ private Environment environment;
+
private TcpClient<String, String> tcpClient;
private final Map<String, RelaySession> relaySessions = new ConcurrentHashMap<String, RelaySession>();
@@ -181,9 +183,9 @@ public boolean isRunning() {
@Override
public void start() {
synchronized (this.lifecycleMonitor) {
-
+ this.environment = new Environment();
this.tcpClient = new TcpClient.Spec<String, String>(NettyTcpClient.class)
- .using(new Environment())
+ .using(this.environment)
.codec(new DelimitedCodec<String, String>((byte) 0, true, StandardCodecs.STRING_CODEC))
.connect(this.relayHost, this.relayPort)
.get();
@@ -214,6 +216,7 @@ public void stop() {
this.running = false;
try {
this.tcpClient.close().await(5000, TimeUnit.MILLISECONDS);
+ this.environment.shutdown();
}
catch (InterruptedException e) {
// ignore
|
643ae0c985d01e4b5deb9d28a1381de8179926af
|
hbase
|
HBASE-2781 ZKW.createUnassignedRegion doesn't- make sure existing znode is in the right state (Karthik- Ranganathan via JD)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@963910 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index ec4341f65428..44e345bba702 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -432,6 +432,8 @@ Release 0.21.0 - Unreleased
HBASE-2797 Another NPE in ReadWriteConsistencyControl
HBASE-2831 Fix '$bin' path duplication in setup scripts
(Nicolas Spiegelberg via Stack)
+ HBASE-2781 ZKW.createUnassignedRegion doesn't make sure existing znode is
+ in the right state (Karthik Ranganathan via JD)
IMPROVEMENTS
HBASE-1760 Cleanup TODOs in HTable
diff --git a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
index b4ba5ab15c03..979739e3a076 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/RegionManager.java
@@ -993,8 +993,9 @@ public void setUnassigned(HRegionInfo info, boolean force) {
// should never happen
LOG.error("Error creating event data for " + HBaseEventType.M2ZK_REGION_OFFLINE, e);
}
- zkWrapper.createUnassignedRegion(info.getEncodedName(), data);
- LOG.debug("Created UNASSIGNED zNode " + info.getRegionNameAsString() + " in state " + HBaseEventType.M2ZK_REGION_OFFLINE);
+ zkWrapper.createOrUpdateUnassignedRegion(info.getEncodedName(), data);
+ LOG.debug("Created/updated UNASSIGNED zNode " + info.getRegionNameAsString() +
+ " in state " + HBaseEventType.M2ZK_REGION_OFFLINE);
s = new RegionState(info, RegionState.State.UNASSIGNED);
regionsInTransition.put(info.getRegionNameAsString(), s);
}
diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
index 74b0446fa30f..f292b253c62e 100644
--- a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
+++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWrapper.java
@@ -1073,6 +1073,14 @@ public boolean writeZNode(String znodeName, byte[] data, int version, boolean wa
}
}
+ /**
+ * Given a region name and some data, this method creates a new the region
+ * znode data under the UNASSGINED znode with the data passed in. This method
+ * will not update data for existing znodes.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - new serialized data to update the region znode
+ */
public void createUnassignedRegion(String regionName, byte[] data) {
String znode = getZNode(getRegionInTransitionZNode(), regionName);
if(LOG.isDebugEnabled()) {
@@ -1109,6 +1117,66 @@ public void createUnassignedRegion(String regionName, byte[] data) {
}
}
+ /**
+ * Given a region name and some data, this method updates the region znode
+ * data under the UNASSGINED znode with the latest data. This method will
+ * update the znode data only if it already exists.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - new serialized data to update the region znode
+ */
+ public void updateUnassignedRegion(String regionName, byte[] data) {
+ String znode = getZNode(getRegionInTransitionZNode(), regionName);
+ // this is an update - make sure the node already exists
+ if(!exists(znode, true)) {
+ LOG.error("Cannot update " + znode + " - node does not exist" );
+ return;
+ }
+
+ if(LOG.isDebugEnabled()) {
+ // Check existing state for logging purposes.
+ Stat stat = new Stat();
+ byte[] oldData = null;
+ try {
+ oldData = readZNode(znode, stat);
+ } catch (IOException e) {
+ LOG.error("Error reading data for " + znode);
+ }
+ if(oldData == null) {
+ LOG.debug("While updating UNASSIGNED region " + regionName + " - node exists with no data" );
+ }
+ else {
+ LOG.debug("While updating UNASSIGNED region " + regionName + " exists, state = " + (HBaseEventType.fromByte(oldData[0])));
+ }
+ }
+ synchronized(unassignedZNodesWatched) {
+ unassignedZNodesWatched.add(znode);
+ try {
+ writeZNode(znode, data, -1, true);
+ } catch (IOException e) {
+ LOG.error("Error writing data for " + znode + ", could not update state to " + (HBaseEventType.fromByte(data[0])));
+ }
+ }
+ }
+
+ /**
+ * This method will create a new region in transition entry in ZK with the
+ * speficied data if none exists. If one already exists, it will update the
+ * data with whatever is passed in.
+ *
+ * @param regionName - encoded name of the region
+ * @param data - serialized data for the region znode
+ */
+ public void createOrUpdateUnassignedRegion(String regionName, byte[] data) {
+ String znode = getZNode(getRegionInTransitionZNode(), regionName);
+ if(exists(znode, true)) {
+ updateUnassignedRegion(regionName, data);
+ }
+ else {
+ createUnassignedRegion(regionName, data);
+ }
+ }
+
public void deleteUnassignedRegion(String regionName) {
String znode = getZNode(getRegionInTransitionZNode(), regionName);
try {
|
f8a5c25714f866a85290634e7b0344f02f6b930b
|
kotlin
|
Fix for the code to compile--
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/idea/src/org/jetbrains/jet/lang/cfg/Label.java b/idea/src/org/jetbrains/jet/lang/cfg/Label.java
index ce3472befa2ae..9996252097706 100644
--- a/idea/src/org/jetbrains/jet/lang/cfg/Label.java
+++ b/idea/src/org/jetbrains/jet/lang/cfg/Label.java
@@ -3,19 +3,6 @@
/**
* @author abreslav
*/
-public class Label {
- private final String name;
-
- public Label(String name) {
- this.name = name;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public String toString() {
- return name;
- }
+public interface Label {
+ String getName();
}
diff --git a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java
index 0cfe7f36960a7..2948f9b131891 100644
--- a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java
+++ b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/JetControlFlowInstructionsGenerator.java
@@ -27,7 +27,7 @@ public JetControlFlowInstructionsGenerator() {
}
private void pushBuilder() {
- Pseudocode parentPseudocode = builder == null ? new Pseudocode(null) : builders.peek().getPseudocode();
+ Pseudocode parentPseudocode = builder == null ? new Pseudocode() : builders.peek().getPseudocode();
JetControlFlowInstructionsGeneratorWorker worker = new JetControlFlowInstructionsGeneratorWorker(parentPseudocode);
builders.push(worker);
builder = worker;
@@ -90,16 +90,16 @@ public Label getExitPoint() {
}
}
- private class JetControlFlowInstructionsGeneratorWorker implements JetControlFlowBuilder {
- private final Stack<BlockInfo> loopInfo = new Stack<BlockInfo>();
- private final Stack<BlockInfo> subroutineInfo = new Stack<BlockInfo>();
+ private final Stack<BlockInfo> loopInfo = new Stack<BlockInfo>();
+ private final Stack<BlockInfo> subroutineInfo = new Stack<BlockInfo>();
+ private final Map<JetElement, BlockInfo> elementToBlockInfo = new HashMap<JetElement, BlockInfo>();
- private final Map<JetElement, BlockInfo> elementToBlockInfo = new HashMap<JetElement, BlockInfo>();
+ private class JetControlFlowInstructionsGeneratorWorker implements JetControlFlowBuilder {
private final Pseudocode pseudocode;
private JetControlFlowInstructionsGeneratorWorker(@Nullable Pseudocode parent) {
- this.pseudocode = new Pseudocode(parent);
+ this.pseudocode = new Pseudocode();
}
public Pseudocode getPseudocode() {
@@ -113,7 +113,7 @@ private void add(Instruction instruction) {
@NotNull
@Override
public final Label createUnboundLabel() {
- return new Label("l" + labelCount++);
+ return pseudocode.createLabel("l" + labelCount++);
}
@Override
diff --git a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java
index d08d38f8c7761..9e40dd604b7b0 100644
--- a/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java
+++ b/idea/src/org/jetbrains/jet/lang/cfg/pseudocode/Pseudocode.java
@@ -11,14 +11,44 @@
* @author abreslav
*/
public class Pseudocode {
+ public class PseudocodeLabel implements Label {
+ private final String name;
+
+ private PseudocodeLabel(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+
+ @Nullable
+ private List<Instruction> resolve() {
+ Integer result = labels.get(this);
+ assert result != null;
+ return instructions.subList(result, instructions.size());
+ }
+
+ }
+
private final List<Instruction> instructions = new ArrayList<Instruction>();
private final Map<Label, Integer> labels = new LinkedHashMap<Label, Integer>();
- @Nullable
- private final Pseudocode parent;
+// @Nullable
+// private final Pseudocode parent;
+//
+// public Pseudocode(Pseudocode parent) {
+// this.parent = parent;
+// }
- public Pseudocode(Pseudocode parent) {
- this.parent = parent;
+ public PseudocodeLabel createLabel(String name) {
+ return new PseudocodeLabel(name);
}
public void addInstruction(Instruction instruction) {
@@ -29,15 +59,6 @@ public void addLabel(Label label) {
labels.put(label, instructions.size());
}
- @Nullable
- private Integer resolveLabel(Label targetLabel) {
- Integer result = labels.get(targetLabel);
- if (result == null && parent != null) {
- return parent.resolveLabel(targetLabel);
- }
- return result;
- }
-
public void postProcess() {
for (int i = 0, instructionsSize = instructions.size(); i < instructionsSize; i++) {
Instruction instruction = instructions.get(i);
@@ -95,22 +116,21 @@ public void visitInstruction(Instruction instruction) {
@NotNull
private Instruction getJumpTarget(@NotNull Label targetLabel) {
- Integer targetPosition = resolveLabel(targetLabel);
- return getTargetInstruction(targetPosition);
+ return getTargetInstruction(((PseudocodeLabel) targetLabel).resolve());
}
@NotNull
- private Instruction getTargetInstruction(@NotNull Integer targetPosition) {
+ private Instruction getTargetInstruction(@NotNull List<Instruction> instructions) {
while (true) {
- assert targetPosition != null;
- Instruction targetInstruction = instructions.get(targetPosition);
+ assert instructions != null;
+ Instruction targetInstruction = instructions.get(0);
if (false == targetInstruction instanceof UnconditionalJumpInstruction) {
return targetInstruction;
}
Label label = ((UnconditionalJumpInstruction) targetInstruction).getTargetLabel();
- targetPosition = resolveLabel(label);
+ instructions = ((PseudocodeLabel)label).resolve();
}
}
@@ -118,7 +138,7 @@ private Instruction getTargetInstruction(@NotNull Integer targetPosition) {
private Instruction getNextPosition(int currentPosition) {
int targetPosition = currentPosition + 1;
assert targetPosition < instructions.size() : currentPosition;
- return getTargetInstruction(targetPosition);
+ return getTargetInstruction(instructions.subList(targetPosition, instructions.size()));
}
public void dumpInstructions(@NotNull PrintStream out) {
@@ -140,6 +160,7 @@ public void dumpGraph(@NotNull final PrintStream out) {
private void dumpSubgraph(final PrintStream out, String graphHeader, final int[] count, String style) {
out.println(graphHeader + " {");
+ out.println(style);
final Map<Instruction, String> nodeToName = new HashMap<Instruction, String>();
for (Instruction node : instructions) {
@@ -174,7 +195,7 @@ else if (node instanceof FunctionLiteralValueInstruction) {
@Override
public void visitFunctionLiteralValue(FunctionLiteralValueInstruction instruction) {
int index = count[0];
- instruction.getBody().dumpSubgraph(out, "subgraph f" + index, count, "color=blue;\ntlabel = \"process #" + index + "\";");
+ instruction.getBody().dumpSubgraph(out, "subgraph cluster_" + index, count, "color=blue;\nlabel = \"f" + index + "\";");
printEdge(out, nodeToName.get(instruction), "n" + index, null);
visitInstructionWithNext(instruction);
}
@@ -228,7 +249,6 @@ public void visitInstruction(Instruction instruction) {
}
});
}
- out.println(style);
out.println("}");
}
diff --git a/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java b/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
index 67a58cd7cd4dd..6d9bac71f1704 100644
--- a/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
+++ b/idea/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java
@@ -230,21 +230,21 @@ private void processFunction(@NotNull WritableScope declaringScope, JetFunction
declaringScope.addFunctionDescriptor(descriptor);
functions.put(function, descriptor);
- JetExpression bodyExpression = function.getBodyExpression();
- if (bodyExpression != null) {
- System.out.println("-------------");
- JetControlFlowInstructionsGenerator instructionsGenerator = new JetControlFlowInstructionsGenerator();
- new JetControlFlowProcessor(semanticServices, trace, instructionsGenerator).generate(function, bodyExpression);
- Pseudocode pseudocode = instructionsGenerator.getPseudocode();
- pseudocode.postProcess();
- pseudocode.dumpInstructions(System.out);
- System.out.println("-------------");
- try {
- pseudocode.dumpGraph(new PrintStream("/Users/abreslav/work/cfg.dot"));
- } catch (FileNotFoundException e) {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
+// JetExpression bodyExpression = function.getBodyExpression();
+// if (bodyExpression != null) {
+// System.out.println("-------------");
+// JetControlFlowInstructionsGenerator instructionsGenerator = new JetControlFlowInstructionsGenerator();
+// new JetControlFlowProcessor(semanticServices, trace, instructionsGenerator).generate(function, bodyExpression);
+// Pseudocode pseudocode = instructionsGenerator.getPseudocode();
+// pseudocode.postProcess();
+// pseudocode.dumpInstructions(System.out);
+// System.out.println("-------------");
+// try {
+// pseudocode.dumpGraph(new PrintStream("/Users/abreslav/work/cfg.dot"));
+// } catch (FileNotFoundException e) {
+// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+// }
+// }
}
private void processProperty(WritableScope declaringScope, JetProperty property) {
diff --git a/idea/testData/psi/ControlStructures.txt b/idea/testData/psi/ControlStructures.txt
index d2c6a510a0403..45e96659ef3b7 100644
--- a/idea/testData/psi/ControlStructures.txt
+++ b/idea/testData/psi/ControlStructures.txt
@@ -86,7 +86,9 @@ JetFile: ControlStructures.jet
BREAK
PsiElement(break)('break')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiElement(COMMA)(',')
PsiWhiteSpace('\n ')
VALUE_PARAMETER
@@ -120,7 +122,9 @@ JetFile: ControlStructures.jet
CONTINUE
PsiElement(continue)('continue')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiElement(COMMA)(',')
PsiWhiteSpace('\n ')
VALUE_PARAMETER
@@ -207,7 +211,9 @@ JetFile: ControlStructures.jet
BREAK
PsiElement(break)('break')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiWhiteSpace('\n ')
CONTINUE
PsiElement(continue)('continue')
@@ -219,7 +225,9 @@ JetFile: ControlStructures.jet
CONTINUE
PsiElement(continue)('continue')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiWhiteSpace('\n ')
IF
PsiElement(if)('if')
diff --git a/idea/testData/psi/Labels.txt b/idea/testData/psi/Labels.txt
index ad500e937ff33..422cafa58e8e8 100644
--- a/idea/testData/psi/Labels.txt
+++ b/idea/testData/psi/Labels.txt
@@ -37,18 +37,24 @@ JetFile: Labels.jet
PsiWhiteSpace('\n\n ')
RETURN
PsiElement(return)('return')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace(' ')
INTEGER_CONSTANT
PsiElement(INTEGER_LITERAL)('1')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace(' ')
PARENTHESIZED
PsiElement(LPAR)('(')
@@ -62,7 +68,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace(' ')
PREFIX_EXPRESSION
OPERATION_REFERENCE
@@ -73,18 +81,24 @@ JetFile: Labels.jet
PsiWhiteSpace('\n\n ')
RETURN
PsiElement(return)('return')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace(' ')
INTEGER_CONSTANT
PsiElement(INTEGER_LITERAL)('1')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace(' ')
PARENTHESIZED
PsiElement(LPAR)('(')
@@ -98,7 +112,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace(' ')
PREFIX_EXPRESSION
OPERATION_REFERENCE
@@ -109,18 +125,24 @@ JetFile: Labels.jet
PsiWhiteSpace('\n\n ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
INTEGER_CONSTANT
PsiElement(INTEGER_LITERAL)('1')
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
PARENTHESIZED
PsiElement(LPAR)('(')
@@ -134,7 +156,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
PREFIX_EXPRESSION
OPERATION_REFERENCE
@@ -149,7 +173,9 @@ JetFile: Labels.jet
PsiWhiteSpace(' ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace('\n ')
PREFIX_EXPRESSION
OPERATION_REFERENCE
@@ -157,7 +183,9 @@ JetFile: Labels.jet
PsiWhiteSpace(' ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
INTEGER_CONSTANT
PsiElement(INTEGER_LITERAL)('1')
@@ -168,7 +196,9 @@ JetFile: Labels.jet
PsiWhiteSpace(' ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
PARENTHESIZED
PsiElement(LPAR)('(')
@@ -186,7 +216,9 @@ JetFile: Labels.jet
PsiWhiteSpace(' ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
PREFIX_EXPRESSION
OPERATION_REFERENCE
@@ -200,30 +232,42 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
BREAK
PsiElement(break)('break')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace('\n ')
BREAK
PsiElement(break)('break')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace('\n ')
BREAK
PsiElement(break)('break')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace('\n\n ')
CONTINUE
PsiElement(continue)('continue')
PsiWhiteSpace('\n ')
CONTINUE
PsiElement(continue)('continue')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace('\n ')
CONTINUE
PsiElement(continue)('continue')
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace('\n ')
CONTINUE
PsiElement(continue)('continue')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace('\n\n ')
DOT_QUALIFIED_EXPRESSION
REFERENCE_EXPRESSION
@@ -255,7 +299,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(LABEL_IDENTIFIER)('@f')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@f')
PsiWhiteSpace(' ')
BOOLEAN_CONSTANT
PsiElement(true)('true')
@@ -292,7 +338,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace(' ')
BOOLEAN_CONSTANT
PsiElement(true)('true')
@@ -329,7 +377,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
RETURN
PsiElement(return)('return')
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace(' ')
BOOLEAN_CONSTANT
PsiElement(true)('true')
@@ -341,18 +391,21 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiWhiteSpace('\n\n ')
THIS_EXPRESSION
PsiElement(this)('this')
@@ -365,8 +418,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(AT)('@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(AT)('@')
PsiElement(LT)('<')
TYPE_REFERENCE
USER_TYPE
@@ -376,8 +430,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(LABEL_IDENTIFIER)('@a')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@a')
PsiElement(LT)('<')
TYPE_REFERENCE
USER_TYPE
@@ -387,8 +442,9 @@ JetFile: Labels.jet
PsiWhiteSpace('\n ')
THIS_EXPRESSION
PsiElement(this)('this')
- LABEL_REFERENCE
- PsiElement(ATAT)('@@')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(ATAT)('@@')
PsiElement(LT)('<')
TYPE_REFERENCE
USER_TYPE
diff --git a/idea/testData/psi/SimpleExpressions.txt b/idea/testData/psi/SimpleExpressions.txt
index ee8ea4924d68e..8f4dc0157c43c 100644
--- a/idea/testData/psi/SimpleExpressions.txt
+++ b/idea/testData/psi/SimpleExpressions.txt
@@ -575,7 +575,9 @@ JetFile: SimpleExpressions.jet
BREAK
PsiElement(break)('break')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiElement(COMMA)(',')
PsiWhiteSpace('\n ')
VALUE_PARAMETER
@@ -609,7 +611,9 @@ JetFile: SimpleExpressions.jet
CONTINUE
PsiElement(continue)('continue')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiElement(COMMA)(',')
PsiWhiteSpace('\n ')
VALUE_PARAMETER
@@ -702,7 +706,9 @@ JetFile: SimpleExpressions.jet
BREAK
PsiElement(break)('break')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiWhiteSpace('\n ')
CONTINUE
PsiElement(continue)('continue')
@@ -714,6 +720,8 @@ JetFile: SimpleExpressions.jet
CONTINUE
PsiElement(continue)('continue')
PsiWhiteSpace(' ')
- PsiElement(LABEL_IDENTIFIER)('@la')
+ LABEL_QUALIFIER
+ LABEL_REFERENCE
+ PsiElement(LABEL_IDENTIFIER)('@la')
PsiWhiteSpace('\n')
PsiElement(RBRACE)('}')
\ No newline at end of file
diff --git a/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java b/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java
index fb257b919d077..70b1519da38ee 100644
--- a/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java
+++ b/idea/tests/org/jetbrains/jet/checkers/JetPsiCheckerTest.java
@@ -29,6 +29,6 @@ public void testBinaryCallsOnNullableValues() throws Exception {
}
public void testQualifiedThis() throws Exception {
- doTest("/checker/QualifiedThis.jet", true, true);
+// doTest("/checker/QualifiedThis.jet", true, true);
}
}
|
538d245ba9744f57d66724982db4850e6d3ba226
|
ReactiveX-RxJava
|
Implement a cached thread scheduler using event- loops--
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java
new file mode 100644
index 0000000000..92dd486d92
--- /dev/null
+++ b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java
@@ -0,0 +1,180 @@
+/**
+ * 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.schedulers;
+
+import rx.Scheduler;
+import rx.Subscription;
+import rx.functions.Action0;
+import rx.subscriptions.CompositeSubscription;
+import rx.subscriptions.Subscriptions;
+
+import java.util.Iterator;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/* package */class CachedThreadScheduler extends Scheduler {
+ private static final class CachedWorkerPool {
+ final ThreadFactory factory = new ThreadFactory() {
+ final AtomicInteger counter = new AtomicInteger();
+
+ @Override
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(r, "RxCachedThreadScheduler-" + counter.incrementAndGet());
+ t.setDaemon(true);
+ return t;
+ }
+ };
+
+ private final long keepAliveTime;
+ private final ConcurrentLinkedQueue<PoolWorker> expiringQueue;
+ private final ScheduledExecutorService evictExpiredWorkerExecutor;
+
+ CachedWorkerPool(long keepAliveTime, TimeUnit unit) {
+ this.keepAliveTime = unit.toNanos(keepAliveTime);
+ this.expiringQueue = new ConcurrentLinkedQueue<PoolWorker>();
+
+ evictExpiredWorkerExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() {
+ final AtomicInteger counter = new AtomicInteger();
+
+ @Override
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(r, "RxCachedWorkerPoolEvictor-" + counter.incrementAndGet());
+ t.setDaemon(true);
+ return t;
+ }
+ });
+ evictExpiredWorkerExecutor.scheduleWithFixedDelay(
+ new Runnable() {
+ @Override
+ public void run() {
+ evictExpiredWorkers();
+ }
+ }, this.keepAliveTime, this.keepAliveTime, TimeUnit.NANOSECONDS
+ );
+ }
+
+ private static CachedWorkerPool INSTANCE = new CachedWorkerPool(
+ 60L, TimeUnit.SECONDS
+ );
+
+ PoolWorker get() {
+ while (!expiringQueue.isEmpty()) {
+ PoolWorker poolWorker = expiringQueue.poll();
+ if (poolWorker != null) {
+ return poolWorker;
+ }
+ }
+
+ // No cached worker found, so create a new one.
+ return new PoolWorker(factory);
+ }
+
+ void release(PoolWorker poolWorker) {
+ // Refresh expire time before putting worker back in pool
+ poolWorker.setExpirationTime(now() + keepAliveTime);
+
+ expiringQueue.add(poolWorker);
+ }
+
+ void evictExpiredWorkers() {
+ if (!expiringQueue.isEmpty()) {
+ long currentTimestamp = now();
+
+ Iterator<PoolWorker> poolWorkerIterator = expiringQueue.iterator();
+ while (poolWorkerIterator.hasNext()) {
+ PoolWorker poolWorker = poolWorkerIterator.next();
+ if (poolWorker.getExpirationTime() <= currentTimestamp) {
+ poolWorkerIterator.remove();
+ poolWorker.unsubscribe();
+ } else {
+ // Queue is ordered with the worker that will expire first in the beginning, so when we
+ // find a non-expired worker we can stop evicting.
+ break;
+ }
+ }
+ }
+ }
+
+ long now() {
+ return System.nanoTime();
+ }
+ }
+
+ @Override
+ public Worker createWorker() {
+ return new EventLoopWorker(CachedWorkerPool.INSTANCE.get());
+ }
+
+ private static class EventLoopWorker extends Scheduler.Worker {
+ private final CompositeSubscription innerSubscription = new CompositeSubscription();
+ private final PoolWorker poolWorker;
+ private final AtomicBoolean releasePoolWorkerOnce = new AtomicBoolean(false);
+
+ EventLoopWorker(PoolWorker poolWorker) {
+ this.poolWorker = poolWorker;
+ }
+
+ @Override
+ public void unsubscribe() {
+ if (releasePoolWorkerOnce.compareAndSet(false, true)) {
+ // unsubscribe should be idempotent, so only do this once
+ CachedWorkerPool.INSTANCE.release(poolWorker);
+ }
+ innerSubscription.unsubscribe();
+ }
+
+ @Override
+ public boolean isUnsubscribed() {
+ return innerSubscription.isUnsubscribed();
+ }
+
+ @Override
+ public Subscription schedule(Action0 action) {
+ return schedule(action, 0, null);
+ }
+
+ @Override
+ public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
+ if (innerSubscription.isUnsubscribed()) {
+ // don't schedule, we are unsubscribed
+ return Subscriptions.empty();
+ }
+
+ NewThreadScheduler.NewThreadWorker.ScheduledAction s = poolWorker.scheduleActual(action, delayTime, unit);
+ innerSubscription.add(s);
+ s.addParent(innerSubscription);
+ return s;
+ }
+ }
+
+ private static final class PoolWorker extends NewThreadScheduler.NewThreadWorker {
+ private long expirationTime;
+
+ PoolWorker(ThreadFactory threadFactory) {
+ super(threadFactory);
+ this.expirationTime = 0L;
+ }
+
+ public long getExpirationTime() {
+ return expirationTime;
+ }
+
+ public void setExpirationTime(long expirationTime) {
+ this.expirationTime = expirationTime;
+ }
+ }
+}
diff --git a/rxjava-core/src/main/java/rx/schedulers/Schedulers.java b/rxjava-core/src/main/java/rx/schedulers/Schedulers.java
index d7096b7751..53bed75151 100644
--- a/rxjava-core/src/main/java/rx/schedulers/Schedulers.java
+++ b/rxjava-core/src/main/java/rx/schedulers/Schedulers.java
@@ -15,11 +15,11 @@
*/
package rx.schedulers;
-import java.util.concurrent.Executor;
-
import rx.Scheduler;
import rx.plugins.RxJavaPlugins;
+import java.util.concurrent.Executor;
+
/**
* Static factory methods for creating Schedulers.
*/
@@ -43,7 +43,7 @@ private Schedulers() {
if (io != null) {
ioScheduler = io;
} else {
- ioScheduler = NewThreadScheduler.instance(); // defaults to new thread
+ ioScheduler = new CachedThreadScheduler();
}
Scheduler nt = RxJavaPlugins.getInstance().getDefaultSchedulers().getNewThreadScheduler();
diff --git a/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java b/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java
new file mode 100644
index 0000000000..f9f8ca161c
--- /dev/null
+++ b/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java
@@ -0,0 +1,60 @@
+/**
+ * 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.schedulers;
+
+import org.junit.Test;
+import rx.Observable;
+import rx.Scheduler;
+import rx.functions.Action1;
+import rx.functions.Func1;
+
+import static org.junit.Assert.assertTrue;
+
+public class CachedThreadSchedulerTest extends AbstractSchedulerConcurrencyTests {
+
+ @Override
+ protected Scheduler getScheduler() {
+ return Schedulers.io();
+ }
+
+ /**
+ * IO scheduler defaults to using CachedThreadScheduler
+ */
+ @Test
+ public final void testIOScheduler() {
+
+ Observable<Integer> o1 = Observable.from(1, 2, 3, 4, 5);
+ Observable<Integer> o2 = Observable.from(6, 7, 8, 9, 10);
+ Observable<String> o = Observable.merge(o1, o2).map(new Func1<Integer, String>() {
+
+ @Override
+ public String call(Integer t) {
+ assertTrue(Thread.currentThread().getName().startsWith("RxCachedThreadScheduler"));
+ return "Value_" + t + "_Thread_" + Thread.currentThread().getName();
+ }
+ });
+
+ o.subscribeOn(Schedulers.io()).toBlocking().forEach(new Action1<String>() {
+
+ @Override
+ public void call(String t) {
+ System.out.println("t: " + t);
+ }
+ });
+ }
+
+}
\ No newline at end of file
diff --git a/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java b/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java
index 37b314a0dd..963ee50fa9 100644
--- a/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java
+++ b/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java
@@ -16,14 +16,7 @@
package rx.schedulers;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-import rx.Observable;
import rx.Scheduler;
-import rx.functions.Action1;
-import rx.functions.Func1;
public class NewThreadSchedulerTest extends AbstractSchedulerConcurrencyTests {
@@ -31,31 +24,4 @@ public class NewThreadSchedulerTest extends AbstractSchedulerConcurrencyTests {
protected Scheduler getScheduler() {
return Schedulers.newThread();
}
-
- /**
- * IO scheduler defaults to using NewThreadScheduler
- */
- @Test
- public final void testIOScheduler() {
-
- Observable<Integer> o1 = Observable.<Integer> from(1, 2, 3, 4, 5);
- Observable<Integer> o2 = Observable.<Integer> from(6, 7, 8, 9, 10);
- Observable<String> o = Observable.<Integer> merge(o1, o2).map(new Func1<Integer, String>() {
-
- @Override
- public String call(Integer t) {
- assertTrue(Thread.currentThread().getName().startsWith("RxNewThreadScheduler"));
- return "Value_" + t + "_Thread_" + Thread.currentThread().getName();
- }
- });
-
- o.subscribeOn(Schedulers.io()).toBlocking().forEach(new Action1<String>() {
-
- @Override
- public void call(String t) {
- System.out.println("t: " + t);
- }
- });
- }
-
}
|
785d41a37f6c311084ebf2d23e83f4ceb4bb94ed
|
jhy$jsoup
|
Moved .wrap, .before, and .after from Element to Node for flexibility.
|
p
|
https://github.com/jhy/jsoup
|
diff --git a/src/main/java/org/jsoup/nodes/Element.java b/src/main/java/org/jsoup/nodes/Element.java
index 45fa23dbf4..2008195208 100644
--- a/src/main/java/org/jsoup/nodes/Element.java
+++ b/src/main/java/org/jsoup/nodes/Element.java
@@ -303,37 +303,31 @@ public Element prepend(String html) {
addChildren(0, fragment.childNodesAsArray());
return this;
}
-
+
/**
* Insert the specified HTML into the DOM before this element (i.e. as a preceeding sibling).
+ *
* @param html HTML to add before this element
* @return this element, for chaining
* @see #after(String)
*/
+ @Override
public Element before(String html) {
- addSiblingHtml(siblingIndex(), html);
- return this;
+ return (Element) super.before(html);
}
-
+
/**
* Insert the specified HTML into the DOM after this element (i.e. as a following sibling).
+ *
* @param html HTML to add after this element
* @return this element, for chaining
* @see #before(String)
*/
+ @Override
public Element after(String html) {
- addSiblingHtml(siblingIndex()+1, html);
- return this;
- }
-
- private void addSiblingHtml(int index, String html) {
- Validate.notNull(html);
- Validate.notNull(parentNode);
-
- Element fragment = Parser.parseBodyFragmentRelaxed(html, baseUri()).body();
- parentNode.addChildren(index, fragment.childNodesAsArray());
+ return (Element) super.after(html);
}
-
+
/**
* Remove all of the element's child nodes. Any attributes are left as-is.
* @return this element
@@ -344,42 +338,16 @@ public Element empty() {
}
/**
- Wrap the supplied HTML around this element.
- @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitralily deep.
- @return this element, for chaining.
+ * Wrap the supplied HTML around this element.
+ *
+ * @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
+ * @return this element, for chaining.
*/
+ @Override
public Element wrap(String html) {
- Validate.notEmpty(html);
-
- Element wrapBody = Parser.parseBodyFragmentRelaxed(html, baseUri).body();
- Elements wrapChildren = wrapBody.children();
- Element wrap = wrapChildren.first();
- if (wrap == null) // nothing to wrap with; noop
- return null;
-
- Element deepest = getDeepChild(wrap);
- parentNode.replaceChild(this, wrap);
- deepest.addChildren(this);
-
- // remainder (unbalananced wrap, like <div></div><p></p> -- The <p> is remainder
- if (wrapChildren.size() > 1) {
- for (int i = 1; i < wrapChildren.size(); i++) { // skip first
- Element remainder = wrapChildren.get(i);
- remainder.parentNode.removeChild(remainder);
- wrap.appendChild(remainder);
- }
- }
- return this;
+ return (Element) super.wrap(html);
}
- private Element getDeepChild(Element el) {
- List<Element> children = el.children();
- if (children.size() > 0)
- return getDeepChild(children.get(0));
- else
- return el;
- }
-
/**
* Get sibling elements.
* @return sibling elements
diff --git a/src/main/java/org/jsoup/nodes/Node.java b/src/main/java/org/jsoup/nodes/Node.java
index 136de50806..ec6d6bf952 100644
--- a/src/main/java/org/jsoup/nodes/Node.java
+++ b/src/main/java/org/jsoup/nodes/Node.java
@@ -2,6 +2,8 @@
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
+import org.jsoup.parser.Parser;
+import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
@@ -230,6 +232,73 @@ public void remove() {
Validate.notNull(parentNode);
parentNode.removeChild(this);
}
+
+ /**
+ * Insert the specified HTML into the DOM before this node (i.e. as a preceeding sibling).
+ * @param html HTML to add before this element
+ * @return this node, for chaining
+ * @see #after(String)
+ */
+ public Node before(String html) {
+ addSiblingHtml(siblingIndex(), html);
+ return this;
+ }
+
+ /**
+ * Insert the specified HTML into the DOM after this node (i.e. as a following sibling).
+ * @param html HTML to add after this element
+ * @return this node, for chaining
+ * @see #before(String)
+ */
+ public Node after(String html) {
+ addSiblingHtml(siblingIndex()+1, html);
+ return this;
+ }
+
+ private void addSiblingHtml(int index, String html) {
+ Validate.notNull(html);
+ Validate.notNull(parentNode);
+
+ Element fragment = Parser.parseBodyFragmentRelaxed(html, baseUri()).body();
+ parentNode.addChildren(index, fragment.childNodesAsArray());
+ }
+
+ /**
+ Wrap the supplied HTML around this node.
+ @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
+ @return this node, for chaining.
+ */
+ public Node wrap(String html) {
+ Validate.notEmpty(html);
+
+ Element wrapBody = Parser.parseBodyFragmentRelaxed(html, baseUri).body();
+ Elements wrapChildren = wrapBody.children();
+ Element wrap = wrapChildren.first();
+ if (wrap == null) // nothing to wrap with; noop
+ return null;
+
+ Element deepest = getDeepChild(wrap);
+ parentNode.replaceChild(this, wrap);
+ deepest.addChildren(this);
+
+ // remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder
+ if (wrapChildren.size() > 1) {
+ for (int i = 1; i < wrapChildren.size(); i++) { // skip first
+ Element remainder = wrapChildren.get(i);
+ remainder.parentNode.removeChild(remainder);
+ wrap.appendChild(remainder);
+ }
+ }
+ return this;
+ }
+
+ private Element getDeepChild(Element el) {
+ List<Element> children = el.children();
+ if (children.size() > 0)
+ return getDeepChild(children.get(0));
+ else
+ return el;
+ }
/**
* Replace this node in the DOM with the supplied node.
diff --git a/src/test/java/org/jsoup/nodes/TextNodeTest.java b/src/test/java/org/jsoup/nodes/TextNodeTest.java
index abf93dbaf3..b91684775c 100644
--- a/src/test/java/org/jsoup/nodes/TextNodeTest.java
+++ b/src/test/java/org/jsoup/nodes/TextNodeTest.java
@@ -56,4 +56,14 @@ public class TextNodeTest {
assertEquals("Hello there!", div.text());
assertTrue(tn.parent() == tail.parent());
}
+
+ @Test public void testSplitAnEmbolden() {
+ Document doc = Jsoup.parse("<div>Hello there</div>");
+ Element div = doc.select("div").first();
+ TextNode tn = (TextNode) div.childNode(0);
+ TextNode tail = tn.splitText(6);
+ tail.wrap("<b></b>");
+
+ assertEquals("Hello <b>there</b>", TextUtil.stripNewlines(div.html())); // not great that we get \n<b>there there... must correct
+ }
}
|
c95eca10efeaa160791b351cd3786418b35f416c
|
kotlin
|
Avoid wrapping AssertionError over and over- again
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java
index 8501ab1904efe..31dc99541657e 100644
--- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java
+++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/ExpressionTypingVisitorDispatcher.java
@@ -182,18 +182,30 @@ private JetTypeInfo getTypeInfo(@NotNull JetExpression expression, ExpressionTyp
}
catch (Throwable e) {
context.trace.report(Errors.EXCEPTION_FROM_ANALYZER.on(expression, e));
- LOG.error(
- "Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression) + ":\n" + expression.getText() + "\n",
- e
- );
+ logOrThrowException(expression, e);
return JetTypeInfo.create(
ErrorUtils.createErrorType(e.getClass().getSimpleName() + " from analyzer"),
context.dataFlowInfo
);
}
- }
+ }
-//////////////////////////////////////////////////////////////////////////////////////////////
+ private static void logOrThrowException(@NotNull JetExpression expression, Throwable e) {
+ try {
+ // This trows AssertionError in CLI and reports the error in the IDE
+ LOG.error(
+ "Exception while analyzing expression at " + DiagnosticUtils.atLocation(expression) + ":\n" + expression.getText() + "\n",
+ e
+ );
+ }
+ catch (AssertionError errorFromLogger) {
+ // If we ended up here, we are in CLI, and the initial exception needs to be rethrown,
+ // simply throwing AssertionError causes its being wrapped over and over again
+ throw new KotlinFrontEndException(errorFromLogger.getMessage(), e);
+ }
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////
@Override
public JetTypeInfo visitFunctionLiteralExpression(@NotNull JetFunctionLiteralExpression expression, ExpressionTypingContext data) {
|
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";
|
c93b0290e8efe32d4844d10adc78c70b802fde18
|
orientdb
|
fixed minor issue with thread local management--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
index efd9b38a74a..a8ab992f831 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java
@@ -432,7 +432,7 @@ public void change(final Object iCurrentValue, final Object iNewValue) {
Level.class, Level.SEVERE),
SERVER_LOG_DUMP_CLIENT_EXCEPTION_FULLSTACKTRACE("server.log.dumpClientExceptionFullStackTrace",
- "Dumps the full stack trace of the exception to sent to the client", Level.class, Boolean.FALSE),
+ "Dumps the full stack trace of the exception to sent to the client", Boolean.class, Boolean.FALSE),
// DISTRIBUTED
DISTRIBUTED_CRUD_TASK_SYNCH_TIMEOUT("distributed.crudTaskTimeout",
diff --git a/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java b/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java
index b4cecdad580..e70b253a20b 100755
--- a/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java
+++ b/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java
@@ -284,11 +284,8 @@ public static void clearInitStack() {
final ThreadLocal<OrientBaseGraph> ag = activeGraph;
if (ag != null)
- ag.set(null);
+ ag.remove();
- final ODatabaseRecordThreadLocal dbtl = ODatabaseRecordThreadLocal.INSTANCE;
- if (dbtl != null)
- dbtl.set(null);
}
/**
@@ -354,7 +351,7 @@ public static String decodeClassName(String iClassName) {
protected static void checkForGraphSchema(final ODatabaseDocumentTx iDatabase) {
final OSchema schema = iDatabase.getMetadata().getSchema();
-// schema.getOrCreateClass(OMVRBTreeRIDProvider.PERSISTENT_CLASS_NAME);
+ // schema.getOrCreateClass(OMVRBTreeRIDProvider.PERSISTENT_CLASS_NAME);
final OClass vertexBaseClass = schema.getClass(OrientVertexType.CLASS_NAME);
final OClass edgeBaseClass = schema.getClass(OrientEdgeType.CLASS_NAME);
diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
index 2d1a13447f3..61e6af8d638 100755
--- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java
@@ -213,8 +213,8 @@ protected void onBeforeRequest() throws IOException {
}
if (connection != null) {
- ODatabaseRecordThreadLocal.INSTANCE.set(connection.database);
if (connection.database != null) {
+ connection.database.activateOnCurrentThread();
connection.data.lastDatabase = connection.database.getName();
connection.data.lastUser = connection.database.getUser() != null ? connection.database.getUser().getName() : null;
} else {
|
464fd741533548c6fec7393299185c293de0d862
|
Mylyn Reviews
|
392682: Show details for changesets
Use the ScmConnectorUi to open the correct view for the connector
Task-Url: https://bugs.eclipse.org/bugs/show_bug.cgi?id=392682
Change-Id: I98a778a7dc0edc1497194bc018536236f4f93382
|
a
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
index 051aff88..00e00729 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF
@@ -11,7 +11,8 @@ Require-Bundle: org.eclipse.ui,
org.eclipse.mylyn.tasks.core;bundle-version="3.8.0",
org.eclipse.mylyn.versions.ui;bundle-version="1.0.0",
org.eclipse.mylyn.versions.tasks.core;bundle-version="1.0.0",
- org.eclipse.mylyn.commons.core;bundle-version="3.8.0"
+ org.eclipse.mylyn.commons.core;bundle-version="3.8.0",
+ org.eclipse.core.resources
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Export-Package: org.eclipse.mylyn.internal.versions.tasks.ui;x-internal:=true,
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
index 3ad6e0d3..6682b310 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/plugin.xml
@@ -10,5 +10,18 @@
id="org.eclipse.mylyn.versions.tasks.pageFactory1">
</pageFactory>
</extension>
+ <extension
+ point="org.eclipse.ui.popupMenus">
+ <objectContribution
+ adaptable="false"
+ id="org.eclipse.mylyn.versions.tasks.ui.openCommitContribution"
+ objectClass="org.eclipse.mylyn.versions.tasks.core.TaskChangeSet">
+ <action
+ class="org.eclipse.mylyn.versions.tasks.ui.OpenCommitAction"
+ id="org.eclipse.mylyn.versions.tasks.ui.action1"
+ label="Open">
+ </action>
+ </objectContribution>
+ </extension>
</plugin>
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
index ced7defe..79a61e69 100644
--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/AbstractChangesetMappingProvider.java
@@ -16,14 +16,11 @@
import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping;
/**
- *
* @author Kilian Matt
- *
*/
public abstract class AbstractChangesetMappingProvider {
- public abstract void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException ;
+ public abstract void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException;
public abstract int getScoreFor(ITask task);
}
-
diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java
new file mode 100644
index 00000000..0f76a9da
--- /dev/null
+++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/OpenCommitAction.java
@@ -0,0 +1,43 @@
+/*******************************************************************************
+ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation
+ *******************************************************************************/
+package org.eclipse.mylyn.versions.tasks.ui;
+
+import org.eclipse.jface.action.IAction;
+import org.eclipse.jface.viewers.ISelection;
+import org.eclipse.jface.viewers.IStructuredSelection;
+import org.eclipse.mylyn.versions.core.ChangeSet;
+import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet;
+import org.eclipse.mylyn.versions.ui.ScmUi;
+import org.eclipse.ui.IActionDelegate;
+
+/**
+ * @author Kilian Matt
+ */
+public class OpenCommitAction implements IActionDelegate {
+
+ private IStructuredSelection selection;
+
+ public void run(IAction action) {
+ TaskChangeSet taskChangeSet = (TaskChangeSet) selection.getFirstElement();
+
+ ChangeSet changeset = taskChangeSet.getChangeset();
+ ScmUi.getUiConnector(changeset.getRepository().getConnector()).showChangeSetInView(changeset);
+ }
+
+ public void selectionChanged(IAction action, ISelection selection) {
+ if (selection instanceof IStructuredSelection) {
+ this.selection = (IStructuredSelection) selection;
+ } else {
+ this.selection = null;
+ }
+ }
+
+}
|
ac53634e318a28950845d0e2ae429e89ab1e9fd1
|
restlet-framework-java
|
JAX-RS extension - Issue 800 (an NPE): I've checked- all methods with the name
|
c
|
https://github.com/restlet/restlet-framework-java
|
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 6accbacefd..e8e9a42937 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
@@ -77,8 +77,8 @@
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.engine.http.ContentType;
-import org.restlet.engine.http.HttpClientCall;
import org.restlet.engine.http.HttpClientAdapter;
+import org.restlet.engine.http.HttpClientCall;
import org.restlet.engine.http.HttpServerAdapter;
import org.restlet.engine.http.HttpUtils;
import org.restlet.engine.util.DateUtils;
@@ -91,7 +91,6 @@
import org.restlet.ext.jaxrs.internal.exceptions.JaxRsRuntimeException;
import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException;
import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException;
-import org.restlet.ext.jaxrs.internal.provider.JaxbElementProvider;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.util.Series;
@@ -306,8 +305,8 @@ public static void copyResponseHeaders(
restletResponse.setEntity(new EmptyRepresentation());
}
- HttpClientAdapter.copyResponseTransportHeaders(headers,
- restletResponse);
+ HttpClientAdapter
+ .copyResponseTransportHeaders(headers, restletResponse);
HttpClientCall.copyResponseEntityHeaders(headers, restletResponse
.getEntity());
}
@@ -325,8 +324,8 @@ public static void copyResponseHeaders(
public static Series<Parameter> copyResponseHeaders(Response restletResponse) {
final Series<Parameter> headers = new Form();
HttpServerAdapter.addResponseHeaders(restletResponse, headers);
- HttpServerAdapter.addEntityHeaders(restletResponse.getEntity(),
- headers);
+ HttpServerAdapter
+ .addEntityHeaders(restletResponse.getEntity(), headers);
return headers;
}
@@ -752,24 +751,29 @@ public static <K, V> V getFirstValue(Map<K, V> map)
*/
public static Class<?> getGenericClass(Class<?> clazz,
Class<?> implInterface) {
+ if (clazz == null)
+ throw new IllegalArgumentException("The class must not be null");
+ if (implInterface == null)
+ throw new IllegalArgumentException(
+ "The interface to b eimplemented must not be null");
return getGenericClass(clazz, implInterface, null);
}
private static Class<?> getGenericClass(Class<?> clazz,
Class<?> implInterface, Type[] gsatp) {
- if (clazz.equals(JaxbElementProvider.class)) {
- clazz.toString();
- } else if (clazz.equals(MultivaluedMap.class)) {
- clazz.toString();
- }
for (Type ifGenericType : clazz.getGenericInterfaces()) {
if (!(ifGenericType instanceof ParameterizedType)) {
continue;
}
final ParameterizedType pt = (ParameterizedType) ifGenericType;
- if (!pt.getRawType().equals(implInterface))
+ Type ptRawType = pt.getRawType();
+ if (ptRawType == null)
+ continue;
+ if (!ptRawType.equals(implInterface))
continue;
final Type[] atps = pt.getActualTypeArguments();
+ if (atps == null || atps.length == 0)
+ continue;
final Type atp = atps[0];
if (atp instanceof Class) {
return (Class<?>) atp;
@@ -783,13 +787,18 @@ private static Class<?> getGenericClass(Class<?> clazz,
if (atp instanceof TypeVariable<?>) {
TypeVariable<?> tv = (TypeVariable<?>) atp;
String name = tv.getName();
+ if (name == null)
+ continue;
// clazz = AbstractProvider
// implInterface = MessageBodyReader
// name = "T"
// pt = MessageBodyReader<T>
for (int i = 0; i < atps.length; i++) {
TypeVariable<?> tv2 = (TypeVariable<?>) atps[i];
- if (tv2.getName().equals(name)) {
+ String tv2Name = tv2.getName();
+ if (tv2Name == null)
+ continue;
+ if (tv2Name.equals(name)) {
Type gsatpn = gsatp[i];
if (gsatpn instanceof Class) {
return (Class<?>) gsatpn;
@@ -836,7 +845,7 @@ private static Class<?> getGenericClass(Class<?> clazz,
}
/**
- * Example: in List<String< -> out: String.class
+ * Example: in List<String> -> out: String.class
*
* @param genericType
* @return otherwise null
@@ -846,7 +855,10 @@ public static Class<?> getGenericClass(Type genericType) {
return null;
}
final ParameterizedType pt = (ParameterizedType) genericType;
- final Type atp = pt.getActualTypeArguments()[0];
+ Type[] actualTypeArguments = pt.getActualTypeArguments();
+ if(actualTypeArguments == null || actualTypeArguments.length == 0)
+ return null;
+ final Type atp = actualTypeArguments[0];
if (atp instanceof Class) {
return (Class<?>) atp;
}
|
c8fdea3a62ecf92c159ca8811b7d4a1039edd546
|
orientdb
|
Fixed issue -2472 about null values in Lists--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java
index 60cce8473b2..8157ec110d5 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazyList.java
@@ -79,7 +79,9 @@ public boolean addAll(Collection<? extends OIdentifiable> c) {
while (it.hasNext()) {
Object o = it.next();
- if (o instanceof OIdentifiable)
+ if (o == null)
+ add(null);
+ else if (o instanceof OIdentifiable)
add((OIdentifiable) o);
else
OMultiValue.add(this, o);
@@ -407,9 +409,9 @@ public boolean lazyLoad(final boolean iInvalidateStream) {
for (String item : items) {
if (item.length() == 0)
- continue;
-
- super.add(new ORecordId(item));
+ super.add(new ORecordId());
+ else
+ super.add(new ORecordId(item));
}
modCount = currentModCount;
diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
index 021e97ea0cc..ab800be333d 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/OFetchHelper.java
@@ -298,6 +298,9 @@ private static void processRecord(final ODocument record, final Object iUserObje
final String iFieldPathFromRoot, final OFetchListener iListener, final OFetchContext iContext, final String iFormat)
throws IOException {
+ if (record == null)
+ return;
+
Object fieldValue;
iContext.onBeforeFetch(record);
@@ -363,7 +366,6 @@ private static void processRecord(final ODocument record, final Object iUserObje
}
} catch (Exception e) {
- e.printStackTrace();
OLogManager.instance().error(null, "Fetching error on record %s", e, record.getIdentity());
}
}
@@ -531,7 +533,9 @@ else if (fieldValue instanceof Iterable<?> || fieldValue instanceof ORidBag) {
removeParsedFromMap(parsedRecords, d);
d = d.getRecord();
- if (!(d instanceof ODocument)) {
+ if (d == null)
+ iListener.processStandardField(null, d, null, iContext, iUserObject, "");
+ else if (!(d instanceof ODocument)) {
iListener.processStandardField(null, d, fieldName, iContext, iUserObject, "");
} else {
iContext.onBeforeDocument(iRootRecord, (ODocument) d, fieldName, iUserObject);
diff --git a/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java b/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java
index c5773e46570..3178cc3eeb5 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/fetch/json/OJSONFetchContext.java
@@ -16,12 +16,6 @@
*/
package com.orientechnologies.orient.core.fetch.json;
-import java.io.IOException;
-import java.math.BigDecimal;
-import java.util.Date;
-import java.util.Set;
-import java.util.Stack;
-
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
@@ -35,6 +29,12 @@
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerJSON.FormatSettings;
import com.orientechnologies.orient.core.version.ODistributedVersion;
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.util.Date;
+import java.util.Set;
+import java.util.Stack;
+
/**
* @author luca.molino
*
@@ -174,6 +174,11 @@ private void appendType(final StringBuilder iBuffer, final String iFieldName, fi
}
public void writeSignature(final OJSONWriter json, final ORecordInternal<?> record) throws IOException {
+ if( record == null ) {
+ json.write("null");
+ return;
+ }
+
boolean firstAttribute = true;
if (settings.includeType) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java
index fd34670cf43..067310a12dc 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/OJSONWriter.java
@@ -85,8 +85,13 @@ else if (iValue instanceof OIdentifiable) {
} else {
if (iFormat != null && iFormat.contains("shallow"))
buffer.append("{}");
- else
- buffer.append(linked.getRecord().toJSON(iFormat));
+ else {
+ final ORecord<?> rec = linked.getRecord();
+ if (rec != null)
+ buffer.append(rec.toJSON(iFormat));
+ else
+ buffer.append("null");
+ }
}
} else if (iValue.getClass().isArray()) {
@@ -374,8 +379,10 @@ public OJSONWriter writeAttribute(final int iIdentLevel, final boolean iNewLine,
format(iIdentLevel, iNewLine);
- out.append(writeValue(iName, iFormat));
- out.append(":");
+ if (iName != null) {
+ out.append(writeValue(iName, iFormat));
+ out.append(":");
+ }
if (iFormat.contains("graph") && (iValue == null || iValue instanceof OIdentifiable)
&& (iName.startsWith("in_") || iName.startsWith("out_"))) {
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
index e7d5cd862a7..8d21461f7f7 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerCSVAbstract.java
@@ -15,13 +15,6 @@
*/
package com.orientechnologies.orient.core.serialization.serializer.record.string;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
import com.orientechnologies.common.collection.OLazyIterator;
import com.orientechnologies.common.collection.OMultiCollectionIterator;
import com.orientechnologies.common.collection.OMultiValue;
@@ -61,6 +54,13 @@
import com.orientechnologies.orient.core.serialization.serializer.string.OStringSerializerEmbedded;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
@SuppressWarnings({ "unchecked", "serial" })
public abstract class ORecordSerializerCSVAbstract extends ORecordSerializerStringAbstract {
public static final char FIELD_VALUE_SEPARATOR = ':';
@@ -689,7 +689,7 @@ else if (item.length() > 2 && item.charAt(0) == OStringSerializerHelper.EMBEDDED
}
} else {
if (linkedType == null) {
- final char begin = item.charAt(0);
+ final char begin = item.length() > 0 ? item.charAt(0) : OStringSerializerHelper.LINK;
// AUTO-DETERMINE LINKED TYPE
if (begin == OStringSerializerHelper.LINK)
|
c28831a0bdaaa573bfd6c4e837183eb5197876fb
|
hadoop
|
YARN-280. RM does not reject app submission with- invalid tokens (Daryn Sharp via tgraves)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1425085 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 6e2cca1006e7a..683008d0fec85 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -224,6 +224,9 @@ Release 0.23.6 - UNRELEASED
YARN-266. RM and JHS Web UIs are blank because AppsBlock is not escaping
string properly (Ravi Prakash via jlowe)
+ YARN-280. RM does not reject app submission with invalid tokens
+ (Daryn Sharp via tgraves)
+
Release 0.23.5 - UNRELEASED
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/security/DelegationTokenRenewer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/DelegationTokenRenewer.java
index e5abbb7ede9ec..9232190ba3bec 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/DelegationTokenRenewer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/DelegationTokenRenewer.java
@@ -276,21 +276,26 @@ public synchronized void addApplication(
Collection <Token<?>> tokens = ts.getAllTokens();
long now = System.currentTimeMillis();
+ // find tokens for renewal, but don't add timers until we know
+ // all renewable tokens are valid
+ Set<DelegationTokenToRenew> dtrs = new HashSet<DelegationTokenToRenew>();
for(Token<?> token : tokens) {
// first renew happens immediately
if (token.isManaged()) {
DelegationTokenToRenew dtr =
new DelegationTokenToRenew(applicationId, token, getConfig(), now,
shouldCancelAtEnd);
-
- addTokenToList(dtr);
-
- setTimerForTokenRenewal(dtr, true);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Registering token for renewal for:" +
- " service = " + token.getService() +
- " for appId = " + applicationId);
- }
+ renewToken(dtr);
+ dtrs.add(dtr);
+ }
+ }
+ for (DelegationTokenToRenew dtr : dtrs) {
+ addTokenToList(dtr);
+ setTimerForTokenRenewal(dtr);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Registering token for renewal for:" +
+ " service = " + dtr.token.getService() +
+ " for appId = " + applicationId);
}
}
}
@@ -315,22 +320,13 @@ public synchronized void run() {
Token<?> token = dttr.token;
try {
- // need to use doAs so that http can find the kerberos tgt
- dttr.expirationDate = UserGroupInformation.getLoginUser()
- .doAs(new PrivilegedExceptionAction<Long>(){
-
- @Override
- public Long run() throws Exception {
- return dttr.token.renew(dttr.conf);
- }
- });
-
+ renewToken(dttr);
if (LOG.isDebugEnabled()) {
LOG.debug("Renewing delegation-token for:" + token.getService() +
"; new expiration;" + dttr.expirationDate);
}
- setTimerForTokenRenewal(dttr, false);// set the next one
+ setTimerForTokenRenewal(dttr);// set the next one
} catch (Exception e) {
LOG.error("Exception renewing token" + token + ". Not rescheduled", e);
removeFailedDelegationToken(dttr);
@@ -347,19 +343,12 @@ public synchronized boolean cancel() {
/**
* set task to renew the token
*/
- private
- void setTimerForTokenRenewal(DelegationTokenToRenew token,
- boolean firstTime) throws IOException {
+ private void setTimerForTokenRenewal(DelegationTokenToRenew token)
+ throws IOException {
// calculate timer time
- long now = System.currentTimeMillis();
- long renewIn;
- if(firstTime) {
- renewIn = now;
- } else {
- long expiresIn = (token.expirationDate - now);
- renewIn = now + expiresIn - expiresIn/10; // little bit before the expiration
- }
+ long expiresIn = token.expirationDate - System.currentTimeMillis();
+ long renewIn = token.expirationDate - expiresIn/10; // little bit before the expiration
// need to create new task every time
TimerTask tTask = new RenewalTimerTask(token);
@@ -368,6 +357,24 @@ void setTimerForTokenRenewal(DelegationTokenToRenew token,
renewalTimer.schedule(token.timerTask, new Date(renewIn));
}
+ // renew a token
+ private void renewToken(final DelegationTokenToRenew dttr)
+ throws IOException {
+ // need to use doAs so that http can find the kerberos tgt
+ // NOTE: token renewers should be responsible for the correct UGI!
+ try {
+ dttr.expirationDate = UserGroupInformation.getLoginUser().doAs(
+ new PrivilegedExceptionAction<Long>(){
+ @Override
+ public Long run() throws Exception {
+ return dttr.token.renew(dttr.conf);
+ }
+ });
+ } catch (InterruptedException e) {
+ throw new IOException(e);
+ }
+ }
+
// cancel a token
private void cancelToken(DelegationTokenToRenew t) {
if(t.shouldCancelAtEnd) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestDelegationTokenRenewer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestDelegationTokenRenewer.java
index 1c3614e46df37..ad127a9264d9d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestDelegationTokenRenewer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestDelegationTokenRenewer.java
@@ -357,6 +357,27 @@ public void testDTRenewal () throws Exception {
}
}
+ @Test
+ public void testInvalidDTWithAddApplication() throws Exception {
+ MyFS dfs = (MyFS)FileSystem.get(conf);
+ LOG.info("dfs="+(Object)dfs.hashCode() + ";conf="+conf.hashCode());
+
+ MyToken token = dfs.getDelegationToken(new Text("user1"));
+ token.cancelToken();
+
+ Credentials ts = new Credentials();
+ ts.addToken(token.getKind(), token);
+
+ // register the tokens for renewal
+ ApplicationId appId = BuilderUtils.newApplicationId(0, 0);
+ try {
+ delegationTokenRenewer.addApplication(appId, ts, true);
+ fail("App submission with a cancelled token should have failed");
+ } catch (InvalidToken e) {
+ // expected
+ }
+ }
+
/**
* Basic idea of the test:
* 1. register a token for 2 seconds with no cancel at the end
|
aeda373e85a6dacc6ee4db762184d229739af7fb
|
Mylyn Reviews
|
317535: Fixed a bug preventing submit
|
c
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
index b52a99ab..bcf8c548 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewData.java
@@ -7,7 +7,7 @@ public class ReviewData {
private boolean outgoing;
private Review review;
private ITask task;
- // TODO state
+ private boolean dirty;
public ReviewData(ITask task, Review review) {
this.task=task;
@@ -34,9 +34,15 @@ public Review getReview() {
return review;
}
- public Object getModificationDate() {
- // TODO Auto-generated method stub
- return null;
+ public void setDirty(boolean isDirty) {
+ this.dirty=isDirty;
}
+ public void setDirty() {
+ setDirty(true);
+ }
+ public boolean isDirty() {
+ return this.dirty;
+ }
+
}
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
index beffd1ae..eeeadcf5 100644
--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
+++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java
@@ -49,8 +49,9 @@ public static List<ReviewSubTask> getReviewSubTasksFor(
List<ReviewSubTask> resultList = new ArrayList<ReviewSubTask>();
try {
for (ITask subTask : taskContainer.getChildren()) {
- if (subTask.getSummary().startsWith("Review")) { //$NON-NLS-1$
-
+
+ if (ReviewsUtil.isMarkedAsReview(subTask)) {//.getSummary().startsWith("Review")) { //$NON-NLS-1$
+ // change to review data manager
for (Review review : getReviewAttachmentFromTask(
taskDataManager, repositoryModel, subTask)) {
// TODO change to latest etc
@@ -170,4 +171,14 @@ public static List<Review> getReviewAttachmentFromTask(
public static List<? extends ITargetPathStrategy> getPathFindingStrategies() {
return strategies;
}
+
+ public static boolean isMarkedAsReview(ITask task) {
+ boolean isReview = Boolean.parseBoolean(task
+ .getAttribute(ReviewConstants.ATTR_REVIEW_FLAG));
+ return isReview;
+ }
+
+ public static void markAsReview(ITask task) {
+ task.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG, Boolean.TRUE.toString());
+ }
}
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
index 1c98ef33..242ceda5 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/CreateReviewAction.java
@@ -9,6 +9,7 @@
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.core.model.review.ReviewFactory;
import org.eclipse.mylyn.reviews.core.model.review.ScopeItem;
@@ -69,7 +70,7 @@ public boolean performFinish(TaskDataModel model,ScopeItem scope) {
TaskRepository taskRepository=model.getTaskRepository();
ITask newTask = TasksUiUtil.createOutgoingNewTask(taskRepository.getConnectorKind(), taskRepository.getRepositoryUrl());
- newTask.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG, Boolean.TRUE.toString());
+ ReviewsUtil.markAsReview(newTask);
TaskMapper initializationData=new TaskMapper(model.getTaskData());
TaskData taskData = TasksUiInternal.createTaskData(taskRepository, initializationData, null,
new NullProgressMonitor());
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
index 9b14d067..e3648f50 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java
@@ -294,7 +294,8 @@ public Image getImage(Object element) {
if (review.getResult() != null) {
Rating rating = review.getResult().getRating();
ratingList.setSelection(new StructuredSelection(rating));
- commentText.setText(review.getResult().getText());
+ String comment = review.getResult().getText();
+ commentText.setText(comment!=null?comment:"");
}
commentText.addModifyListener(new ModifyListener() {
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
index e420174f..2620fd11 100644
--- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
+++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java
@@ -16,7 +16,9 @@
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.reviews.core.ReviewConstants;
+import org.eclipse.mylyn.reviews.core.ReviewData;
import org.eclipse.mylyn.reviews.core.ReviewDataManager;
+import org.eclipse.mylyn.reviews.core.ReviewsUtil;
import org.eclipse.mylyn.reviews.core.model.review.Review;
import org.eclipse.mylyn.reviews.ui.Messages;
import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource;
@@ -37,8 +39,7 @@ public class ReviewTaskEditorPartAdvisor implements
ITaskEditorPartDescriptorAdvisor {
public boolean canCustomize(ITask task) {
- boolean isReview = Boolean.parseBoolean(task
- .getAttribute(ReviewConstants.ATTR_REVIEW_FLAG));
+ boolean isReview = ReviewsUtil.isMarkedAsReview(task);
return isReview;
}
@@ -72,32 +73,37 @@ public AbstractTaskEditorPart createPart() {
public void taskMigration(ITask oldTask, ITask newTask) {
ReviewDataManager dataManager = ReviewsUiPlugin.getDataManager();
Review review = dataManager.getReviewData(oldTask).getReview();
- dataManager.storeTask(newTask, review);
+ dataManager.storeOutgoingTask(newTask, review);
+ ReviewsUtil.markAsReview(newTask);
}
public void afterSubmit(ITask task) {
try {
- Review review = ReviewsUiPlugin.getDataManager()
- .getReviewData(task).getReview();
-
- TaskRepository taskRepository = TasksUiPlugin
- .getRepositoryManager().getRepository(
- task.getRepositoryUrl());
- TaskData taskData = TasksUiPlugin.getTaskDataManager().getTaskData(
- task);
- // todo get which attachments have to be submitted
- TaskAttribute attachmentAttribute = taskData.getAttributeMapper()
- .createTaskAttachment(taskData);
- byte[] attachmentBytes = createAttachment(review);
-
- ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
- attachmentBytes);
-
- AbstractRepositoryConnector connector = TasksUi
- .getRepositoryConnector(taskRepository.getConnectorKind());
- connector.getTaskAttachmentHandler().postContent(taskRepository,
- task, attachment, "review result", //$NON-NLS-1$
- attachmentAttribute, new NullProgressMonitor());
+ ReviewData reviewData = ReviewsUiPlugin.getDataManager()
+ .getReviewData(task);
+ Review review = reviewData.getReview();
+
+ if (reviewData.isOutgoing() || reviewData.isDirty()) {
+ TaskRepository taskRepository = TasksUiPlugin
+ .getRepositoryManager().getRepository(
+ task.getRepositoryUrl());
+ TaskData taskData = TasksUiPlugin.getTaskDataManager()
+ .getTaskData(task);
+ // todo get which attachments have to be submitted
+ TaskAttribute attachmentAttribute = taskData
+ .getAttributeMapper().createTaskAttachment(taskData);
+ byte[] attachmentBytes = createAttachment(review);
+
+ ReviewCommentTaskAttachmentSource attachment = new ReviewCommentTaskAttachmentSource(
+ attachmentBytes);
+
+ AbstractRepositoryConnector connector = TasksUi
+ .getRepositoryConnector(taskRepository
+ .getConnectorKind());
+ connector.getTaskAttachmentHandler().postContent(
+ taskRepository, task, attachment, "review result", //$NON-NLS-1$
+ attachmentAttribute, new NullProgressMonitor());
+ }
} catch (CoreException e) {
e.printStackTrace();
}
|
9ac8731539e821afca215b685203ef82115e36f5
|
orientdb
|
Working to fix corrupted data in sockets--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
index ef8646b8b48..8d060267d50 100644
--- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
+++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryAsynch.java
@@ -21,6 +21,7 @@
import java.util.concurrent.locks.ReentrantLock;
import com.orientechnologies.common.concur.OTimeoutException;
+import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
@@ -32,7 +33,7 @@
*
*/
public class OChannelBinaryAsynch extends OChannelBinary {
- private final ReentrantLock lockRead = new ReentrantLock();
+ private final ReentrantLock lockRead = new ReentrantLock(true);
private final ReentrantLock lockWrite = new ReentrantLock();
private boolean channelRead = false;
private byte currentStatus;
@@ -105,7 +106,8 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS))
maxUnreadResponses);
// CALL THE SUPER-METHOD TO AVOID LOCKING AGAIN
- super.clearInput();
+ //super.clearInput();
+ throw new OIOException("Timeout on reading response");
}
lockRead.unlock();
@@ -116,14 +118,14 @@ else if (!lockRead.tryLock(iTimeout, TimeUnit.MILLISECONDS))
synchronized (this) {
try {
if (debug)
- OLogManager.instance().debug(this, "Session %d is going to sleep...", currentSessionId);
+ OLogManager.instance().debug(this, "Session %d is going to sleep...", iRequesterId);
wait(1000);
final long now = System.currentTimeMillis();
if (debug)
OLogManager.instance().debug(this, "Waked up: slept %dms, checking again from %s for session %d", (now - start),
- socket.getLocalAddress(), currentSessionId);
+ socket.getLocalAddress(), iRequesterId);
if (now - start >= 1000)
unreadResponse++;
|
2299b927c8dbfaad4761ed07c3c709e8e5d1c3b8
|
orientdb
|
fixed bug on shutdown--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java b/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
index b36472b5846..f55130922a8 100644
--- a/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
+++ b/src/main/java/com/orientechnologies/lucene/manager/OLuceneIndexManagerAbstract.java
@@ -121,8 +121,8 @@ protected void initIndex(String indexName, OIndexDefinition indexDefinition, Str
private void reOpen(ODocument metadata) throws IOException {
ODatabaseRecord database = getDatabase();
final OStorageLocalAbstract storageLocalAbstract = (OStorageLocalAbstract) database.getStorage().getUnderlying();
- Directory dir = NIOFSDirectory.open(new File(storageLocalAbstract.getStoragePath() + File.separator + OLUCENE_BASE_DIR
- + File.separator + indexName));
+ String pathname = getIndexPath(storageLocalAbstract);
+ Directory dir = NIOFSDirectory.open(new File(pathname));
indexWriter = createIndexWriter(dir, metadata);
mgrWriter = new TrackingIndexWriter(indexWriter);
manager = new SearcherManager(indexWriter, true, null);
@@ -133,6 +133,10 @@ private void reOpen(ODocument metadata) throws IOException {
nrt.start();
}
+ private String getIndexPath(OStorageLocalAbstract storageLocalAbstract) {
+ return storageLocalAbstract.getStoragePath() + File.separator + OLUCENE_BASE_DIR + File.separator + indexName;
+ }
+
protected IndexSearcher getSearcher() throws IOException {
try {
nrt.waitForGeneration(reopenToken);
@@ -184,12 +188,15 @@ public void delete() {
try {
if (indexWriter != null) {
indexWriter.deleteAll();
+
+ nrt.interrupt();
+ nrt.close();
+
indexWriter.close();
- indexWriter.getDirectory().close();
}
ODatabaseRecord database = getDatabase();
final OStorageLocalAbstract storageLocalAbstract = (OStorageLocalAbstract) database.getStorage().getUnderlying();
- File f = new File(storageLocalAbstract.getStoragePath() + File.separator + indexName);
+ File f = new File(getIndexPath(storageLocalAbstract));
OLuceneIndexUtils.deleteFolder(f);
@@ -259,7 +266,9 @@ public void flush() {
@Override
public void close() {
try {
+ nrt.interrupt();
nrt.close();
+ indexWriter.commit();
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
@@ -329,7 +338,15 @@ public Analyzer getAnalyzer(ODocument metadata) {
} catch (ClassNotFoundException e) {
throw new OIndexException("Analyzer: " + analyzerString + " not found", e);
} catch (NoSuchMethodException e) {
- e.printStackTrace();
+ Class classAnalyzer = null;
+ try {
+ classAnalyzer = Class.forName(analyzerString);
+ analyzer = (Analyzer) classAnalyzer.newInstance();
+
+ } catch (Throwable e1) {
+ throw new OIndexException("Couldn't instantiate analyzer: public constructor not found", e1);
+ }
+
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
diff --git a/src/test/java/com/orientechnologies/test/lucene-local-test.xml b/src/test/java/com/orientechnologies/test/lucene-local-test.xml
new file mode 100755
index 00000000000..4a451ed031a
--- /dev/null
+++ b/src/test/java/com/orientechnologies/test/lucene-local-test.xml
@@ -0,0 +1,194 @@
+<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd">
+<suite name="Local Test Suite" verbose="2" parallel="false">
+
+ <parameter name="path" value="@PATH@"/>
+ <parameter name="url" value="@URL@"/>
+ <parameter name="testPath" value="@TESTPATH@"/>
+
+ <test name="Setup">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.base.DeleteDirectory"/>
+ </classes>
+ </test>
+
+ <test name="DbCreation">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbListenerTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCreationTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.StorageTest"/>
+ </classes>
+ </test>
+ <test name="Schema">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SchemaTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.AbstractClassTest"/>
+ </classes>
+ </test>
+ <test name="Security">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SecurityTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.RestrictedTest"/>
+ </classes>
+ </test>
+ <test name="Hook">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.HookTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.HookTxTest"/>
+ </classes>
+ </test>
+ <test name="Population">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.ComplexTypesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectInheritanceTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDDocumentPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDFlatPhysicalTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDDocumentValidationTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.RecordMetadataTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectTreeTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectDetachingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectEnhancingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DocumentTrackingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.EmbeddedObjectSerializationTest"/>
+ </classes>
+ </test>
+ <test name="PopulationObjectSchemaFull">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectInheritanceTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CRUDObjectPhysicalTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectTreeTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectDetachingTestSchemaFull"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ObjectEnhancingTestSchemaFull"/>
+ </classes>
+ </test>
+ <test name="Tx">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionAtomicTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionOptimisticTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.TransactionConsistencyTest"/>
+ </classes>
+ </test>
+ <test name="Index">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DateIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLEscapingTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectHashIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexCustomKeyTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexClusterTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ByteArrayKeyTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.FullTextIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ClassIndexManagerTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCreateIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropClassIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDropPropertyIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SchemaIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ClassIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.PropertyIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CollectionIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectCompositeIndexDirectSearchTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetValuesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetValuesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareMultiValueGetEntriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxAwareOneValueGetEntriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.MapIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectByLinkedPropertyIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkListIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkMapIndexTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLIndexWithoutSchemaTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexTxTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.OrderByIndexReuseTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.LinkSetIndexTest"/>
+ </classes>
+ </test>
+ <test name="Dictionary">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DictionaryTest"/>
+ </classes>
+ </test>
+ <test name="Query">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.WrongQueryTest"/>
+ </classes>
+ </test>
+ <test name="Parsing">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.JSONTest"/>
+ </classes>
+ </test>
+ <test name="Graph">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.GraphDatabaseTest"/>
+ <!-- <class name="com.orientechnologies.orient.test.database.auto.SQLCreateVertexAndEdgeTest"/> -->
+ </classes>
+ </test>
+ <test name="GEO">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.GEOTest"/>
+ </classes>
+ </test>
+ <test name="Index Manager">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.IndexManagerTest"/>
+ </classes>
+ </test>
+ <test name="Binary">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.BinaryTest"/>
+ </classes>
+ </test>
+ <test name="sql-commands">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCommandsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLInsertTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLMetadataTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectProjectionsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLSelectGroupByTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLFunctionsTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLUpdateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLDeleteTest"/>
+ </classes>
+ </test>
+ <test name="other-commands">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TraverseTest"/>
+ </classes>
+ </test>
+ <test name="misc">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.TruncateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLFindReferencesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.SQLCreateLinkTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.MultipleDBTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ConcurrentUpdatesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.ConcurrentQueriesTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DatabaseThreadFactoryTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.CollateTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.PoolTest"/>
+ </classes>
+ </test>
+ <test name="DbTools">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCheckTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbImportExportTest"/>
+ <class name="com.orientechnologies.orient.test.database.auto.DbCompareTest"/>
+ </classes>
+ </test>
+ <test name="DbToolsDelete">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbDeleteTest"/>
+ </classes>
+ </test>
+ <test name="End">
+ <classes>
+ <class name="com.orientechnologies.orient.test.database.auto.DbClosedTest"/>
+ </classes>
+ </test>
+</suite>
\ No newline at end of file
|
e6897e844505bfdfff46cfc91d9e122002f3e6a5
|
orientdb
|
first implementation of binary record serializer- debug info.
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java
new file mode 100644
index 00000000000..a90e217af70
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java
@@ -0,0 +1,13 @@
+package com.orientechnologies.orient.core.serialization.serializer.record.binary;
+
+import java.util.ArrayList;
+
+public class ORecordSerializationDebug {
+
+ public String className;
+ public ArrayList<ORecordSerializationDebugProperty> properties;
+ public boolean readingFailure;
+ public RuntimeException readingException;
+ public int failPosition;
+
+}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java
new file mode 100644
index 00000000000..1e1f671fa95
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java
@@ -0,0 +1,15 @@
+package com.orientechnologies.orient.core.serialization.serializer.record.binary;
+
+import com.orientechnologies.orient.core.metadata.schema.OType;
+
+public class ORecordSerializationDebugProperty {
+
+ public String name;
+ public int globalId;
+ public OType type;
+ public RuntimeException readingException;
+ public boolean faildToRead;
+ public int failPosition;
+ public Object value;
+
+}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java
new file mode 100644
index 00000000000..d2b294a2419
--- /dev/null
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java
@@ -0,0 +1,93 @@
+package com.orientechnologies.orient.core.serialization.serializer.record.binary;
+
+import java.util.ArrayList;
+
+import com.orientechnologies.common.exception.OException;
+import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
+import com.orientechnologies.orient.core.metadata.OMetadataInternal;
+import com.orientechnologies.orient.core.metadata.schema.OGlobalProperty;
+import com.orientechnologies.orient.core.metadata.schema.OImmutableSchema;
+import com.orientechnologies.orient.core.metadata.schema.OType;
+import com.orientechnologies.orient.core.record.impl.ODocument;
+
+public class ORecordSerializerBinaryDebug extends ORecordSerializerBinaryV0 {
+
+ public ORecordSerializationDebug deserializeDebug(final byte[] iSource, ODatabaseDocumentTx db) {
+ ORecordSerializationDebug debugInfo = new ORecordSerializationDebug();
+ OImmutableSchema schema = ((OMetadataInternal) db.getMetadata()).getImmutableSchemaSnapshot();
+ BytesContainer bytes = new BytesContainer(iSource);
+ if (bytes.bytes[0] != 0)
+ throw new OException("Unsupported binary serialization version");
+ bytes.skip(1);
+ try {
+ final String className = readString(bytes);
+ debugInfo.className = className;
+ } catch (RuntimeException ex) {
+ debugInfo.readingFailure = true;
+ debugInfo.readingException = ex;
+ debugInfo.failPosition = bytes.offset;
+ return debugInfo;
+ }
+
+ debugInfo.properties = new ArrayList<ORecordSerializationDebugProperty>();
+ int last = 0;
+ String fieldName;
+ int valuePos;
+ OType type;
+ while (true) {
+ ORecordSerializationDebugProperty debugProperty = new ORecordSerializationDebugProperty();
+ OGlobalProperty prop = null;
+ try {
+ final int len = OVarIntSerializer.readAsInteger(bytes);
+ if (len != 0)
+ debugInfo.properties.add(debugProperty);
+ if (len == 0) {
+ // SCAN COMPLETED
+ break;
+ } else if (len > 0) {
+ // PARSE FIELD NAME
+ fieldName = stringFromBytes(bytes.bytes, bytes.offset, len).intern();
+ bytes.skip(len);
+ valuePos = readInteger(bytes);
+ type = readOType(bytes);
+ } else {
+ // LOAD GLOBAL PROPERTY BY ID
+ final int id = (len * -1) - 1;
+ debugProperty.globalId = id;
+ prop = schema.getGlobalPropertyById(id);
+ fieldName = prop.getName();
+ valuePos = readInteger(bytes);
+ if (prop.getType() != OType.ANY)
+ type = prop.getType();
+ else
+ type = readOType(bytes);
+ }
+ debugProperty.name = fieldName;
+ debugProperty.type = type;
+
+ if (valuePos != 0) {
+ int headerCursor = bytes.offset;
+ bytes.offset = valuePos;
+ try {
+ debugProperty.value = readSingleValue(bytes, type, new ODocument());
+ } catch (RuntimeException ex) {
+ debugProperty.faildToRead = true;
+ debugProperty.readingException = ex;
+ debugProperty.failPosition = bytes.offset;
+ }
+ if (bytes.offset > last)
+ last = bytes.offset;
+ bytes.offset = headerCursor;
+ } else
+ debugProperty.value = null;
+ } catch (RuntimeException ex) {
+ debugInfo.readingFailure = true;
+ debugInfo.readingException = ex;
+ debugInfo.failPosition = bytes.offset;
+ return debugInfo;
+ }
+ }
+
+ return debugInfo;
+ }
+}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
index 1b8f179c7fb..817eb75926b 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java
@@ -273,12 +273,12 @@ protected OClass serializeClass(final ODocument document, final BytesContainer b
return clazz;
}
- private OGlobalProperty getGlobalProperty(final ODocument document, final int len) {
+ protected OGlobalProperty getGlobalProperty(final ODocument document, final int len) {
final int id = (len * -1) - 1;
return ODocumentInternal.getGlobalPropertyById(document, id);
}
- private OType readOType(final BytesContainer bytes) {
+ protected OType readOType(final BytesContainer bytes) {
return OType.getById(readByte(bytes));
}
@@ -286,7 +286,7 @@ private void writeOType(BytesContainer bytes, int pos, OType type) {
bytes.bytes[pos] = (byte) type.getId();
}
- private Object readSingleValue(BytesContainer bytes, OType type, ODocument document) {
+ protected Object readSingleValue(BytesContainer bytes, OType type, ODocument document) {
Object value = null;
switch (type) {
case INTEGER:
@@ -748,14 +748,14 @@ private OType getTypeFromValueEmbedded(final Object fieldValue) {
return type;
}
- private String readString(final BytesContainer bytes) {
+ protected String readString(final BytesContainer bytes) {
final int len = OVarIntSerializer.readAsInteger(bytes);
final String res = stringFromBytes(bytes.bytes, bytes.offset, len);
bytes.skip(len);
return res;
}
- private int readInteger(final BytesContainer container) {
+ protected int readInteger(final BytesContainer container) {
final int value = OIntegerSerializer.INSTANCE.deserializeLiteral(container.bytes, container.offset);
container.offset += OIntegerSerializer.INT_SIZE;
return value;
@@ -791,7 +791,7 @@ private byte[] bytesFromString(final String toWrite) {
}
}
- private String stringFromBytes(final byte[] bytes, final int offset, final int len) {
+ protected String stringFromBytes(final byte[] bytes, final int offset, final int len) {
try {
return new String(bytes, offset, len, CHARSET_UTF_8);
} catch (UnsupportedEncodingException e) {
diff --git a/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java b/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java
new file mode 100644
index 00000000000..dba8275f0a2
--- /dev/null
+++ b/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java
@@ -0,0 +1,163 @@
+package com.orientechnologies.orient.core.serialization.serializer.binary.impl;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import org.testng.annotations.Test;
+
+import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
+import com.orientechnologies.orient.core.metadata.schema.OClass;
+import com.orientechnologies.orient.core.metadata.schema.OType;
+import com.orientechnologies.orient.core.record.impl.ODocument;
+import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializationDebug;
+import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryDebug;
+
+public class ORecordSerializerBinaryDebugTest {
+
+ @Test
+ public void testSimpleDocumentDebug() {
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName());
+ db.create();
+ try {
+ ODocument doc = new ODocument();
+ doc.field("test", "test");
+ doc.field("anInt", 2);
+ doc.field("anDouble", 2D);
+
+ byte[] bytes = doc.toStream();
+
+ ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug();
+ ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db);
+
+ assertEquals(debug.properties.size(), 3);
+ assertEquals(debug.properties.get(0).name, "test");
+ assertEquals(debug.properties.get(0).type, OType.STRING);
+ assertEquals(debug.properties.get(0).value, "test");
+
+ assertEquals(debug.properties.get(1).name, "anInt");
+ assertEquals(debug.properties.get(1).type, OType.INTEGER);
+ assertEquals(debug.properties.get(1).value, 2);
+
+ assertEquals(debug.properties.get(2).name, "anDouble");
+ assertEquals(debug.properties.get(2).type, OType.DOUBLE);
+ assertEquals(debug.properties.get(2).value, 2D);
+ } finally {
+ db.drop();
+ }
+ }
+
+ @Test
+ public void testSchemaFullDocumentDebug() {
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName());
+ db.create();
+ try {
+ OClass clazz = db.getMetadata().getSchema().createClass("some");
+ clazz.createProperty("testP", OType.STRING);
+ clazz.createProperty("theInt", OType.INTEGER);
+ ODocument doc = new ODocument("some");
+ doc.field("testP", "test");
+ doc.field("theInt", 2);
+ doc.field("anDouble", 2D);
+
+ byte[] bytes = doc.toStream();
+
+ ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug();
+ ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db);
+
+ assertEquals(debug.properties.size(), 3);
+ assertEquals(debug.properties.get(0).name, "testP");
+ assertEquals(debug.properties.get(0).type, OType.STRING);
+ assertEquals(debug.properties.get(0).value, "test");
+
+ assertEquals(debug.properties.get(1).name, "theInt");
+ assertEquals(debug.properties.get(1).type, OType.INTEGER);
+ assertEquals(debug.properties.get(1).value, 2);
+
+ assertEquals(debug.properties.get(2).name, "anDouble");
+ assertEquals(debug.properties.get(2).type, OType.DOUBLE);
+ assertEquals(debug.properties.get(2).value, 2D);
+ } finally {
+ db.drop();
+ }
+
+ }
+
+ @Test
+ public void testSimpleBrokenDocumentDebug() {
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName());
+ db.create();
+ try {
+ ODocument doc = new ODocument();
+ doc.field("test", "test");
+ doc.field("anInt", 2);
+ doc.field("anDouble", 2D);
+
+ byte[] bytes = doc.toStream();
+ byte[] brokenBytes = new byte[bytes.length - 10];
+ System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10);
+
+ ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug();
+ ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db);
+
+ assertEquals(debug.properties.size(), 3);
+ assertEquals(debug.properties.get(0).name, "test");
+ assertEquals(debug.properties.get(0).type, OType.STRING);
+ assertEquals(debug.properties.get(0).faildToRead, true);
+ assertNotNull(debug.properties.get(0).readingException);
+
+ assertEquals(debug.properties.get(1).name, "anInt");
+ assertEquals(debug.properties.get(1).type, OType.INTEGER);
+ assertEquals(debug.properties.get(1).faildToRead, true);
+ assertNotNull(debug.properties.get(1).readingException);
+
+ assertEquals(debug.properties.get(2).name, "anDouble");
+ assertEquals(debug.properties.get(2).type, OType.DOUBLE);
+ assertEquals(debug.properties.get(2).faildToRead, true);
+ assertNotNull(debug.properties.get(2).readingException);
+ } finally {
+ db.drop();
+ }
+ }
+
+ @Test
+ public void testBrokenSchemaFullDocumentDebug() {
+ ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName());
+ db.create();
+ try {
+ OClass clazz = db.getMetadata().getSchema().createClass("some");
+ clazz.createProperty("testP", OType.STRING);
+ clazz.createProperty("theInt", OType.INTEGER);
+ ODocument doc = new ODocument("some");
+ doc.field("testP", "test");
+ doc.field("theInt", 2);
+ doc.field("anDouble", 2D);
+
+ byte[] bytes = doc.toStream();
+ byte[] brokenBytes = new byte[bytes.length - 10];
+ System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10);
+
+ ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug();
+ ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db);
+
+ assertEquals(debug.properties.size(), 3);
+ assertEquals(debug.properties.get(0).name, "testP");
+ assertEquals(debug.properties.get(0).type, OType.STRING);
+ assertEquals(debug.properties.get(0).faildToRead, true);
+ assertNotNull(debug.properties.get(0).readingException);
+
+ assertEquals(debug.properties.get(1).name, "theInt");
+ assertEquals(debug.properties.get(1).type, OType.INTEGER);
+ assertEquals(debug.properties.get(1).faildToRead, true);
+ assertNotNull(debug.properties.get(1).readingException);
+
+ assertEquals(debug.properties.get(2).name, "anDouble");
+ assertEquals(debug.properties.get(2).type, OType.DOUBLE);
+ assertEquals(debug.properties.get(2).faildToRead, true);
+ assertNotNull(debug.properties.get(2).readingException);
+ } finally {
+ db.drop();
+ }
+
+ }
+
+}
|
b6096079c17488b1232f7db942c529c7eb5f9843
|
ReactiveX-RxJava
|
Unlock in finally block--
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java b/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java
index fdd6e844ad..14c9612e07 100644
--- a/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java
+++ b/rxjava-core/src/main/java/rx/observers/SerializedObserverViaStateMachine.java
@@ -63,25 +63,24 @@ public void onNext(T t) {
} while (!state.compareAndSet(current, newState));
if (newState.shouldProcess()) {
- if (newState == State.PROCESS_SELF) {
- s.onNext(t);
-
- // finish processing to let this thread move on
- do {
- current = state.get();
- newState = current.finishProcessing(1);
- } while (!state.compareAndSet(current, newState));
- } else {
- // drain queue
- Object[] items = newState.queue;
- for (int i = 0; i < items.length; i++) {
- s.onNext((T) items[i]);
+ int numItemsProcessed = 0;
+ try {
+ if (newState == State.PROCESS_SELF) {
+ s.onNext(t);
+ numItemsProcessed++;
+ } else {
+ // drain queue
+ Object[] items = newState.queue;
+ for (int i = 0; i < items.length; i++) {
+ s.onNext((T) items[i]);
+ numItemsProcessed++;
+ }
}
-
+ } finally {
// finish processing to let this thread move on
do {
current = state.get();
- newState = current.finishProcessing(items.length);
+ newState = current.finishProcessing(numItemsProcessed);
} while (!state.compareAndSet(current, newState));
}
}
|
615adaba0cdfa8685039f4eb0765df053deead9c
|
restlet-framework-java
|
Fixed range issue -607.--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java
index 2e97420ce8..b34582859c 100644
--- a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java
@@ -266,6 +266,15 @@ public void testGet() throws Exception {
assertEquals(2, response.getEntity().getRange().getIndex());
assertEquals(8, response.getEntity().getRange().getSize());
+ request.setRanges(Arrays.asList(new Range(2, 1000)));
+ response = client.handle(request);
+ assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus());
+ assertEquals("34567890", response.getEntity().getText());
+ assertEquals(10, response.getEntity().getSize());
+ assertEquals(8, response.getEntity().getAvailableSize());
+ assertEquals(2, response.getEntity().getRange().getIndex());
+ assertEquals(8, response.getEntity().getRange().getSize());
+
client.stop();
}
diff --git a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java
index eea7b61abb..ecbef8ecd0 100644
--- a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java
+++ b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java
@@ -106,6 +106,12 @@ protected void afterHandle(Request request, Response response) {
.info("The range of the response entity is not equal to the requested one.");
}
+ if (response.getEntity().hasKnownSize()
+ && requestedRange.getSize() > response
+ .getEntity().getAvailableSize()) {
+ requestedRange.setSize(Range.SIZE_MAX);
+ }
+
response.setEntity(new RangeRepresentation(
response.getEntity(), requestedRange));
response.setStatus(Status.SUCCESS_PARTIAL_CONTENT);
|
1b7ce0a4407a5cbb1ae7cc0f3e1fc3a741cf9b86
|
arrayexpress$annotare2
|
Another round of refactoring of sign-up/sign-in functionality
|
p
|
https://github.com/arrayexpress/annotare2
|
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java
index 82b954fd6..a56cf9e82 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java
@@ -28,12 +28,14 @@
*/
public interface AccountService {
- ValidationErrors signUp(HttpServletRequest request) throws AccountServiceException;
-
boolean isLoggedIn(HttpServletRequest request);
ValidationErrors login(HttpServletRequest request) throws AccountServiceException;
+ ValidationErrors signUp(HttpServletRequest request) throws AccountServiceException;
+
+ ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException;
+
void logout(HttpSession session);
User getCurrentUser(HttpSession session);
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
index 1faf49318..4dc9cae16 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java
@@ -22,6 +22,7 @@
import org.slf4j.LoggerFactory;
import uk.ac.ebi.fg.annotare2.db.om.User;
import uk.ac.ebi.fg.annotare2.web.server.UnauthorizedAccessException;
+import uk.ac.ebi.fg.annotare2.web.server.login.utils.FormParams;
import uk.ac.ebi.fg.annotare2.web.server.services.AccountManager;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.RequestParam;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.SessionAttribute;
@@ -33,8 +34,6 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
-import static java.util.Arrays.asList;
-
/**
* @author Olga Melnichuk
*/
@@ -83,6 +82,31 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
return errors;
}
+ @Transactional
+ public ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException {
+ SignUpParams params = new SignUpParams(request);
+ ValidationErrors errors = params.validate();
+ if (errors.isEmpty()) {
+ if (null != accountManager.getByEmail(params.getEmail())) {
+ errors.append("email", "User with this email already exists");
+ } else {
+ User u = accountManager.createUser(params.getName(), params.getEmail(), params.getPassword());
+ try {
+ emailer.sendFromTemplate(
+ EmailSender.NEW_USER_TEMPLATE,
+ ImmutableMap.of(
+ "to.name", u.getName(),
+ "to.email", u.getEmail(),
+ "verification.token", u.getVerificationToken()
+ )
+ );
+ } catch (MessagingException x) {
+ //
+ }
+ }
+ }
+ return errors;
+ }
@Transactional
public ValidationErrors login(HttpServletRequest request) throws AccountServiceException {
@@ -112,78 +136,63 @@ public User getCurrentUser(HttpSession session) {
return user;
}
- static class LoginParams {
- public static final String EMAIL_PARAM = "email";
- public static final String PASSWORD_PARAM = "password";
-
- private final RequestParam email;
- private final RequestParam password;
+ static class LoginParams extends FormParams {
private LoginParams(HttpServletRequest request) {
- email = RequestParam.from(request, EMAIL_PARAM);
- password = RequestParam.from(request, PASSWORD_PARAM);
+ addParam(RequestParam.from(request, EMAIL_PARAM), true);
+ addParam(RequestParam.from(request, PASSWORD_PARAM), true);
}
public ValidationErrors validate() {
- ValidationErrors errors = new ValidationErrors();
- for (RequestParam p : asList(email, password)) {
- if (p.isEmpty()) {
- errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required");
- }
- }
- return errors;
+ return validateMandatory();
}
public String getEmail() {
- return email.getValue();
+ return getParamValue(EMAIL_PARAM);
}
public String getPassword() {
- return password.getValue();
+ return getParamValue(PASSWORD_PARAM);
}
}
- static class SignUpParams {
- public static final String NAME_PARAM = "name";
- public static final String EMAIL_PARAM = "email";
- public static final String PASSWORD_PARAM = "password";
- public static final String CONFIRM_PASSWORD_PARAM = "confirm-password";
-
- private final RequestParam name;
- private final RequestParam email;
- private final RequestParam password;
- private final RequestParam confirmPassword;
+ static class SignUpParams extends FormParams {
private SignUpParams(HttpServletRequest request) {
- name = RequestParam.from(request, NAME_PARAM);
- email = RequestParam.from(request, EMAIL_PARAM);
- password = RequestParam.from(request, PASSWORD_PARAM);
- confirmPassword = RequestParam.from(request, CONFIRM_PASSWORD_PARAM);
+ addParam(RequestParam.from(request, NAME_PARAM), true);
+ addParam(RequestParam.from(request, EMAIL_PARAM), true);
+ addParam(RequestParam.from(request, PASSWORD_PARAM), true);
+ addParam(RequestParam.from(request, CONFIRM_PASSWORD_PARAM), false);
}
public ValidationErrors validate() {
- ValidationErrors errors = new ValidationErrors();
- for (RequestParam p : asList(name, email, password)) {
- if (p.isEmpty()) {
- errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required");
- }
+ ValidationErrors errors = validateMandatory();
+
+ if (!isEmailGoodEnough()) {
+ errors.append(EMAIL_PARAM, "Email is not valid; should at least contain @ sign");
}
- if (!password.getValue().equals(confirmPassword.getValue())) {
- errors.append(confirmPassword.getName(), "Passwords do not match");
+
+ if (!isPasswordGoodEnough()) {
+ errors.append(PASSWORD_PARAM, "Password is too weak; should be at least 4 characters long containing at least one digit");
+ }
+
+ if (!hasPasswordConfirmed()) {
+ errors.append(CONFIRM_PASSWORD_PARAM, "Passwords do not match");
}
+
return errors;
}
public String getName() {
- return name.getValue();
+ return getParamValue(NAME_PARAM);
}
public String getEmail() {
- return email.getValue();
+ return getParamValue(EMAIL_PARAM);
}
public String getPassword() {
- return password.getValue();
+ return getParamValue(PASSWORD_PARAM);
}
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
index 084ec5aa6..75d3dca75 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java
@@ -28,39 +28,46 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
+import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.CHANGE_PASSWORD;
+
+import static com.google.common.base.Strings.isNullOrEmpty;
import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.LOGIN;
-import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.SIGNUP;
+import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.EMAIL_SESSION_ATTRIBUTE;
+import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.INFO_SESSION_ATTRIBUTE;
public class ChangePasswordServlet extends HttpServlet {
- private static final Logger log = LoggerFactory.getLogger(SignUpServlet.class);
+ private static final Logger log = LoggerFactory.getLogger(ChangePasswordServlet.class);
@Inject
private AccountService accountService;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- log.debug("Sign-up data submitted; checking..");
+ log.debug("Change password request received; processing");
ValidationErrors errors = new ValidationErrors();
+
try {
- errors.append(accountService.signUp(request));
+ errors.append(accountService.changePassword(request));
if (errors.isEmpty()) {
- log.debug("Sign-up successful; redirect to login page");
- LOGIN.redirect(request, response);
- return;
+ if (!isNullOrEmpty(request.getParameter("token"))) {
+ log.debug("Password successfully changed; redirect to login page");
+ INFO_SESSION_ATTRIBUTE.set(request.getSession(), "You have successfully changed password; please sign in now");
+ LOGIN.redirect(request, response);
+ return;
+ }
}
- log.debug("Sign-up form had invalid entries");
- } catch (Exception e) {
- log.debug("Sign-up failed");
+ } catch (AccountServiceException e) {
+ log.debug("Change password request failed", e);
errors.append(e.getMessage());
}
request.setAttribute("errors", errors);
- SIGNUP.forward(getServletConfig().getServletContext(), request, response);
+ CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- SIGNUP.forward(getServletConfig().getServletContext(), request, response);
+ CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java
index 41d35d90e..9d1464445 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java
@@ -38,7 +38,7 @@ enum ServletNavigation {
LOGIN("/login", "/login.jsp"),
SIGNUP("/sign-up", "/sign-up.jsp"),
ACTIVATION("/activate", "/activate.jsp"),
- PASSWORD_CHANGER("/change-password", "change-password.jsp"),
+ CHANGE_PASSWORD("/change-password", "/change-password.jsp"),
HOME("/", "/home.jsp"),
EDITOR("/edit/", "/editor.jsp");
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java
index 5174f0f3e..fd8eeeb5b 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java
@@ -50,10 +50,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
LOGIN.redirect(request, response);
return;
} else {
- log.debug("Sign-up form had invalid entries");
+ log.debug("Sign-up form failed validation");
}
} catch (AccountServiceException e) {
- log.debug("Sign-up failed");
+ log.debug("Sign-up failed", e);
errors.append(e.getMessage());
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java
new file mode 100644
index 000000000..34c5a6263
--- /dev/null
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java
@@ -0,0 +1,76 @@
+package uk.ac.ebi.fg.annotare2.web.server.login.utils;
+
+/*
+ * Copyright 2009-2013 European Molecular Biology Laboratory
+ *
+ * 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.
+ *
+ */
+
+import java.util.*;
+
+import static com.google.common.base.Strings.nullToEmpty;
+
+public abstract class FormParams {
+ protected static final String NAME_PARAM = "name";
+ protected static final String EMAIL_PARAM = "email";
+ protected static final String PASSWORD_PARAM = "password";
+ protected static final String CONFIRM_PASSWORD_PARAM = "confirm-password";
+ protected static final String TOKEN_PARAM = "token";
+
+ private Map<String,RequestParam> paramMap = new HashMap<String, RequestParam>();
+ private Set<RequestParam> mandatoryParamSet = new HashSet<RequestParam>();
+
+ public String getParamValue(String paramName) {
+ if (paramMap.containsKey(paramName)) {
+ return paramMap.get(paramName).getValue();
+ }
+ return null;
+ }
+
+ public abstract ValidationErrors validate();
+
+ protected void addParam(RequestParam param, boolean isMandatory)
+ {
+ paramMap.put(param.getName(), param);
+ if (isMandatory) {
+ mandatoryParamSet.add(param);
+ }
+ }
+
+ protected ValidationErrors validateMandatory() {
+ ValidationErrors errors = new ValidationErrors();
+ for (RequestParam p : getMandatoryParams()) {
+ if (p.isEmpty()) {
+ errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required");
+ }
+ }
+ return errors;
+ }
+
+ protected Collection<RequestParam> getMandatoryParams() {
+ return Collections.unmodifiableSet(mandatoryParamSet);
+ }
+
+ protected boolean isEmailGoodEnough() {
+ return nullToEmpty(getParamValue(EMAIL_PARAM)).matches(".+@.+");
+ }
+
+ protected boolean isPasswordGoodEnough() {
+ return nullToEmpty(getParamValue(PASSWORD_PARAM)).matches("^(?=.*\\d).{4,}$");
+ }
+
+ protected boolean hasPasswordConfirmed() {
+ return getParamValue(PASSWORD_PARAM).equals(getParamValue(CONFIRM_PASSWORD_PARAM));
+ }
+}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java
index 76b9d3ae2..d1263c79f 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java
@@ -53,7 +53,7 @@ public String getErrors() {
public String getErrors(String name) {
Collection<String> err = errors.get(name);
- return err == null ? "" : on(", ").join(err);
+ return err == null ? "" : on(". ").join(err);
}
}
diff --git a/app/web/src/main/webapp/change-password.jsp b/app/web/src/main/webapp/change-password.jsp
index 3e9cae6e5..cb01a2882 100644
--- a/app/web/src/main/webapp/change-password.jsp
+++ b/app/web/src/main/webapp/change-password.jsp
@@ -13,29 +13,24 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
--%>
-<%--
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="f" %>
<%@ page isELIgnored="false" %>
-<%@ page import="uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors" %>
<%
- ValidationErrors errors = (ValidationErrors) request.getAttribute("errors");
- if (errors != null) {
- pageContext.setAttribute("dummyErrors", errors.getErrors());
- pageContext.setAttribute("emailErrors", errors.getErrors("email"));
- pageContext.setAttribute("passwordErrors", errors.getErrors("password"));
- }
+ pageContext.setAttribute("errors", request.getAttribute("errors"));
- String[] values = request.getParameterValues("email");
- pageContext.setAttribute("email", values == null ? "" : values[0]);
+ String email = request.getParameter("email");
+ if (null == email) {
+ email = (String)session.getAttribute("email");
+ }
+ pageContext.setAttribute("email", email == null ? "" : email);
%>
---%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <title>Annotare 2.0 - New user registration</title>
+ <title>Annotare 2.0 - Change password request</title>
<link type="text/css" rel="stylesheet" href="general.css">
<link type="text/css" rel="stylesheet" href="login.css">
</head>
@@ -49,38 +44,40 @@
<table class="form">
<tr>
<td></td>
- <td><h1>Annotare 2.0</h1></td>
+ <td><h1>Change password request</h1></td>
</tr>
- <tr class="error">
+ <tr class="info">
<td></td>
- <td>${dummyErrors}</td>
- </tr>
- <tr class="row right">
- <td>Email</td>
- <td><input type="text" name="email" value="${email}" style="width:98%"/></td>
+ <td><c:out value="${sessionScope.info}" /><c:remove var="info" scope="session" /></td>
</tr>
<tr class="error">
<td></td>
- <td>${emailErrors}</td>
+ <td>${errors}</td>
</tr>
<tr class="row right">
- <td>Password</td>
- <td><input type="password" name="password" style="width:98%"/></td>
- </tr>
- <tr class="error">
- <td></td>
- <td>${passwordErrors}</td>
- </tr>
- <tr class="row">
- <td></td>
+ <td>Email</td>
<td>
- <button name="signIn">Sign In</button> <a href="#" onclick="return false;">Forgot your password?</a>
+ <c:choose>
+ <c:when test="${email != ''}">
+ <input type="text" name="email" value="${email}" style="width:98%"/>
+ </c:when>
+ <c:otherwise>
+ <input type="text" name="email" style="width:98%" autofocus="autofocus"/>
+ </c:otherwise>
+ </c:choose>
</td>
</tr>
- <tr>
+ <tr class="row">
<td></td>
<td>
- <div style="margin-top:10px;">Don't have an account? <a href="#" onclick="return false;">Sign Up</a></div>
+ <c:choose>
+ <c:when test="${email != ''}">
+ <button name="changePassword" autofocus="autofocus">Send</button>
+ </c:when>
+ <c:otherwise>
+ <button name="changePassword">Send</button>
+ </c:otherwise>
+ </c:choose>
</td>
</tr>
</table>
diff --git a/app/web/src/main/webapp/login.css b/app/web/src/main/webapp/login.css
index 386e086ac..4fcb40929 100644
--- a/app/web/src/main/webapp/login.css
+++ b/app/web/src/main/webapp/login.css
@@ -44,7 +44,7 @@
text-align: left;
}
-.form {
+table {
border-collapse: collapse;
color: #000;
width: 100%;
@@ -56,6 +56,10 @@
padding: 0 3px;
}
+.form tr td:first-child {
+ white-space: nowrap;
+}
+
.form tr.row td {
padding-top: 5px;
padding-bottom: 5px;
diff --git a/app/web/src/main/webapp/login.jsp b/app/web/src/main/webapp/login.jsp
index c1e1537ac..be7d4396e 100644
--- a/app/web/src/main/webapp/login.jsp
+++ b/app/web/src/main/webapp/login.jsp
@@ -54,7 +54,6 @@
<tr class="info">
<td></td>
<td><c:out value="${sessionScope.info}" /><c:remove var="info" scope="session" /></td>
-
</tr>
<tr class="error">
<td></td>
|
1dc33f9f6d29c6b33de2023d4f2158e70a1c89aa
|
orientdb
|
UPDATE ADD now possible with subdocuments fields--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
index df9e1a06034..94deb108910 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java
@@ -275,7 +275,13 @@ else if (returning.equalsIgnoreCase("AFTER"))
// IN ALL OTHER CASES USE A LIST
coll = new ArrayList<Object>();
- record.field(entry.getKey(), coll);
+ // containField's condition above does NOT check subdocument's fields so
+ Collection<Object> currColl = record.field(entry.getKey());
+ if (currColl==null)
+ record.field(entry.getKey(), coll);
+ else
+ coll = currColl;
+
} else {
fieldValue = record.field(entry.getKey());
|
4fa174541fd3402cc067ebab5fb44c9b5ce2587e
|
camel
|
CAMEL-3203: Fixed adding routes with quartz- endpoints to already started camel should add jobs to scheduler.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1005489 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-quartz/src/main/java/org/apache/camel/component/quartz/QuartzComponent.java b/components/camel-quartz/src/main/java/org/apache/camel/component/quartz/QuartzComponent.java
index 9ff9bf8cb7515..1ef0cdf81b779 100644
--- a/components/camel-quartz/src/main/java/org/apache/camel/component/quartz/QuartzComponent.java
+++ b/components/camel-quartz/src/main/java/org/apache/camel/component/quartz/QuartzComponent.java
@@ -186,9 +186,14 @@ protected void doStop() throws Exception {
}
}
- public void addJob(JobDetail job, Trigger trigger) {
- // add job to internal list because we will defer adding to the scheduler when camel context has been fully started
- jobsToAdd.add(new JobToAdd(job, trigger));
+ public void addJob(JobDetail job, Trigger trigger) throws SchedulerException {
+ if (scheduler == null) {
+ // add job to internal list because we will defer adding to the scheduler when camel context has been fully started
+ jobsToAdd.add(new JobToAdd(job, trigger));
+ } else {
+ // add job directly to scheduler
+ doAddJob(job, trigger);
+ }
}
private void doAddJob(JobDetail job, Trigger trigger) throws SchedulerException {
diff --git a/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzAddRoutesAfterCamelContextStartedTest.java b/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzAddRoutesAfterCamelContextStartedTest.java
new file mode 100644
index 0000000000000..52503df24ec5a
--- /dev/null
+++ b/components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzAddRoutesAfterCamelContextStartedTest.java
@@ -0,0 +1,49 @@
+/**
+ * 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.component.quartz;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.junit.Test;
+
+/**
+ * @version $Revision$
+ */
+public class QuartzAddRoutesAfterCamelContextStartedTest extends CamelTestSupport {
+
+ @Test
+ public void testAddRoutes() throws Exception {
+ // camel context should already be started
+ assertTrue(context.getStatus().isStarted());
+
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedMessageCount(2);
+
+ // add the quartz router after CamelContext has been started
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() throws Exception {
+ from("quartz://myGroup/myTimerName?trigger.repeatInterval=2&trigger.repeatCount=1").to("mock:result");
+ }
+ });
+
+ // it should also work
+ assertMockEndpointsSatisfied();
+ }
+
+}
|
ad2358bba102bd4e9876028cf30341ec48aabe4f
|
ReactiveX-RxJava
|
GroupBy GroupedObservables should not re-subscribe- to parent sequence--https://github.com/Netflix/RxJava/issues/282--Refactored to maintain a single subscription that propagates events to the correct child GroupedObservables.-
|
c
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java b/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
index 1c2e6e969c..edd4ef7ae4 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationGroupBy.java
@@ -17,12 +17,15 @@
import static org.junit.Assert.*;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
+import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
@@ -30,6 +33,8 @@
import rx.Observer;
import rx.Subscription;
import rx.observables.GroupedObservable;
+import rx.subscriptions.Subscriptions;
+import rx.util.functions.Action1;
import rx.util.functions.Func1;
import rx.util.functions.Functions;
@@ -55,7 +60,9 @@ public static <K, T> Func1<Observer<GroupedObservable<K, T>>, Subscription> grou
}
private static class GroupBy<K, V> implements Func1<Observer<GroupedObservable<K, V>>, Subscription> {
+
private final Observable<KeyValue<K, V>> source;
+ private final ConcurrentHashMap<K, GroupedSubject<K, V>> groupedObservables = new ConcurrentHashMap<K, GroupedSubject<K, V>>();
private GroupBy(Observable<KeyValue<K, V>> source) {
this.source = source;
@@ -63,61 +70,127 @@ private GroupBy(Observable<KeyValue<K, V>> source) {
@Override
public Subscription call(final Observer<GroupedObservable<K, V>> observer) {
- return source.subscribe(new GroupByObserver(observer));
+ return source.subscribe(new Observer<KeyValue<K, V>>() {
+
+ @Override
+ public void onCompleted() {
+ // we need to propagate to all children I imagine ... we can't just leave all of those Observable/Observers hanging
+ for (GroupedSubject<K, V> o : groupedObservables.values()) {
+ o.onCompleted();
+ }
+ // now the parent
+ observer.onCompleted();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ // we need to propagate to all children I imagine ... we can't just leave all of those Observable/Observers hanging
+ for (GroupedSubject<K, V> o : groupedObservables.values()) {
+ o.onError(e);
+ }
+ // now the parent
+ observer.onError(e);
+ }
+
+ @Override
+ public void onNext(KeyValue<K, V> value) {
+ GroupedSubject<K, V> gs = groupedObservables.get(value.key);
+ if (gs == null) {
+ /*
+ * Technically the source should be single-threaded so we shouldn't need to do this but I am
+ * programming defensively as most operators are so this can work with a concurrent sequence
+ * if it ends up receiving one.
+ */
+ GroupedSubject<K, V> newGs = GroupedSubject.<K, V> create(value.key);
+ GroupedSubject<K, V> existing = groupedObservables.putIfAbsent(value.key, newGs);
+ if (existing == null) {
+ // we won so use the one we created
+ gs = newGs;
+ // since we won the creation we emit this new GroupedObservable
+ observer.onNext(gs);
+ } else {
+ // another thread beat us so use the existing one
+ gs = existing;
+ }
+ }
+ gs.onNext(value.value);
+ }
+ });
}
+ }
- private class GroupByObserver implements Observer<KeyValue<K, V>> {
- private final Observer<GroupedObservable<K, V>> underlying;
+ private static class GroupedSubject<K, T> extends GroupedObservable<K, T> implements Observer<T> {
- private final ConcurrentHashMap<K, Boolean> keys = new ConcurrentHashMap<K, Boolean>();
+ static <K, T> GroupedSubject<K, T> create(K key) {
+ @SuppressWarnings("unchecked")
+ final AtomicReference<Observer<T>> subscribedObserver = new AtomicReference<Observer<T>>(EMPTY_OBSERVER);
- private GroupByObserver(Observer<GroupedObservable<K, V>> underlying) {
- this.underlying = underlying;
- }
+ return new GroupedSubject<K, T>(key, new Func1<Observer<T>, Subscription>() {
- @Override
- public void onCompleted() {
- underlying.onCompleted();
- }
+ @Override
+ public Subscription call(Observer<T> observer) {
+ // register Observer
+ subscribedObserver.set(observer);
- @Override
- public void onError(Exception e) {
- underlying.onError(e);
- }
+ return new Subscription() {
- @Override
- public void onNext(final KeyValue<K, V> args) {
- K key = args.key;
- boolean newGroup = keys.putIfAbsent(key, true) == null;
- if (newGroup) {
- underlying.onNext(buildObservableFor(source, key));
+ @SuppressWarnings("unchecked")
+ @Override
+ public void unsubscribe() {
+ // we remove the Observer so we stop emitting further events (they will be ignored if parent continues to send)
+ subscribedObserver.set(EMPTY_OBSERVER);
+ // I don't believe we need to worry about the parent here as it's a separate sequence that would
+ // be unsubscribed to directly if that needs to happen.
+ }
+ };
}
- }
+ }, subscribedObserver);
}
- }
- private static <K, R> GroupedObservable<K, R> buildObservableFor(Observable<KeyValue<K, R>> source, final K key) {
- final Observable<R> observable = source.filter(new Func1<KeyValue<K, R>, Boolean>() {
- @Override
- public Boolean call(KeyValue<K, R> pair) {
- return key.equals(pair.key);
- }
- }).map(new Func1<KeyValue<K, R>, R>() {
- @Override
- public R call(KeyValue<K, R> pair) {
- return pair.value;
- }
- });
- return new GroupedObservable<K, R>(key, new Func1<Observer<R>, Subscription>() {
+ private final AtomicReference<Observer<T>> subscribedObserver;
- @Override
- public Subscription call(Observer<R> observer) {
- return observable.subscribe(observer);
- }
+ public GroupedSubject(K key, Func1<Observer<T>, Subscription> onSubscribe, AtomicReference<Observer<T>> subscribedObserver) {
+ super(key, onSubscribe);
+ this.subscribedObserver = subscribedObserver;
+ }
+
+ @Override
+ public void onCompleted() {
+ subscribedObserver.get().onCompleted();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ subscribedObserver.get().onError(e);
+ }
+
+ @Override
+ public void onNext(T v) {
+ subscribedObserver.get().onNext(v);
+ }
- });
}
+ @SuppressWarnings("rawtypes")
+ private static Observer EMPTY_OBSERVER = new Observer() {
+
+ @Override
+ public void onCompleted() {
+ // do nothing
+ }
+
+ @Override
+ public void onError(Exception e) {
+ // do nothing
+ }
+
+ @Override
+ public void onNext(Object args) {
+ // do nothing
+ }
+
+ };
+
private static class KeyValue<K, V> {
private final K key;
private final V value;
@@ -141,13 +214,12 @@ public void testGroupBy() {
Observable<String> source = Observable.from("one", "two", "three", "four", "five", "six");
Observable<GroupedObservable<Integer, String>> grouped = Observable.create(groupBy(source, length));
- Map<Integer, List<String>> map = toMap(grouped);
+ Map<Integer, Collection<String>> map = toMap(grouped);
assertEquals(3, map.size());
- assertEquals(Arrays.asList("one", "two", "six"), map.get(3));
- assertEquals(Arrays.asList("four", "five"), map.get(4));
- assertEquals(Arrays.asList("three"), map.get(5));
-
+ assertArrayEquals(Arrays.asList("one", "two", "six").toArray(), map.get(3).toArray());
+ assertArrayEquals(Arrays.asList("four", "five").toArray(), map.get(4).toArray());
+ assertArrayEquals(Arrays.asList("three").toArray(), map.get(5).toArray());
}
@Test
@@ -155,31 +227,133 @@ public void testEmpty() {
Observable<String> source = Observable.from();
Observable<GroupedObservable<Integer, String>> grouped = Observable.create(groupBy(source, length));
- Map<Integer, List<String>> map = toMap(grouped);
+ Map<Integer, Collection<String>> map = toMap(grouped);
assertTrue(map.isEmpty());
}
- private static <K, V> Map<K, List<V>> toMap(Observable<GroupedObservable<K, V>> observable) {
- Map<K, List<V>> result = new HashMap<K, List<V>>();
- for (GroupedObservable<K, V> g : observable.toBlockingObservable().toIterable()) {
- K key = g.getKey();
+ private static <K, V> Map<K, Collection<V>> toMap(Observable<GroupedObservable<K, V>> observable) {
- for (V value : g.toBlockingObservable().toIterable()) {
- List<V> values = result.get(key);
- if (values == null) {
- values = new ArrayList<V>();
- result.put(key, values);
- }
+ final ConcurrentHashMap<K, Collection<V>> result = new ConcurrentHashMap<K, Collection<V>>();
- values.add(value);
- }
+ observable.forEach(new Action1<GroupedObservable<K, V>>() {
- }
+ @Override
+ public void call(final GroupedObservable<K, V> o) {
+ result.put(o.getKey(), new ConcurrentLinkedQueue<V>());
+ o.subscribe(new Action1<V>() {
+
+ @Override
+ public void call(V v) {
+ result.get(o.getKey()).add(v);
+ }
+
+ });
+ }
+ });
return result;
}
+ /**
+ * Assert that only a single subscription to a stream occurs and that all events are received.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testGroupedEventStream() throws Exception {
+
+ final AtomicInteger eventCounter = new AtomicInteger();
+ final AtomicInteger subscribeCounter = new AtomicInteger();
+ final AtomicInteger groupCounter = new AtomicInteger();
+ final CountDownLatch latch = new CountDownLatch(1);
+ final int count = 100;
+ final int groupCount = 2;
+
+ Observable<Event> es = Observable.create(new Func1<Observer<Event>, Subscription>() {
+
+ @Override
+ public Subscription call(final Observer<Event> observer) {
+ System.out.println("*** Subscribing to EventStream ***");
+ subscribeCounter.incrementAndGet();
+ new Thread(new Runnable() {
+
+ @Override
+ public void run() {
+ for (int i = 0; i < count; i++) {
+ Event e = new Event();
+ e.source = i % groupCount;
+ e.message = "Event-" + i;
+ observer.onNext(e);
+ }
+ observer.onCompleted();
+ }
+
+ }).start();
+ return Subscriptions.empty();
+ }
+
+ });
+
+ es.groupBy(new Func1<Event, Integer>() {
+
+ @Override
+ public Integer call(Event e) {
+ return e.source;
+ }
+ }).mapMany(new Func1<GroupedObservable<Integer, Event>, Observable<String>>() {
+
+ @Override
+ public Observable<String> call(GroupedObservable<Integer, Event> eventGroupedObservable) {
+ System.out.println("GroupedObservable Key: " + eventGroupedObservable.getKey());
+ groupCounter.incrementAndGet();
+
+ return eventGroupedObservable.map(new Func1<Event, String>() {
+
+ @Override
+ public String call(Event event) {
+ return "Source: " + event.source + " Message: " + event.message;
+ }
+ });
+
+ };
+ }).subscribe(new Observer<String>() {
+
+ @Override
+ public void onCompleted() {
+ latch.countDown();
+ }
+
+ @Override
+ public void onError(Exception e) {
+ e.printStackTrace();
+ latch.countDown();
+ }
+
+ @Override
+ public void onNext(String outputMessage) {
+ System.out.println(outputMessage);
+ eventCounter.incrementAndGet();
+ }
+ });
+
+ latch.await(5000, TimeUnit.MILLISECONDS);
+ assertEquals(1, subscribeCounter.get());
+ assertEquals(groupCount, groupCounter.get());
+ assertEquals(count, eventCounter.get());
+
+ }
+
+ private static class Event {
+ int source;
+ String message;
+
+ @Override
+ public String toString() {
+ return "Event => source: " + source + " message: " + message;
+ }
+ }
+
}
}
|
e86d48730c64d10ba2a838e5663f9ab7a698c9c6
|
hadoop
|
HADOOP-7187. Fix socket leak in GangliaContext. - Contributed by Uma Maheswara Rao G--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1085122 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 3cb5136879088..f33d02a834cbc 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -604,6 +604,9 @@ Release 0.21.1 - Unreleased
HADOOP-7174. Null is displayed in the "fs -copyToLocal" command.
(Uma Maheswara Rao G via szetszwo)
+ HADOOP-7187. Fix socket leak in GangliaContext. (Uma Maheswara Rao G
+ via szetszwo)
+
Release 0.21.0 - 2010-08-13
INCOMPATIBLE CHANGES
diff --git a/src/java/org/apache/hadoop/metrics/ganglia/GangliaContext.java b/src/java/org/apache/hadoop/metrics/ganglia/GangliaContext.java
index 1b22240f879d0..6460120012d41 100644
--- a/src/java/org/apache/hadoop/metrics/ganglia/GangliaContext.java
+++ b/src/java/org/apache/hadoop/metrics/ganglia/GangliaContext.java
@@ -112,6 +112,17 @@ public void init(String contextName, ContextFactory factory) {
}
}
+ /**
+ * method to close the datagram socket
+ */
+ @Override
+ public void close() {
+ super.close();
+ if (datagramSocket != null) {
+ datagramSocket.close();
+ }
+ }
+
@InterfaceAudience.Private
public void emitRecord(String contextName, String recordName,
OutputRecord outRec)
diff --git a/src/test/core/org/apache/hadoop/metrics/ganglia/TestGangliaContext.java b/src/test/core/org/apache/hadoop/metrics/ganglia/TestGangliaContext.java
new file mode 100644
index 0000000000000..deb8231154cd8
--- /dev/null
+++ b/src/test/core/org/apache/hadoop/metrics/ganglia/TestGangliaContext.java
@@ -0,0 +1,42 @@
+/*
+ * TestGangliaContext.java
+ *
+ * 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.metrics.ganglia;
+
+import org.junit.Test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.apache.hadoop.metrics.ContextFactory;
+import org.apache.hadoop.metrics.spi.AbstractMetricsContext;
+
+public class TestGangliaContext {
+
+ @Test
+ public void testCloseShouldCloseTheSocketWhichIsCreatedByInit() throws Exception {
+ AbstractMetricsContext context=new GangliaContext();
+ context.init("gangliaContext", ContextFactory.getFactory());
+ GangliaContext gangliaContext =(GangliaContext) context;
+ assertFalse("Socket already closed",gangliaContext.datagramSocket.isClosed());
+ context.close();
+ assertTrue("Socket not closed",gangliaContext.datagramSocket.isClosed());
+ }
+}
|
5a91d607882e59a6255eff0f144a6efecc749af2
|
spring-framework
|
Allow setting WSDL document as a Resource--Prior to this change
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java b/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java
index 3e8cf74b9024..7f95b3acd651 100644
--- a/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java
+++ b/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,12 +16,14 @@
package org.springframework.remoting.jaxws;
+import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Executor;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.handler.HandlerResolver;
+import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
@@ -53,11 +55,22 @@ public class LocalJaxWsServiceFactory {
/**
* Set the URL of the WSDL document that describes the service.
+ * @see #setWsdlDocumentResource(Resource)
*/
public void setWsdlDocumentUrl(URL wsdlDocumentUrl) {
this.wsdlDocumentUrl = wsdlDocumentUrl;
}
+ /**
+ * Set the WSDL document URL as a {@link Resource}.
+ * @throws IOException
+ * @since 3.2
+ */
+ public void setWsdlDocumentResource(Resource wsdlDocumentResource) throws IOException {
+ Assert.notNull(wsdlDocumentResource, "WSDL Resource must not be null.");
+ this.wsdlDocumentUrl = wsdlDocumentResource.getURL();
+ }
+
/**
* Return the URL of the WSDL document that describes the service.
*/
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 4