commit_id
stringlengths 40
40
| project
stringclasses 90
values | commit_message
stringlengths 5
2.21k
| type
stringclasses 3
values | url
stringclasses 89
values | git_diff
stringlengths 283
4.32M
|
|---|---|---|---|---|---|
e63ed754f1483af587dc3372467d2bc58ee8b785
|
kotlin
|
rename JetTypeMapper constants--
|
p
|
https://github.com/JetBrains/kotlin
|
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ClosureCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ClosureCodegen.java
index d9776cd9eec58..265a64f84ca79 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ClosureCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ClosureCodegen.java
@@ -78,14 +78,14 @@ private static JvmMethodSignature erasedInvokeSignature(FunctionDescriptor fd) {
for (int i = 0; i < paramCount; ++i) {
signatureWriter.writeParameterType(JvmMethodParameterKind.VALUE);
- signatureWriter.writeAsmType(JetTypeMapper.TYPE_OBJECT, true);
+ signatureWriter.writeAsmType(JetTypeMapper.OBJECT_TYPE, true);
signatureWriter.writeParameterTypeEnd();
}
signatureWriter.writeParametersEnd();
signatureWriter.writeReturnType();
- signatureWriter.writeAsmType(JetTypeMapper.TYPE_OBJECT, true);
+ signatureWriter.writeAsmType(JetTypeMapper.OBJECT_TYPE, true);
signatureWriter.writeReturnTypeEnd();
return signatureWriter.makeJvmMethodSignature("invoke");
@@ -242,24 +242,24 @@ private void generateBridge(String className, FunctionDescriptor funDescriptor,
final ReceiverDescriptor receiver = funDescriptor.getReceiverParameter();
int count = 1;
if (receiver.exists()) {
- StackValue.local(count, JetTypeMapper.TYPE_OBJECT).put(JetTypeMapper.TYPE_OBJECT, iv);
- StackValue.onStack(JetTypeMapper.TYPE_OBJECT)
+ StackValue.local(count, JetTypeMapper.OBJECT_TYPE).put(JetTypeMapper.OBJECT_TYPE, iv);
+ StackValue.onStack(JetTypeMapper.OBJECT_TYPE)
.upcast(typeMapper.mapType(receiver.getType(), MapTypeMode.VALUE), iv);
count++;
}
final List<ValueParameterDescriptor> params = funDescriptor.getValueParameters();
for (ValueParameterDescriptor param : params) {
- StackValue.local(count, JetTypeMapper.TYPE_OBJECT).put(JetTypeMapper.TYPE_OBJECT, iv);
- StackValue.onStack(JetTypeMapper.TYPE_OBJECT)
+ StackValue.local(count, JetTypeMapper.OBJECT_TYPE).put(JetTypeMapper.OBJECT_TYPE, iv);
+ StackValue.onStack(JetTypeMapper.OBJECT_TYPE)
.upcast(typeMapper.mapType(param.getType(), MapTypeMode.VALUE), iv);
count++;
}
iv.invokevirtual(className, "invoke", delegate.getDescriptor());
- StackValue.onStack(delegate.getReturnType()).put(JetTypeMapper.TYPE_OBJECT, iv);
+ StackValue.onStack(delegate.getReturnType()).put(JetTypeMapper.OBJECT_TYPE, iv);
- iv.areturn(JetTypeMapper.TYPE_OBJECT);
+ iv.areturn(JetTypeMapper.OBJECT_TYPE);
FunctionCodegen.endVisit(mv, "bridge", fun);
}
@@ -285,7 +285,7 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
int k = 1;
for (int i = 0; i != argTypes.length; ++i) {
- StackValue.local(0, JetTypeMapper.TYPE_OBJECT).put(JetTypeMapper.TYPE_OBJECT, iv);
+ StackValue.local(0, JetTypeMapper.OBJECT_TYPE).put(JetTypeMapper.OBJECT_TYPE, iv);
final Pair<String, Type> nameAndType = args.get(i);
final Type type = nameAndType.second;
StackValue.local(k, type).put(type, iv);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
index 429a24f9e9193..2a582b5827639 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContext.java
@@ -27,7 +27,7 @@
import java.util.HashMap;
import java.util.Map;
-import static org.jetbrains.jet.codegen.JetTypeMapper.TYPE_OBJECT;
+import static org.jetbrains.jet.codegen.JetTypeMapper.OBJECT_TYPE;
/*
* @author max
@@ -169,7 +169,7 @@ public FrameMap prepareFrame(JetTypeMapper mapper) {
FrameMap frameMap = new FrameMap();
if (getContextKind() != OwnerKind.NAMESPACE) {
- frameMap.enterTemp(TYPE_OBJECT); // 0 slot for this
+ frameMap.enterTemp(OBJECT_TYPE); // 0 slot for this
}
CallableDescriptor receiverDescriptor = getReceiverDescriptor();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
index bd39491830226..619b143948437 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/CodegenContexts.java
@@ -86,7 +86,7 @@ public String toString() {
return "ROOT";
}
};
- private static final StackValue local1 = StackValue.local(1, JetTypeMapper.TYPE_OBJECT);
+ private static final StackValue local1 = StackValue.local(1, JetTypeMapper.OBJECT_TYPE);
public abstract static class ReceiverContext extends CodegenContext {
final CallableDescriptor receiverDescriptor;
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java b/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
index f2671c4fed38d..0e0a5cadda2c4 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ConstructorFrameMap.java
@@ -33,10 +33,10 @@ public class ConstructorFrameMap extends FrameMap {
private int myOuterThisIndex = -1;
public ConstructorFrameMap(CallableMethod callableMethod, @Nullable ConstructorDescriptor descriptor, boolean hasThis0) {
- enterTemp(JetTypeMapper.TYPE_OBJECT); // this
+ enterTemp(JetTypeMapper.OBJECT_TYPE); // this
if (descriptor != null) {
if (hasThis0) {
- myOuterThisIndex = enterTemp(JetTypeMapper.TYPE_OBJECT); // outer class instance
+ myOuterThisIndex = enterTemp(JetTypeMapper.OBJECT_TYPE); // outer class instance
}
}
@@ -45,7 +45,7 @@ public ConstructorFrameMap(CallableMethod callableMethod, @Nullable ConstructorD
if (descriptor != null &&
(descriptor.getContainingDeclaration().getKind() == ClassKind.ENUM_CLASS ||
descriptor.getContainingDeclaration().getKind() == ClassKind.ENUM_ENTRY)) {
- enterTemp(JetTypeMapper.TYPE_OBJECT); // name
+ enterTemp(JetTypeMapper.OBJECT_TYPE); // name
enterTemp(Type.INT_TYPE); // ordinal
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
index 225eccadb7de3..0ccbc84a91e72 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/FunctionCodegen.java
@@ -245,8 +245,8 @@ else if (functionDescriptor instanceof SimpleFunctionDescriptor) {
else if (kind instanceof OwnerKind.DelegateKind) {
OwnerKind.DelegateKind dk = (OwnerKind.DelegateKind) kind;
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
- dk.getDelegate().put(JetTypeMapper.TYPE_OBJECT, iv);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
+ dk.getDelegate().put(JetTypeMapper.OBJECT_TYPE, iv);
for (int i = 0; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(i + 1, argType);
@@ -495,7 +495,7 @@ private static void generateDefaultImpl(
FrameMap frameMap = owner.prepareFrame(state.getInjector().getJetTypeMapper());
if (kind instanceof OwnerKind.StaticDelegateKind) {
- frameMap.leaveTemp(JetTypeMapper.TYPE_OBJECT);
+ frameMap.leaveTemp(JetTypeMapper.OBJECT_TYPE);
}
ExpressionCodegen codegen = new ExpressionCodegen(mv, frameMap, jvmSignature.getReturnType(), owner, state);
@@ -645,15 +645,15 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
Type[] argTypes = overridden.getArgumentTypes();
Type[] originalArgTypes = jvmSignature.getArgumentTypes();
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
for (int i = 0, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
if (argType.getSort() == Type.OBJECT) {
- StackValue.onStack(JetTypeMapper.TYPE_OBJECT).put(originalArgTypes[i], iv);
+ StackValue.onStack(JetTypeMapper.OBJECT_TYPE).put(originalArgTypes[i], iv);
}
else if (argType.getSort() == Type.ARRAY) {
- StackValue.onStack(JetTypeMapper.ARRAY_GENERIC_TYPE).put(originalArgTypes[i], iv);
+ StackValue.onStack(JetTypeMapper.JAVA_ARRAY_GENERIC_TYPE).put(originalArgTypes[i], iv);
}
//noinspection AssignmentToForLoopParameter
@@ -699,22 +699,22 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
Type[] argTypes = method.getArgumentTypes();
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
for (int i = 0, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
if (argType.getSort() == Type.OBJECT) {
- StackValue.onStack(JetTypeMapper.TYPE_OBJECT).put(method.getArgumentTypes()[i], iv);
+ StackValue.onStack(JetTypeMapper.OBJECT_TYPE).put(method.getArgumentTypes()[i], iv);
}
else if (argType.getSort() == Type.ARRAY) {
- StackValue.onStack(JetTypeMapper.ARRAY_GENERIC_TYPE).put(method.getArgumentTypes()[i], iv);
+ StackValue.onStack(JetTypeMapper.JAVA_ARRAY_GENERIC_TYPE).put(method.getArgumentTypes()[i], iv);
}
//noinspection AssignmentToForLoopParameter
reg += argType.getSize();
}
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
field.put(field.type, iv);
ClassDescriptor classDescriptor = (ClassDescriptor) overriddenDescriptor.getContainingDeclaration();
String internalName =
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
index ee3011a08ab18..3fe4135ef910c 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ImplementationBodyCodegen.java
@@ -47,7 +47,7 @@
import java.util.*;
import static org.jetbrains.asm4.Opcodes.*;
-import static org.jetbrains.jet.codegen.JetTypeMapper.TYPE_OBJECT;
+import static org.jetbrains.jet.codegen.JetTypeMapper.OBJECT_TYPE;
/**
* @author max
@@ -400,7 +400,7 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
for (int i = 1, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
@@ -437,7 +437,7 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
if (original.getVisibility() == Visibilities.PRIVATE) {
iv.getfield(typeMapper.getOwner(original, OwnerKind.IMPLEMENTATION).getInternalName(), original.getName().getName(),
originalMethod.getReturnType().getDescriptor());
@@ -472,7 +472,7 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
Type[] argTypes = method.getArgumentTypes();
for (int i = 1, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
@@ -701,7 +701,7 @@ else if (superCall instanceof JetDelegatorToSuperClass) {
if (closure != null) {
int k = hasOuterThis ? 2 : 1;
if (closure.captureReceiver != null) {
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
final Type asmType = typeMapper.mapType(closure.captureReceiver.getDefaultType(), MapTypeMode.IMPL);
iv.load(1, asmType);
iv.putfield(typeMapper.mapType(descriptor.getDefaultType(), MapTypeMode.VALUE).getInternalName(), "receiver$0",
@@ -715,7 +715,7 @@ else if (superCall instanceof JetDelegatorToSuperClass) {
if (sharedVarType == null) {
sharedVarType = typeMapper.mapType(((VariableDescriptor) varDescr).getType(), MapTypeMode.VALUE);
}
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
iv.load(k, StackValue.refType(sharedVarType));
k += StackValue.refType(sharedVarType).getSize();
iv.putfield(typeMapper.mapType(descriptor.getDefaultType(), MapTypeMode.VALUE).getInternalName(),
@@ -765,7 +765,7 @@ private void genSuperCallToDelegatorToSuperClass(InstructionAdapter iv) {
assert superType != null;
ClassDescriptor superClassDescriptor = (ClassDescriptor) superType.getConstructor().getDeclarationDescriptor();
if (typeMapper.hasThis0(superClassDescriptor)) {
- iv.load(1, JetTypeMapper.TYPE_OBJECT);
+ iv.load(1, JetTypeMapper.OBJECT_TYPE);
parameterTypes.add(typeMapper.mapType(
typeMapper.getClosureAnnotator().getEclosingClassDescriptor(descriptor).getDefaultType(), MapTypeMode.VALUE));
}
@@ -778,7 +778,7 @@ private void genSuperCallToDelegatorToSuperClass(InstructionAdapter iv) {
private void genSimpleSuperCall(InstructionAdapter iv) {
iv.load(0, Type.getType("L" + superClass + ";"));
if (descriptor.getKind() == ClassKind.ENUM_CLASS || descriptor.getKind() == ClassKind.ENUM_ENTRY) {
- iv.load(1, JetTypeMapper.JL_STRING_TYPE);
+ iv.load(1, JetTypeMapper.JAVA_STRING_TYPE);
iv.load(2, Type.INT_TYPE);
iv.invokespecial(superClass, "<init>", "(Ljava/lang/String;I)V");
}
@@ -1025,7 +1025,7 @@ else if (state.getClassBuilderMode() == ClassBuilderMode.FULL) {
Type[] argTypes = function.getArgumentTypes();
List<Type> originalArgTypes = jvmSignature.getValueParameterTypes();
InstructionAdapter iv = new InstructionAdapter(mv);
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
for (int i = 0, reg = 1; i < argTypes.length; i++) {
Type argType = argTypes[i];
iv.load(reg, argType);
@@ -1065,9 +1065,9 @@ private void generateDelegatorToConstructorCall(
) {
ClassDescriptor classDecl = constructorDescriptor.getContainingDeclaration();
- iv.load(0, TYPE_OBJECT);
+ iv.load(0, OBJECT_TYPE);
if (classDecl.getKind() == ClassKind.ENUM_CLASS || classDecl.getKind() == ClassKind.ENUM_ENTRY) {
- iv.load(1, JetTypeMapper.TYPE_OBJECT);
+ iv.load(1, JetTypeMapper.OBJECT_TYPE);
iv.load(2, Type.INT_TYPE);
}
@@ -1183,7 +1183,7 @@ private void initializeEnumConstants(InstructionAdapter iv) {
}
iv.dup();
iv.putstatic(myAsmType.getInternalName(), enumConstant.getName(), "L" + myAsmType.getInternalName() + ";");
- iv.astore(TYPE_OBJECT);
+ iv.astore(OBJECT_TYPE);
}
iv.putstatic(myAsmType.getInternalName(), "$VALUES", arrayAsmType.getDescriptor());
}
@@ -1206,7 +1206,7 @@ public static void generateInitializers(
Type type = typeMapper.mapType(jetType, MapTypeMode.VALUE);
if (skipDefaultValue(propertyDescriptor, value, type)) continue;
}
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
Type type = codegen.expressionType(initializer);
if (jetType.isNullable()) {
type = JetTypeMapper.boxType(type);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java b/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
index 84d2ab5b4e2b5..1e26a784248f2 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/JetTypeMapper.java
@@ -40,10 +40,10 @@
import org.jetbrains.jet.lang.types.lang.JetStandardLibrary;
import org.jetbrains.jet.lang.types.lang.JetStandardLibraryNames;
-import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Iterator;
import java.util.List;
import static org.jetbrains.asm4.Opcodes.*;
@@ -53,36 +53,35 @@
* @author alex.tkachman
*/
public class JetTypeMapper {
- public static final Type TYPE_OBJECT = Type.getObjectType("java/lang/Object");
- public static final Type TYPE_THROWABLE = Type.getObjectType("java/lang/Throwable");
- public static final Type TYPE_NOTHING = Type.getObjectType("jet/Nothing");
- public static final Type JL_NUMBER_TYPE = Type.getObjectType("java/lang/Number");
- public static final Type JL_STRING_BUILDER = Type.getObjectType("java/lang/StringBuilder");
- public static final Type JL_STRING_TYPE = Type.getObjectType("java/lang/String");
- public static final Type JL_ENUM_TYPE = Type.getObjectType("java/lang/Enum");
- public static final Type JL_CHAR_SEQUENCE_TYPE = Type.getObjectType("java/lang/CharSequence");
- public static final Type JL_COMPARABLE_TYPE = Type.getObjectType("java/lang/Comparable");
- public static final Type JL_ITERABLE_TYPE = Type.getObjectType("java/lang/Iterable");
- public static final Type JL_ITERATOR_TYPE = Type.getObjectType("java/util/Iterator");
- public static final Type JL_CLASS_TYPE = Type.getObjectType("java/lang/Class");
- public static final Type JL_BOOLEAN_TYPE = Type.getObjectType("java/lang/Boolean");
-
- public static final Type ARRAY_GENERIC_TYPE = Type.getType(Object[].class);
- public static final Type TUPLE0_TYPE = Type.getObjectType("jet/Tuple0");
-
- public static final Type TYPE_ITERATOR = Type.getObjectType("jet/Iterator");
- public static final Type TYPE_INT_RANGE = Type.getObjectType("jet/IntRange");
- public static final Type TYPE_SHARED_VAR = Type.getObjectType("jet/runtime/SharedVar$Object");
- public static final Type TYPE_SHARED_INT = Type.getObjectType("jet/runtime/SharedVar$Int");
- public static final Type TYPE_SHARED_DOUBLE = Type.getObjectType("jet/runtime/SharedVar$Double");
- public static final Type TYPE_SHARED_FLOAT = Type.getObjectType("jet/runtime/SharedVar$Float");
- public static final Type TYPE_SHARED_BYTE = Type.getObjectType("jet/runtime/SharedVar$Byte");
- public static final Type TYPE_SHARED_SHORT = Type.getObjectType("jet/runtime/SharedVar$Short");
- public static final Type TYPE_SHARED_CHAR = Type.getObjectType("jet/runtime/SharedVar$Char");
- public static final Type TYPE_SHARED_LONG = Type.getObjectType("jet/runtime/SharedVar$Long");
- public static final Type TYPE_SHARED_BOOLEAN = Type.getObjectType("jet/runtime/SharedVar$Boolean");
- public static final Type TYPE_FUNCTION0 = Type.getObjectType("jet/Function0");
- public static final Type TYPE_FUNCTION1 = Type.getObjectType("jet/Function1");
+ public static final Type OBJECT_TYPE = Type.getType(Object.class);
+ public static final Type JAVA_NUMBER_TYPE = Type.getType(Number.class);
+ public static final Type JAVA_STRING_BUILDER_TYPE = Type.getType(StringBuilder.class);
+ public static final Type JAVA_STRING_TYPE = Type.getType(String.class);
+ public static final Type JAVA_ENUM_TYPE = Type.getType(Enum.class);
+ public static final Type JAVA_CHAR_SEQUENCE_TYPE = Type.getType(CharSequence.class);
+ public static final Type JAVA_COMPARABLE_TYPE = Type.getType(Comparable.class);
+ public static final Type JAVA_THROWABLE_TYPE = Type.getType(Throwable.class);
+ public static final Type JAVA_ITERABLE_TYPE = Type.getType(Iterable.class);
+ public static final Type JAVA_ITERATOR_TYPE = Type.getType(Iterator.class);
+ public static final Type JAVA_CLASS_TYPE = Type.getType(Class.class);
+ public static final Type JAVA_BOOLEAN_TYPE = Type.getType(Boolean.class);
+ public static final Type JAVA_ARRAY_GENERIC_TYPE = Type.getType(Object[].class);
+
+ public static final Type JET_NOTHING_TYPE = Type.getObjectType("jet/Nothing");
+ public static final Type JET_TUPLE0_TYPE = Type.getObjectType("jet/Tuple0");
+ public static final Type JET_FUNCTION0_TYPE = Type.getObjectType("jet/Function0");
+ public static final Type JET_FUNCTION1_TYPE = Type.getObjectType("jet/Function1");
+ public static final Type JET_ITERATOR_TYPE = Type.getObjectType("jet/Iterator");
+ public static final Type JET_INT_RANGE_TYPE = Type.getObjectType("jet/IntRange");
+ public static final Type JET_SHARED_VAR_TYPE = Type.getObjectType("jet/runtime/SharedVar$Object");
+ public static final Type JET_SHARED_INT_TYPE = Type.getObjectType("jet/runtime/SharedVar$Int");
+ public static final Type JET_SHARED_DOUBLE_TYPE = Type.getObjectType("jet/runtime/SharedVar$Double");
+ public static final Type JET_SHARED_FLOAT_TYPE = Type.getObjectType("jet/runtime/SharedVar$Float");
+ public static final Type JET_SHARED_BYTE_TYPE = Type.getObjectType("jet/runtime/SharedVar$Byte");
+ public static final Type JET_SHARED_SHORT_TYPE = Type.getObjectType("jet/runtime/SharedVar$Short");
+ public static final Type JET_SHARED_CHAR_TYPE = Type.getObjectType("jet/runtime/SharedVar$Char");
+ public static final Type JET_SHARED_LONG_TYPE = Type.getObjectType("jet/runtime/SharedVar$Long");
+ public static final Type JET_SHARED_BOOLEAN_TYPE = Type.getObjectType("jet/runtime/SharedVar$Boolean");
public BindingContext bindingContext;
private ClosureAnnotator closureAnnotator;
@@ -254,7 +253,7 @@ else if (jetType.equals(JetStandardClasses.getNothingType())) {
if (signatureVisitor != null) {
signatureVisitor.writeNothing(true);
}
- return TYPE_OBJECT;
+ return OBJECT_TYPE;
}
return mapType(jetType, signatureVisitor, MapTypeMode.VALUE);
}
@@ -413,7 +412,7 @@ else if (kind == MapTypeMode.IMPL) {
r = Type.getType("[" + boxType(mapType(memberType, kind)).getDescriptor());
}
else {
- r = ARRAY_GENERIC_TYPE;
+ r = JAVA_ARRAY_GENERIC_TYPE;
}
checkValidType(r);
return r;
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/KotlinToJavaTypesMap.java b/compiler/backend/src/org/jetbrains/jet/codegen/KotlinToJavaTypesMap.java
index c0d653b31c14d..73421141c3390 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/KotlinToJavaTypesMap.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/KotlinToJavaTypesMap.java
@@ -25,7 +25,6 @@
import org.jetbrains.jet.lang.resolve.DescriptorUtils;
import org.jetbrains.jet.lang.resolve.java.JvmClassName;
import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
-import org.jetbrains.jet.lang.resolve.name.FqNameBase;
import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe;
import org.jetbrains.jet.lang.types.JetType;
import org.jetbrains.jet.lang.types.lang.PrimitiveType;
@@ -83,7 +82,7 @@ private void registerNullable(@NotNull ClassName className, @NotNull Type nullab
}
public void init() {
- register(NOTHING, TYPE_NOTHING);
+ register(NOTHING, JET_NOTHING_TYPE);
for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
ClassName className = jvmPrimitiveType.getPrimitiveType().getClassName();
@@ -92,17 +91,17 @@ public void init() {
registerNullable(className, jvmPrimitiveType.getWrapper().getAsmType());
}
- register(ANY, TYPE_OBJECT);
- register(NUMBER, JL_NUMBER_TYPE);
- register(STRING, JL_STRING_TYPE);
- register(CHAR_SEQUENCE, JL_CHAR_SEQUENCE_TYPE);
- register(THROWABLE, TYPE_THROWABLE);
- register(COMPARABLE, JL_COMPARABLE_TYPE);
- register(ENUM, JL_ENUM_TYPE);
- register(ITERABLE, JL_ITERABLE_TYPE);
- register(ITERATOR, JL_ITERATOR_TYPE);
- register(MUTABLE_ITERABLE, JL_ITERABLE_TYPE);
- register(MUTABLE_ITERATOR, JL_ITERATOR_TYPE);
+ register(ANY, OBJECT_TYPE);
+ register(NUMBER, JAVA_NUMBER_TYPE);
+ register(STRING, JAVA_STRING_TYPE);
+ register(CHAR_SEQUENCE, JAVA_CHAR_SEQUENCE_TYPE);
+ register(THROWABLE, JAVA_THROWABLE_TYPE);
+ register(COMPARABLE, JAVA_COMPARABLE_TYPE);
+ register(ENUM, JAVA_ENUM_TYPE);
+ register(ITERABLE, JAVA_ITERABLE_TYPE);
+ register(ITERATOR, JAVA_ITERATOR_TYPE);
+ register(MUTABLE_ITERABLE, JAVA_ITERABLE_TYPE);
+ register(MUTABLE_ITERATOR, JAVA_ITERATOR_TYPE);
for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
index dad268eb5f8f6..c2b8229baae89 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/PropertyCodegen.java
@@ -215,7 +215,7 @@ public void generateDefaultGetter(PropertyDescriptor propertyDescriptor, int fla
else {
InstructionAdapter iv = new InstructionAdapter(mv);
if (kind != OwnerKind.NAMESPACE) {
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
}
final Type type = state.getInjector().getJetTypeMapper().mapType(propertyDescriptor.getType(), MapTypeMode.VALUE);
@@ -225,7 +225,7 @@ public void generateDefaultGetter(PropertyDescriptor propertyDescriptor, int fla
if (kind instanceof OwnerKind.DelegateKind) {
OwnerKind.DelegateKind dk = (OwnerKind.DelegateKind) kind;
- dk.getDelegate().put(JetTypeMapper.TYPE_OBJECT, iv);
+ dk.getDelegate().put(JetTypeMapper.OBJECT_TYPE, iv);
iv.invokeinterface(dk.getOwnerClass(), getterName, descriptor);
}
else {
@@ -320,7 +320,7 @@ public void generateDefaultSetter(PropertyDescriptor propertyDescriptor, int fla
final Type type = state.getInjector().getJetTypeMapper().mapType(propertyDescriptor.getType(), MapTypeMode.VALUE);
int paramCode = 0;
if (kind != OwnerKind.NAMESPACE) {
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
paramCode = 1;
}
@@ -330,8 +330,8 @@ public void generateDefaultSetter(PropertyDescriptor propertyDescriptor, int fla
if (kind instanceof OwnerKind.DelegateKind) {
OwnerKind.DelegateKind dk = (OwnerKind.DelegateKind) kind;
- iv.load(0, JetTypeMapper.TYPE_OBJECT);
- dk.getDelegate().put(JetTypeMapper.TYPE_OBJECT, iv);
+ iv.load(0, JetTypeMapper.OBJECT_TYPE);
+ dk.getDelegate().put(JetTypeMapper.OBJECT_TYPE, iv);
iv.load(paramCode, type);
iv.invokeinterface(dk.getOwnerClass(), setterName(propertyDescriptor.getName()), descriptor);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/ScriptCodegen.java b/compiler/backend/src/org/jetbrains/jet/codegen/ScriptCodegen.java
index 9b0b2f829b4ff..5bc78204c0001 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/ScriptCodegen.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/ScriptCodegen.java
@@ -38,7 +38,7 @@
import javax.inject.Inject;
import java.util.List;
-import static org.jetbrains.jet.codegen.JetTypeMapper.TYPE_OBJECT;
+import static org.jetbrains.jet.codegen.JetTypeMapper.OBJECT_TYPE;
/**
* @author Stepan Koltsov
@@ -159,7 +159,7 @@ private void genConstructor(
FrameMap frameMap = context.prepareFrame(jetTypeMapper);
for (ScriptDescriptor importedScript : importedScripts) {
- frameMap.enter(importedScript, TYPE_OBJECT);
+ frameMap.enter(importedScript, OBJECT_TYPE);
}
Type[] argTypes = jvmSignature.getAsmMethod().getArgumentTypes();
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java b/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
index 4abae0902b253..de80b0316f248 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/StackValue.java
@@ -35,7 +35,7 @@
import java.util.List;
-import static org.jetbrains.jet.codegen.JetTypeMapper.TYPE_OBJECT;
+import static org.jetbrains.jet.codegen.JetTypeMapper.OBJECT_TYPE;
/**
* @author yole
@@ -267,15 +267,15 @@ else if (toType == Type.DOUBLE_TYPE) {
v.iconst(0);
}
}
- else if (toType.equals(JetTypeMapper.TUPLE0_TYPE) && !fromType.equals(JetTypeMapper.TUPLE0_TYPE)) {
+ else if (toType.equals(JetTypeMapper.JET_TUPLE0_TYPE) && !fromType.equals(JetTypeMapper.JET_TUPLE0_TYPE)) {
pop(fromType, v);
putTuple0Instance(v);
}
- else if (toType.getSort() == Type.OBJECT && fromType.equals(TYPE_OBJECT) || toType.getSort() == Type.ARRAY) {
+ else if (toType.getSort() == Type.OBJECT && fromType.equals(OBJECT_TYPE) || toType.getSort() == Type.ARRAY) {
v.checkcast(toType);
}
else if (toType.getSort() == Type.OBJECT) {
- if (fromType.getSort() == Type.OBJECT && !toType.equals(TYPE_OBJECT)) {
+ if (fromType.getSort() == Type.OBJECT && !toType.equals(OBJECT_TYPE)) {
v.checkcast(toType);
}
else {
@@ -283,7 +283,7 @@ else if (toType.getSort() == Type.OBJECT) {
}
}
else if (fromType.getSort() == Type.OBJECT && toType.getSort() <= Type.DOUBLE) {
- if (fromType.equals(TYPE_OBJECT)) {
+ if (fromType.equals(OBJECT_TYPE)) {
if (toType.getSort() == Type.BOOLEAN) {
v.checkcast(JvmPrimitiveType.BOOLEAN.getWrapper().getAsmType());
}
@@ -291,7 +291,7 @@ else if (toType.getSort() == Type.CHAR) {
v.checkcast(JvmPrimitiveType.CHAR.getWrapper().getAsmType());
}
else {
- v.checkcast(JetTypeMapper.JL_NUMBER_TYPE);
+ v.checkcast(JetTypeMapper.JAVA_NUMBER_TYPE);
}
}
unbox(toType, v);
@@ -477,11 +477,11 @@ public void put(Type type, InstructionAdapter v) {
if (type == Type.VOID_TYPE) {
return;
}
- if (type.equals(JetTypeMapper.TUPLE0_TYPE)) {
+ if (type.equals(JetTypeMapper.JET_TUPLE0_TYPE)) {
putTuple0Instance(v);
return;
}
- if (type != Type.BOOLEAN_TYPE && !type.equals(TYPE_OBJECT) && !type.equals(JetTypeMapper.JL_BOOLEAN_TYPE)) {
+ if (type != Type.BOOLEAN_TYPE && !type.equals(OBJECT_TYPE) && !type.equals(JetTypeMapper.JAVA_BOOLEAN_TYPE)) {
throw new UnsupportedOperationException("don't know how to put a compare as a non-boolean type " + type);
}
putAsBoolean(v);
@@ -570,7 +570,7 @@ public void put(Type type, InstructionAdapter v) {
myOperand.put(type, v); // the operand will remove itself from the stack if needed
return;
}
- if (type != Type.BOOLEAN_TYPE && !type.equals(TYPE_OBJECT) && !type.equals(JetTypeMapper.JL_BOOLEAN_TYPE)) {
+ if (type != Type.BOOLEAN_TYPE && !type.equals(OBJECT_TYPE) && !type.equals(JetTypeMapper.JAVA_BOOLEAN_TYPE)) {
throw new UnsupportedOperationException("don't know how to put a compare as a non-boolean type");
}
putAsBoolean(v);
@@ -718,10 +718,10 @@ public void dupReceiver(InstructionAdapter v) {
int firstTypeParamIndex = -1;
for (int i = typeParameters.size() - 1; i >= 0; --i) {
if (typeParameters.get(i).isReified()) {
- frame.enterTemp(TYPE_OBJECT);
+ frame.enterTemp(OBJECT_TYPE);
lastIndex++;
size++;
- v.store(firstTypeParamIndex = lastIndex - 1, TYPE_OBJECT);
+ v.store(firstTypeParamIndex = lastIndex - 1, OBJECT_TYPE);
}
}
@@ -739,10 +739,10 @@ public void dupReceiver(InstructionAdapter v) {
ReceiverDescriptor thisObject = resolvedGetCall.getThisObject();
int thisIndex = -1;
if (thisObject.exists()) {
- frame.enterTemp(TYPE_OBJECT);
+ frame.enterTemp(OBJECT_TYPE);
lastIndex++;
size++;
- v.store((thisIndex = lastIndex) - 1, TYPE_OBJECT);
+ v.store((thisIndex = lastIndex) - 1, OBJECT_TYPE);
}
// for setter
@@ -756,7 +756,7 @@ public void dupReceiver(InstructionAdapter v) {
}
else {
realReceiverIndex = thisIndex;
- realReceiverType = TYPE_OBJECT;
+ realReceiverType = OBJECT_TYPE;
}
}
else {
@@ -771,7 +771,7 @@ public void dupReceiver(InstructionAdapter v) {
if (resolvedSetCall.getThisObject().exists()) {
if (resolvedSetCall.getReceiverArgument().exists()) {
- codegen.generateFromResolvedCall(resolvedSetCall.getThisObject(), TYPE_OBJECT);
+ codegen.generateFromResolvedCall(resolvedSetCall.getThisObject(), OBJECT_TYPE);
}
v.load(realReceiverIndex - realReceiverType.getSize(), realReceiverType);
}
@@ -794,7 +794,7 @@ public void dupReceiver(InstructionAdapter v) {
// restoring original
if (thisIndex != -1) {
- v.load(thisIndex - 1, TYPE_OBJECT);
+ v.load(thisIndex - 1, OBJECT_TYPE);
}
if (receiverIndex != -1) {
@@ -806,7 +806,7 @@ public void dupReceiver(InstructionAdapter v) {
index = firstTypeParamIndex;
for (int i = 0; i != typeParameters.size(); ++i) {
if (typeParameters.get(i).isReified()) {
- v.load(index - 1, TYPE_OBJECT);
+ v.load(index - 1, OBJECT_TYPE);
index--;
}
}
@@ -821,7 +821,7 @@ public void dupReceiver(InstructionAdapter v) {
}
for (int i = 0; i < size; i++) {
- frame.leaveTemp(TYPE_OBJECT);
+ frame.leaveTemp(OBJECT_TYPE);
}
}
}
@@ -1022,7 +1022,7 @@ public int getIndex() {
@Override
public void put(Type type, InstructionAdapter v) {
- v.load(index, TYPE_OBJECT);
+ v.load(index, OBJECT_TYPE);
Type refType = refType(this.type);
Type sharedType = sharedTypeForType(this.type);
v.visitFieldInsn(Opcodes.GETFIELD, sharedType.getInternalName(), "ref", refType.getDescriptor());
@@ -1030,13 +1030,13 @@ public void put(Type type, InstructionAdapter v) {
coerce(this.type, type, v);
if (isReleaseOnPut) {
v.aconst(null);
- v.store(index, TYPE_OBJECT);
+ v.store(index, OBJECT_TYPE);
}
}
@Override
public void store(Type topOfStackType, InstructionAdapter v) {
- v.load(index, TYPE_OBJECT);
+ v.load(index, OBJECT_TYPE);
v.swap();
Type refType = refType(this.type);
Type sharedType = sharedTypeForType(this.type);
@@ -1048,31 +1048,31 @@ public static Type sharedTypeForType(Type type) {
switch (type.getSort()) {
case Type.OBJECT:
case Type.ARRAY:
- return JetTypeMapper.TYPE_SHARED_VAR;
+ return JetTypeMapper.JET_SHARED_VAR_TYPE;
case Type.BYTE:
- return JetTypeMapper.TYPE_SHARED_BYTE;
+ return JetTypeMapper.JET_SHARED_BYTE_TYPE;
case Type.SHORT:
- return JetTypeMapper.TYPE_SHARED_SHORT;
+ return JetTypeMapper.JET_SHARED_SHORT_TYPE;
case Type.CHAR:
- return JetTypeMapper.TYPE_SHARED_CHAR;
+ return JetTypeMapper.JET_SHARED_CHAR_TYPE;
case Type.INT:
- return JetTypeMapper.TYPE_SHARED_INT;
+ return JetTypeMapper.JET_SHARED_INT_TYPE;
case Type.LONG:
- return JetTypeMapper.TYPE_SHARED_LONG;
+ return JetTypeMapper.JET_SHARED_LONG_TYPE;
case Type.BOOLEAN:
- return JetTypeMapper.TYPE_SHARED_BOOLEAN;
+ return JetTypeMapper.JET_SHARED_BOOLEAN_TYPE;
case Type.FLOAT:
- return JetTypeMapper.TYPE_SHARED_FLOAT;
+ return JetTypeMapper.JET_SHARED_FLOAT_TYPE;
case Type.DOUBLE:
- return JetTypeMapper.TYPE_SHARED_DOUBLE;
+ return JetTypeMapper.JET_SHARED_DOUBLE_TYPE;
default:
throw new UnsupportedOperationException();
@@ -1081,7 +1081,7 @@ public static Type sharedTypeForType(Type type) {
public static Type refType(Type type) {
if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
- return TYPE_OBJECT;
+ return OBJECT_TYPE;
}
return type;
@@ -1141,7 +1141,7 @@ public void put(Type type, InstructionAdapter v) {
@Override
public void store(Type topOfStackType, InstructionAdapter v) {
- prefix.put(TYPE_OBJECT, v);
+ prefix.put(OBJECT_TYPE, v);
suffix.store(topOfStackType, v);
}
}
@@ -1151,7 +1151,7 @@ private static class ThisOuter extends StackValue {
private final ClassDescriptor descriptor;
public ThisOuter(ExpressionCodegen codegen, ClassDescriptor descriptor) {
- super(TYPE_OBJECT);
+ super(OBJECT_TYPE);
this.codegen = codegen;
this.descriptor = descriptor;
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayGet.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayGet.java
index d5aa57215dfe2..641393cf443e7 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayGet.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayGet.java
@@ -42,7 +42,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
Type type = JetTypeMapper.correctElementType(receiver.type);
codegen.gen(arguments.get(0), Type.INT_TYPE);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIndices.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIndices.java
index 27ba2ad13cb9d..0342c1154de81 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIndices.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIndices.java
@@ -39,9 +39,9 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.arraylength();
v.invokestatic("jet/IntRange", "count", "(I)Ljet/IntRange;");
- return StackValue.onStack(JetTypeMapper.TYPE_INT_RANGE);
+ return StackValue.onStack(JetTypeMapper.JET_INT_RANGE_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIterator.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIterator.java
index 12d5c00c57bac..ec6871783f657 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIterator.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArrayIterator.java
@@ -50,7 +50,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
JetCallExpression call = (JetCallExpression) element;
FunctionDescriptor funDescriptor = (FunctionDescriptor) codegen.getBindingContext()
.get(BindingContext.REFERENCE_TARGET, (JetSimpleNameExpression) call.getCalleeExpression());
@@ -58,7 +58,7 @@ public StackValue generate(
ClassDescriptor containingDeclaration = (ClassDescriptor) funDescriptor.getContainingDeclaration().getOriginal();
if (JetStandardLibraryNames.ARRAY.is(containingDeclaration)) {
v.invokestatic("jet/runtime/ArrayIterator", "iterator", "([Ljava/lang/Object;)Ljava/util/Iterator;");
- return StackValue.onStack(JetTypeMapper.TYPE_ITERATOR);
+ return StackValue.onStack(JetTypeMapper.JET_ITERATOR_TYPE);
}
else {
for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySet.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySet.java
index fbb246db59a86..c6ce6e15fbb91 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySet.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySet.java
@@ -42,7 +42,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
Type type = JetTypeMapper.correctElementType(receiver.type);
codegen.gen(arguments.get(0), Type.INT_TYPE);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySize.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySize.java
index 8b77a3f991505..27cac29da8334 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySize.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ArraySize.java
@@ -42,7 +42,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.arraylength();
return StackValue.onStack(Type.INT_TYPE);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Concat.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Concat.java
index c115466b72402..6496a7e45a7fb 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Concat.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Concat.java
@@ -48,7 +48,7 @@ public StackValue generate(
codegen.invokeAppend(arguments.get(1));
}
else { // LHS.plus(RHS)
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
codegen.generateStringBuilderConstructor();
v.swap(); // StringBuilder LHS
codegen.invokeAppendMethod(expectedType); // StringBuilder(LHS)
@@ -56,7 +56,7 @@ public StackValue generate(
}
v.invokevirtual("java/lang/StringBuilder", "toString", "()Ljava/lang/String;");
- StackValue.onStack(JetTypeMapper.JL_STRING_TYPE).put(expectedType, v);
+ StackValue.onStack(JetTypeMapper.JAVA_STRING_TYPE).put(expectedType, v);
return StackValue.onStack(expectedType);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java
index a5cdeec1e7973..4dc5c75640be0 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumName.java
@@ -40,9 +40,9 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.invokevirtual("java/lang/Enum", "name", "()Ljava/lang/String;");
- StackValue.onStack(JetTypeMapper.JL_STRING_TYPE).put(expectedType, v);
+ StackValue.onStack(JetTypeMapper.JAVA_STRING_TYPE).put(expectedType, v);
return StackValue.onStack(expectedType);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java
index 48985a78d6252..77d5827f0acf9 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumOrdinal.java
@@ -40,7 +40,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.invokevirtual("java/lang/Enum", "ordinal", "()I");
StackValue.onStack(Type.INT_TYPE).put(expectedType, v);
return StackValue.onStack(expectedType);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java
index 94eef1995505a..8cc1eee6fa0ca 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/EnumValueOf.java
@@ -50,7 +50,7 @@ public StackValue generate(
Type type = state.getInjector().getJetTypeMapper().mapType(
returnType, MapTypeMode.VALUE);
assert arguments != null;
- codegen.gen(arguments.get(0), JetTypeMapper.JL_STRING_TYPE);
+ codegen.gen(arguments.get(0), JetTypeMapper.JAVA_STRING_TYPE);
v.invokestatic(type.getInternalName(), "valueOf", "(Ljava/lang/String;)" + type.getDescriptor());
StackValue.onStack(type).put(expectedType, v);
return StackValue.onStack(expectedType);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Equals.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Equals.java
index 54b5287e5cbe9..99f0eeaab6cfa 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Equals.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/Equals.java
@@ -50,7 +50,7 @@ public StackValue generate(
boolean leftNullable = true;
JetExpression rightExpr;
if (element instanceof JetCallExpression) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
JetCallExpression jetCallExpression = (JetCallExpression) element;
JetExpression calleeExpression = jetCallExpression.getCalleeExpression();
if (calleeExpression != null) {
@@ -66,16 +66,16 @@ public StackValue generate(
JetType leftType = codegen.getBindingContext().get(BindingContext.EXPRESSION_TYPE, leftExpr);
assert leftType != null;
leftNullable = leftType.isNullable();
- codegen.gen(leftExpr).put(JetTypeMapper.TYPE_OBJECT, v);
+ codegen.gen(leftExpr).put(JetTypeMapper.OBJECT_TYPE, v);
rightExpr = arguments.get(1);
}
JetType rightType = codegen.getBindingContext().get(BindingContext.EXPRESSION_TYPE, rightExpr);
- codegen.gen(rightExpr).put(JetTypeMapper.TYPE_OBJECT, v);
+ codegen.gen(rightExpr).put(JetTypeMapper.OBJECT_TYPE, v);
assert rightType != null;
return codegen
- .generateEqualsForExpressionsOnStack(JetTokens.EQEQ, JetTypeMapper.TYPE_OBJECT, JetTypeMapper.TYPE_OBJECT, leftNullable,
+ .generateEqualsForExpressionsOnStack(JetTokens.EQEQ, JetTypeMapper.OBJECT_TYPE, JetTypeMapper.OBJECT_TYPE, leftNullable,
rightType.isNullable());
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/HashCode.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/HashCode.java
index e4c97194e3fa7..d12a0c7eb092d 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/HashCode.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/HashCode.java
@@ -44,7 +44,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Object", "hashCode", "()I");
return StackValue.onStack(Type.INT_TYPE);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IdentityEquals.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IdentityEquals.java
index 092c007c52a09..20c73524fcf07 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IdentityEquals.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IdentityEquals.java
@@ -46,15 +46,15 @@ public StackValue generate(
@NotNull GenerationState state
) {
if (element instanceof JetCallExpression) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
- codegen.gen(arguments.get(0)).put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
+ codegen.gen(arguments.get(0)).put(JetTypeMapper.OBJECT_TYPE, v);
}
else {
assert element instanceof JetBinaryExpression;
JetBinaryExpression e = (JetBinaryExpression) element;
- codegen.gen(e.getLeft()).put(JetTypeMapper.TYPE_OBJECT, v);
- codegen.gen(e.getRight()).put(JetTypeMapper.TYPE_OBJECT, v);
+ codegen.gen(e.getLeft()).put(JetTypeMapper.OBJECT_TYPE, v);
+ codegen.gen(e.getRight()).put(JetTypeMapper.OBJECT_TYPE, v);
}
- return StackValue.cmp(JetTokens.EQEQEQ, JetTypeMapper.TYPE_OBJECT);
+ return StackValue.cmp(JetTokens.EQEQEQ, JetTypeMapper.OBJECT_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IteratorNext.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IteratorNext.java
index 2d4e72aa8cc9b..5b0f99ccd9ed0 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IteratorNext.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/IteratorNext.java
@@ -70,7 +70,7 @@ else if (expectedType == Type.DOUBLE_TYPE) {
else {
throw new UnsupportedOperationException();
}
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.invokevirtual("jet/" + name + "Iterator", "next" + name, "()" + expectedType.getDescriptor());
return StackValue.onStack(expectedType);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
index cadb011d4a5aa..93c361912d7eb 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassFunction.java
@@ -57,6 +57,6 @@ public StackValue generate(
else {
v.aconst(type);
}
- return StackValue.onStack(JetTypeMapper.JL_CLASS_TYPE);
+ return StackValue.onStack(JetTypeMapper.JAVA_CLASS_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
index 419c65374c5c4..42da8af0975ac 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/JavaClassProperty.java
@@ -53,6 +53,6 @@ public StackValue generate(
else {
v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;");
}
- return StackValue.onStack(JetTypeMapper.JL_CLASS_TYPE);
+ return StackValue.onStack(JetTypeMapper.JAVA_CLASS_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringGetChar.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringGetChar.java
index d0d3874bf4c3b..08b5db7e31440 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringGetChar.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringGetChar.java
@@ -43,7 +43,7 @@ public StackValue generate(
@NotNull GenerationState state
) {
if (receiver != null) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
}
if (arguments != null) {
codegen.gen(arguments.get(0)).put(Type.INT_TYPE, v);
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringLength.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringLength.java
index a7183c4ea3391..5504c0db82131 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringLength.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringLength.java
@@ -42,7 +42,7 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.invokeinterface("java/lang/CharSequence", "length", "()I");
return StackValue.onStack(Type.INT_TYPE);
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringPlus.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringPlus.java
index c889a9305988b..114731920546d 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringPlus.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StringPlus.java
@@ -43,14 +43,14 @@ public StackValue generate(
@NotNull GenerationState state
) {
if (receiver == null || receiver == StackValue.none()) {
- codegen.gen(arguments.get(0)).put(JetTypeMapper.JL_STRING_TYPE, v);
- codegen.gen(arguments.get(1)).put(JetTypeMapper.TYPE_OBJECT, v);
+ codegen.gen(arguments.get(0)).put(JetTypeMapper.JAVA_STRING_TYPE, v);
+ codegen.gen(arguments.get(1)).put(JetTypeMapper.OBJECT_TYPE, v);
}
else {
- receiver.put(JetTypeMapper.JL_STRING_TYPE, v);
- codegen.gen(arguments.get(0)).put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.JAVA_STRING_TYPE, v);
+ codegen.gen(arguments.get(0)).put(JetTypeMapper.OBJECT_TYPE, v);
}
v.invokestatic("jet/runtime/Intrinsics", "stringPlus", "(Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/String;");
- return StackValue.onStack(JetTypeMapper.JL_STRING_TYPE);
+ return StackValue.onStack(JetTypeMapper.JAVA_STRING_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StupidSync.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StupidSync.java
index 618543e664563..d0b72fa352e6d 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StupidSync.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/StupidSync.java
@@ -42,9 +42,9 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- codegen.pushMethodArguments((JetCallExpression) element, Arrays.asList(JetTypeMapper.TYPE_OBJECT, JetTypeMapper.TYPE_FUNCTION0));
+ codegen.pushMethodArguments((JetCallExpression) element, Arrays.asList(JetTypeMapper.OBJECT_TYPE, JetTypeMapper.JET_FUNCTION0_TYPE));
v.invokestatic("jet/runtime/Intrinsics", "stupidSync", "(Ljava/lang/Object;Ljet/Function0;)Ljava/lang/Object;");
- StackValue.onStack(JetTypeMapper.TYPE_OBJECT).put(expectedType, v);
+ StackValue.onStack(JetTypeMapper.OBJECT_TYPE).put(expectedType, v);
return StackValue.onStack(expectedType);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ToString.java b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ToString.java
index 34b1507b67486..601255291db28 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ToString.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/intrinsics/ToString.java
@@ -42,8 +42,8 @@ public StackValue generate(
StackValue receiver,
@NotNull GenerationState state
) {
- receiver.put(JetTypeMapper.TYPE_OBJECT, v);
+ receiver.put(JetTypeMapper.OBJECT_TYPE, v);
v.invokestatic("java/lang/String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;");
- return StackValue.onStack(JetTypeMapper.JL_STRING_TYPE);
+ return StackValue.onStack(JetTypeMapper.JAVA_STRING_TYPE);
}
}
diff --git a/compiler/backend/src/org/jetbrains/jet/codegen/signature/BothSignatureWriter.java b/compiler/backend/src/org/jetbrains/jet/codegen/signature/BothSignatureWriter.java
index d08c6e2d61011..142a0c0bc0230 100644
--- a/compiler/backend/src/org/jetbrains/jet/codegen/signature/BothSignatureWriter.java
+++ b/compiler/backend/src/org/jetbrains/jet/codegen/signature/BothSignatureWriter.java
@@ -196,7 +196,7 @@ public void writeNothing(boolean nullable) {
jetSignatureWriter.visitClassType("jet/Nothing", nullable, false);
jetSignatureWriter.visitEnd();
if (nullable) {
- writeAsmType0(JetTypeMapper.TYPE_OBJECT);
+ writeAsmType0(JetTypeMapper.OBJECT_TYPE);
}
else {
writeAsmType0(Type.VOID_TYPE);
|
ac1113b52380ee31595446c290509deafc484065
|
agorava$agorava-core
|
House cleaning in javadoc
Last Spi added to support Resolver concept
Constants extraction
|
a
|
https://github.com/agorava/agorava-core
|
diff --git a/agorava-core-api/src/main/java/org/agorava/AgoravaConstants.java b/agorava-core-api/src/main/java/org/agorava/AgoravaConstants.java
index 1697461..6839db4 100644
--- a/agorava-core-api/src/main/java/org/agorava/AgoravaConstants.java
+++ b/agorava-core-api/src/main/java/org/agorava/AgoravaConstants.java
@@ -139,9 +139,23 @@ public interface AgoravaConstants {
String CALLBACK_URL = "callback";
/**
- * parameter name to store internal callback in url
+ * parameter name to store internal callback in {@link org.agorava.api.oauth.OAuthSession#extraData}
*/
- String INTERN_CALLBACK_PARAM_NAME = "internalcallback";
+ String INTERN_CALLBACK_PARAM = "internalcallback";
+ /**
+ * parameter name used to propagate {@link org.agorava.api.storage.UserSessionRepository#getId()} in url
+ */
+ String REPOID_PARAM = "repoid";
+
+ /**
+ * cookie name used to store {@link org.agorava.api.storage.UserSessionRepository#getId()} on the browser
+ */
+ String RESOLVER_REPO_COOKIE_NAME = "agorava_repo_id";
+
+ /**
+ * parameter name in config containing the the lifetime of cookies
+ */
+ String RESOLVER_COOKIE_LIFE_PARAM = "cookie.life";
}
diff --git a/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java b/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java
index d23d815..d6644e3 100644
--- a/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java
+++ b/agorava-core-api/src/main/java/org/agorava/api/atinject/GenericBean.java
@@ -28,19 +28,17 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
- * This qualifier is used to mark Class to indicate that they hare the default implementation for a Generic bean
- * For a given {@link ProviderRelated} Qualifier.
+ * This qualifier is used to mark Class to indicate that it should be used to generate differrent beans for each {@link
+ * ProviderRelated} Qualifier.
* <p/>
* Provider services (i.e. Social Media) are dynamically discovered when Agorava is bootstrapped thanks to Provider services
* qualifiers
* defined in each module and bearing the {@link ProviderRelated} annotation.
* <p/>
* Bootstrap process retrieve Generic Beans (thanks to this qualifier) and produces qualified versions with {@link
- * ProviderRelated} qualifiers discovered previously except if specific implementation bearing concrete service related
- * qualifier is found.
+ * ProviderRelated} qualifiers discovered previously.
* <p/>
- * In any case (whether the bean is automatically produced from generic or specifically by third party developer) the
- * bootstrapping process will analyse generic beans to replace {@link InjectWithQualifier} annotation by injection with Bean
+ * The bootstrapping process will analyse generic beans to replace {@link InjectWithQualifier} annotation by injection with Bean
* qualifier
*
* @author Antoine Sabot-Durand
diff --git a/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java b/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java
index 2179c67..eba3b3c 100644
--- a/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java
+++ b/agorava-core-api/src/main/java/org/agorava/api/atinject/InjectWithQualifier.java
@@ -26,7 +26,7 @@
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
- * Annotation used in Generic Bean (qualified with {@link GenericBean})to mark injection point that should be modified by
+ * Annotation used in Generic Bean to mark injection point that should be modified by
* framework bootstrap to bear the same {@link ProviderRelated} qualifier than the containing bean.
* <p>For example:
* <pre>
diff --git a/agorava-core-api/src/main/java/org/agorava/api/oauth/application/OAuthAppSettingsBuilder.java b/agorava-core-api/src/main/java/org/agorava/api/oauth/application/OAuthAppSettingsBuilder.java
index c6ca31a..8e2ae71 100644
--- a/agorava-core-api/src/main/java/org/agorava/api/oauth/application/OAuthAppSettingsBuilder.java
+++ b/agorava-core-api/src/main/java/org/agorava/api/oauth/application/OAuthAppSettingsBuilder.java
@@ -54,6 +54,11 @@ public interface OAuthAppSettingsBuilder {
*/
String SCOPE = "scope";
+ /**
+ * key prefix label
+ */
+ String PREFIX = "prefix";
+
/**
* Set the qualifier of the Social Media for which the settings are intended.
*
diff --git a/agorava-core-api/src/main/java/org/agorava/spi/SessionResolver.java b/agorava-core-api/src/main/java/org/agorava/spi/SessionResolver.java
new file mode 100644
index 0000000..dd2d100
--- /dev/null
+++ b/agorava-core-api/src/main/java/org/agorava/spi/SessionResolver.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2013 Agorava
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.agorava.spi;
+
+import org.agorava.api.oauth.OAuthSession;
+import org.agorava.api.storage.UserSessionRepository;
+
+import java.io.Serializable;
+
+/**
+ * @author Antoine Sabot-Durand
+ */
+public interface SessionResolver extends Serializable {
+
+ OAuthSession getCurrentSession(UserSessionRepository repository);
+}
diff --git a/agorava-core-api/src/main/java/org/agorava/spi/UserSessionRepositoryResolver.java b/agorava-core-api/src/main/java/org/agorava/spi/UserSessionRepositoryResolver.java
new file mode 100644
index 0000000..13c4bd5
--- /dev/null
+++ b/agorava-core-api/src/main/java/org/agorava/spi/UserSessionRepositoryResolver.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2013 Agorava
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.agorava.spi;
+
+import org.agorava.api.storage.UserSessionRepository;
+
+import java.io.Serializable;
+
+/**
+ * Implementation should provide a way to retrieve the current (active) {@link org.agorava.api.storage.UserSessionRepository}
+ *
+ * @author Antoine Sabot-Durand
+ */
+public interface UserSessionRepositoryResolver extends Serializable {
+ /**
+ * @return the current repository
+ */
+ UserSessionRepository getCurrentRepository();
+}
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InApplicationProducer.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InApplicationProducer.java
index 89ac51e..b3faeb6 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InApplicationProducer.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InApplicationProducer.java
@@ -23,6 +23,8 @@
import org.agorava.api.storage.GlobalRepository;
import org.agorava.api.storage.UserSessionRepository;
import org.agorava.cdi.deltaspike.DifferentOrNull;
+import org.agorava.spi.SessionResolver;
+import org.agorava.spi.UserSessionRepositoryResolver;
import org.apache.deltaspike.core.api.exclude.Exclude;
import javax.enterprise.context.ApplicationScoped;
@@ -30,7 +32,6 @@
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import javax.inject.Named;
-import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Set;
@@ -39,18 +40,21 @@
*/
@ApplicationScoped
-@Exclude(onExpression = "producerScope,application", interpretedBy = DifferentOrNull.class)
-public class InApplicationProducer implements Serializable {
+@Exclude(onExpression = InApplicationProducer.RESOLVER + ",application", interpretedBy = DifferentOrNull.class)
+public class InApplicationProducer implements SessionResolver, UserSessionRepositoryResolver {
+
+ public static final String RESOLVER = "resolverType";
@Inject
GlobalRepository globalRepository;
+ @Override
@Produces
@Current
- @Named
+ @Named("currentRepo")
@ApplicationScoped
- public UserSessionRepository getCurrentRepo() {
+ public UserSessionRepository getCurrentRepository() {
return globalRepository.createNew();
}
@@ -85,10 +89,11 @@ protected OAuthSession resolveSession(InjectionPoint ip, @Current UserSessionRep
throw new UnsupportedOperationException("Cannot inject session whitout Current Qualifier in " + ip);
}
+ @Override
@Produces
@Named
public OAuthSession getCurrentSession(@Current UserSessionRepository repository) {
- return resolveSession(null,repository);
+ return resolveSession(null, repository);
}
}
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InCookieProducer.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InCookieProducer.java
index 5e5d2e5..a35d7ff 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InCookieProducer.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InCookieProducer.java
@@ -16,6 +16,7 @@
package org.agorava.cdi;
+import org.agorava.AgoravaConstants;
import org.agorava.api.atinject.Current;
import org.agorava.api.oauth.OAuthSession;
import org.agorava.api.storage.UserSessionRepository;
@@ -38,13 +39,11 @@
*/
@SessionScoped
-@Exclude(onExpression = "producerScope,cookie", interpretedBy = DifferentOrNull.class)
+@Exclude(onExpression = InApplicationProducer.RESOLVER + ",cookie", interpretedBy = DifferentOrNull.class)
public class InCookieProducer extends InRequestProducer {
- public final static String REPO_COOKIE_NAME = "agorava_repo_id";
-
@Inject
- @ConfigProperty(name = "cookie.life", defaultValue = "-1")
+ @ConfigProperty(name = AgoravaConstants.RESOLVER_COOKIE_LIFE_PARAM, defaultValue = "-1")
Integer cookielife;
@@ -56,23 +55,23 @@ public class InCookieProducer extends InRequestProducer {
protected String getRepoId() {
String id;
for (Cookie cookie : request.getCookies()) {
- if (cookie.getName().equals(REPO_COOKIE_NAME))
+ if (cookie.getName().equals(AgoravaConstants.RESOLVER_REPO_COOKIE_NAME))
return cookie.getValue();
}
return null;
}
private void setCookie(String id) {
- Cookie cookie = new Cookie(REPO_COOKIE_NAME, id);
+ Cookie cookie = new Cookie(AgoravaConstants.RESOLVER_REPO_COOKIE_NAME, id);
cookie.setMaxAge(cookielife);
response.addCookie(cookie);
}
@Produces
@Current
- @Named
+ @Named("currentRepo")
@RequestScoped
- public UserSessionRepository getCurrentRepo() {
+ public UserSessionRepository getCurrentRepository() {
String id = getRepoId();
if (id == null || globalRepository.get(id) == null) {
UserSessionRepository repo = globalRepository.createNew();
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InRequestProducer.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InRequestProducer.java
index 25b92d2..235788a 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InRequestProducer.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InRequestProducer.java
@@ -16,6 +16,7 @@
package org.agorava.cdi;
+import org.agorava.AgoravaConstants;
import org.agorava.api.atinject.Current;
import org.agorava.api.oauth.OAuthSession;
import org.agorava.api.oauth.application.OAuthAppSettings;
@@ -39,27 +40,26 @@
*/
@RequestScoped
-@Exclude(onExpression = "producerScope,request", interpretedBy = DifferentOrNull.class)
+@Exclude(onExpression = InApplicationProducer.RESOLVER + ",request", interpretedBy = DifferentOrNull.class)
public class InRequestProducer extends InApplicationProducer {
private static final long serialVersionUID = 6446160199657772110L;
-
@Inject
@Web
protected HttpServletRequest request;
protected String getRepoId() {
- return request.getParameter("repoid");
+ return request.getParameter(AgoravaConstants.REPOID_PARAM);
}
@Produces
@Current
- @Named
+ @Named("currentRepo")
@RequestScoped
- public UserSessionRepository getCurrentRepo() {
+ public UserSessionRepository getCurrentRepository() {
String id = getRepoId();
if (id == null || globalRepository.get(id) == null)
return globalRepository.createNew();
@@ -94,7 +94,7 @@ public OAuthAppSettings tune(OAuthAppSettings toTune) {
return new SimpleOAuthAppSettingsBuilder()
.readFromSettings(toTune)
.callback(new FacesUrlTransformer(toTune.getCallback())
- .appendParamIfNecessary("repoid", repo.getId()).getUrl())
+ .appendParamIfNecessary(AgoravaConstants.REPOID_PARAM, repo.getId()).getUrl())
.build();
}
}
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InSessionProducer.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InSessionProducer.java
index af552ec..e83a638 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InSessionProducer.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/InSessionProducer.java
@@ -32,15 +32,15 @@
*/
@SessionScoped
-@Exclude(onExpression = "producerScope,session", interpretedBy = DifferentOrNull.class)
+@Exclude(onExpression = InApplicationProducer.RESOLVER + ",session", interpretedBy = DifferentOrNull.class)
public class InSessionProducer extends InApplicationProducer {
@Produces
@Current
- @Named
+ @Named("currentRepo")
@SessionScoped
- public UserSessionRepository getCurrentRepo() {
+ public UserSessionRepository getCurrentRepository() {
return globalRepository.createNew();
}
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/OAuthLifeCycleServiceImpl.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/OAuthLifeCycleServiceImpl.java
index d7c11cd..bdbc544 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/OAuthLifeCycleServiceImpl.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/OAuthLifeCycleServiceImpl.java
@@ -161,7 +161,7 @@ else if (!repository.getCurrent().getServiceQualifier().equals(qualifier))
public String startDanceFor(String providerName, String internalCallBack) {
OAuthSession session = buildSessionFor(providerName);
if (internalCallBack != null && !"".equals(internalCallBack.trim()))
- session.getExtraData().put(AgoravaConstants.INTERN_CALLBACK_PARAM_NAME, internalCallBack);
+ session.getExtraData().put(AgoravaConstants.INTERN_CALLBACK_PARAM, internalCallBack);
return getCurrentService().getAuthorizationUrl();
}
diff --git a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java
index a4b6675..4880de8 100644
--- a/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java
+++ b/agorava-core-impl-cdi/src/main/java/org/agorava/cdi/extensions/AgoravaExtension.java
@@ -337,7 +337,7 @@ public void endOfExtension(@Observes AfterDeploymentValidation adv, BeanManager
new BeanResolverCdi();
producerScope = ConfigResolver.getPropertyValue("producerScope", "");
- internalCallBack = ConfigResolver.getPropertyValue(AgoravaConstants.INTERN_CALLBACK_PARAM_NAME);
+ internalCallBack = ConfigResolver.getPropertyValue(AgoravaConstants.INTERN_CALLBACK_PARAM);
if (internalCallBack == null) {
log.warning("No internal callback defined, it's defaulted to home page");
internalCallBack = "/";
diff --git a/agorava-core-impl-cdi/src/test/resources/agorava.properties b/agorava-core-impl-cdi/src/test/resources/agorava.properties
index 310815d..e1a2071 100644
--- a/agorava-core-impl-cdi/src/test/resources/agorava.properties
+++ b/agorava-core-impl-cdi/src/test/resources/agorava.properties
@@ -25,4 +25,4 @@ test.apiSecret=dummySecret2
test.scope=dummyScope
test.callback=oob
-producerScope=application
+resolver=application
diff --git a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java
index abd1b21..ef35906 100644
--- a/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java
+++ b/agorava-core-impl/src/main/java/org/agorava/oauth/OAuth10aServiceImpl.java
@@ -39,6 +39,7 @@
/**
* OAuth 1.0a implementation of {@link org.agorava.api.oauth.OAuthProvider}
*
+ * @author Antoine Sabot-Durand
* @author Pablo Fernandez
*/
diff --git a/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java b/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java
index 28df62a..9b089e6 100644
--- a/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java
+++ b/agorava-core-impl/src/main/java/org/agorava/servlet/OAuthCallbackServlet.java
@@ -40,7 +40,7 @@ public class OAuthCallbackServlet extends HttpServlet {
protected void renderResponse(HttpServletRequest req, HttpServletResponse resp) {
String internalCallBack = (String) lifeCycleService.getCurrentSession().getExtraData().get(AgoravaConstants
- .INTERN_CALLBACK_PARAM_NAME);
+ .INTERN_CALLBACK_PARAM);
if (internalCallBack == null)
internalCallBack = AgoravaContext.getInternalCallBack();
|
85407ae04f15917e2ff48f93929cc6b7e88c9c23
|
drools
|
[DROOLS-740] fix jitting of constraint with strings- concatenation--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java
index e2b1b4bc186..e508a1a71f6 100644
--- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java
+++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java
@@ -7221,4 +7221,23 @@ public void testCompilationFailureOnNonExistingVariable() {
assertDrlHasCompilationError(drl1, 1);
}
+
+ @Test
+ public void testJittedConstraintStringAndLong() {
+ // DROOLS-740
+ String drl =
+ " import org.drools.compiler.Person; " +
+ " rule 'hello person' " +
+ " when " +
+ " Person( name == \"Elizabeth\" + new Long(2L) ) " +
+ " then " +
+ " end " +
+ "\n";
+ KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL)
+ .build()
+ .newKieSession();
+
+ ksession.insert(new org.drools.compiler.Person("Elizabeth2", 88));
+ assertEquals(1, ksession.fireAllRules());
+ }
}
\ No newline at end of file
diff --git a/drools-core/src/main/java/org/drools/core/rule/constraint/ASMConditionEvaluatorJitter.java b/drools-core/src/main/java/org/drools/core/rule/constraint/ASMConditionEvaluatorJitter.java
index 2808af69aa3..48ab8a63163 100644
--- a/drools-core/src/main/java/org/drools/core/rule/constraint/ASMConditionEvaluatorJitter.java
+++ b/drools-core/src/main/java/org/drools/core/rule/constraint/ASMConditionEvaluatorJitter.java
@@ -675,12 +675,16 @@ private Class<?> jitAritmeticExpression(AritmeticExpression aritmeticExpression)
private void jitStringConcat(Expression left, Expression right) {
invokeConstructor(StringBuilder.class);
jitExpression(left, String.class);
- invokeVirtual(StringBuilder.class, "append", StringBuilder.class, left.getType());
+ invokeVirtual(StringBuilder.class, "append", StringBuilder.class, getTypeForAppend(left.getType()));
jitExpression(right, String.class);
- invokeVirtual(StringBuilder.class, "append", StringBuilder.class, right.getType());
+ invokeVirtual(StringBuilder.class, "append", StringBuilder.class, getTypeForAppend(right.getType()));
invokeVirtual(StringBuilder.class, "toString", String.class);
}
+ private Class<?> getTypeForAppend(Class<?> c) {
+ return c.isPrimitive() ? c : Object.class;
+ }
+
private void jitExpressionToPrimitiveType(Expression expression, Class<?> primitiveType) {
jitExpression(expression, primitiveType);
if (!isFixed(expression)) {
|
e865dfb1f190d36243c09c317dfc1f0c369178c9
|
tapiji
|
[RAP] Removes outdated encryption project from warfile definition.
|
p
|
https://github.com/tapiji/tapiji
|
diff --git a/org.eclipselabs.tapiji.translator.rap/translator.warproduct b/org.eclipselabs.tapiji.translator.rap/translator.warproduct
index fffbbe5b..29116104 100755
--- a/org.eclipselabs.tapiji.translator.rap/translator.warproduct
+++ b/org.eclipselabs.tapiji.translator.rap/translator.warproduct
@@ -71,7 +71,6 @@
<plugin id="org.eclipselabs.tapiji.translator.rap.model"/>
<plugin id="org.eclipselabs.tapiji.translator.rap.supplemental"/>
<plugin id="org.hibernate"/>
- <plugin id="org.jasypt"/>
<plugin id="org.junit"/>
</plugins>
@@ -140,7 +139,6 @@
<plugin id="org.eclipselabs.tapiji.translator.rap.model" autoStart="true" startLevel="0" />
<plugin id="org.eclipselabs.tapiji.translator.rap.supplemental" autoStart="true" startLevel="0" />
<plugin id="org.hibernate" autoStart="true" startLevel="0" />
- <plugin id="org.jasypt" autoStart="true" startLevel="0" />
<plugin id="org.junit" autoStart="true" startLevel="0" />
</configurations>
|
0c260cdc75e73af8273bb31137547338a81d0941
|
Vala
|
glib-2.0: Use strtol instead of atol for string.to_long
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi
index bac7126b7f..f1f215780b 100644
--- a/vapi/glib-2.0.vapi
+++ b/vapi/glib-2.0.vapi
@@ -911,8 +911,8 @@ public class string {
[CCode (cname = "atoi")]
public int to_int ();
- [CCode (cname = "atol")]
- public long to_long ();
+ [CCode (cname = "strtol")]
+ public long to_long (out weak string endptr = null, int _base = 0);
[CCode (cname = "g_ascii_strtod")]
public double to_double (out weak string endptr = null);
[CCode (cname = "strtoul")]
|
9f52c4b6c98b29363b2a0d7642523c7a26a8760e
|
Search_api
|
Issue #1819412 by drunken monkey: Added clean way for retrieving an index's data alterations and processors.
|
a
|
https://github.com/lucidworks/drupal_search_api
|
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index 83d46572..4a441f44 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -1,5 +1,7 @@
Search API 1.x, dev (xx/xx/xxxx):
---------------------------------
+- #1819412 by drunken monkey: Added clean way for retrieving an index's data
+ alterations and processors.
- #1838134 by das-peter, drunken monkey: Added hook_search_api_items_indexed().
- #1471310 by drunken monkey: Fixed handling of unset fields when indexing.
- #1594762 by drunken monkey, alanom, esclapes: Fixed detection of deleted items
diff --git a/includes/index_entity.inc b/includes/index_entity.inc
index 541d9184..f12bfbdd 100644
--- a/includes/index_entity.inc
+++ b/includes/index_entity.inc
@@ -537,8 +537,8 @@ class SearchApiIndex extends Entity {
'options list' => 'entity_metadata_language_list',
),
);
- // We use the reverse order here so the hierarchy for overwriting property infos is the same
- // as for actually overwriting the properties.
+ // We use the reverse order here so the hierarchy for overwriting property
+ // infos is the same as for actually overwriting the properties.
foreach (array_reverse($this->getAlterCallbacks()) as $callback) {
$props = $callback->propertyInfo();
if ($props) {
@@ -552,16 +552,14 @@ class SearchApiIndex extends Entity {
return $property_info;
}
- /**
- * Fills the $processors array for use by the pre-/postprocessing functions.
+ /**
+ * Loads all enabled data alterations for this index in proper order.
*
- * @return SearchApiIndex
- * The called object.
* @return array
* All enabled callbacks for this index, as SearchApiAlterCallbackInterface
* objects.
*/
- protected function getAlterCallbacks() {
+ public function getAlterCallbacks() {
if (isset($this->callbacks)) {
return $this->callbacks;
}
@@ -594,11 +592,13 @@ class SearchApiIndex extends Entity {
}
/**
+ * Loads all enabled processors for this index in proper order.
+ *
* @return array
* All enabled processors for this index, as SearchApiProcessorInterface
* objects.
*/
- protected function getProcessors() {
+ public function getProcessors() {
if (isset($this->processors)) {
return $this->processors;
}
|
9214f95cf4e5d19f5d226245043ea0669d276e59
|
hbase
|
HBASE-6170 Timeouts for row lock and scan should- be separate (Chris Trezzo)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1354325 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/hbase
|
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
index 9dac3884c0be..82cf976a1b38 100644
--- a/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
+++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/HConstants.java
@@ -536,16 +536,25 @@ public static enum Modify {
public static String HBASE_CLIENT_INSTANCE_ID = "hbase.client.instance.id";
/**
- * HRegion server lease period in milliseconds. Clients must report in within this period
- * else they are considered dead. Unit measured in ms (milliseconds).
+ * The row lock timeout period in milliseconds.
*/
- public static String HBASE_REGIONSERVER_LEASE_PERIOD_KEY =
- "hbase.regionserver.lease.period";
+ public static String HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD =
+ "hbase.regionserver.rowlock.timeout.period";
/**
- * Default value of {@link #HBASE_REGIONSERVER_LEASE_PERIOD_KEY}.
+ * Default value of {@link #HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD}.
*/
- public static long DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD = 60000;
+ public static int DEFAULT_HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD = 60000;
+
+ /**
+ * The client scanner timeout period in milliseconds.
+ */
+ public static String HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = "hbase.client.scanner.timeout.period";
+
+ /**
+ * Default value of {@link #HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD}.
+ */
+ public static int DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD = 60000;
/**
* timeout for each RPC
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
index 32ddf120c62b..ccb1dc3f79b5 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
@@ -106,9 +106,8 @@ public ClientScanner(final Configuration conf, final Scan scan,
HConstants.HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE_KEY,
HConstants.DEFAULT_HBASE_CLIENT_SCANNER_MAX_RESULT_SIZE);
}
- this.scannerTimeout = (int) conf.getLong(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
- HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD);
+ this.scannerTimeout = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
// check if application wants to collect scan metrics
byte[] enableMetrics = scan.getAttribute(
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
index 3556a7c05586..bad1d12df793 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java
@@ -422,6 +422,16 @@ public class HRegionServer implements ClientProtocol,
*/
private MovedRegionsCleaner movedRegionsCleaner;
+ /**
+ * The lease timeout period for row locks (milliseconds).
+ */
+ private final int rowLockLeaseTimeoutPeriod;
+
+ /**
+ * The lease timeout period for client scanners (milliseconds).
+ */
+ private final int scannerLeaseTimeoutPeriod;
+
/**
* Starts a HRegionServer at the default location
@@ -466,6 +476,13 @@ public HRegionServer(Configuration conf)
this.abortRequested = false;
this.stopped = false;
+ this.rowLockLeaseTimeoutPeriod = conf.getInt(
+ HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD);
+
+ this.scannerLeaseTimeoutPeriod = conf.getInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD,
+ HConstants.DEFAULT_HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD);
+
// Server to handle client requests.
String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
conf.get("hbase.regionserver.dns.interface", "default"),
@@ -705,10 +722,7 @@ private void initializeThreads() throws IOException {
this.compactionChecker = new CompactionChecker(this,
this.threadWakeFrequency * multiplier, this);
- this.leases = new Leases((int) conf.getLong(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY,
- HConstants.DEFAULT_HBASE_REGIONSERVER_LEASE_PERIOD),
- this.threadWakeFrequency);
+ this.leases = new Leases(this.threadWakeFrequency);
// Create the thread for the ThriftServer.
if (conf.getBoolean("hbase.regionserver.export.thrift", false)) {
@@ -2658,7 +2672,8 @@ protected long addRowLock(Integer r, HRegion region)
long lockId = nextLong();
String lockName = String.valueOf(lockId);
rowlocks.put(lockName, r);
- this.leases.createLease(lockName, new RowLockListener(lockName, region));
+ this.leases.createLease(lockName, this.rowLockLeaseTimeoutPeriod, new RowLockListener(lockName,
+ region));
return lockId;
}
@@ -2666,7 +2681,8 @@ protected long addScanner(RegionScanner s) throws LeaseStillHeldException {
long scannerId = nextLong();
String scannerName = String.valueOf(scannerId);
scanners.put(scannerName, s);
- this.leases.createLease(scannerName, new ScannerListener(scannerName));
+ this.leases.createLease(scannerName, this.scannerLeaseTimeoutPeriod, new ScannerListener(
+ scannerName));
return scannerId;
}
@@ -2925,7 +2941,7 @@ public ScanResponse scan(final RpcController controller,
}
scannerId = addScanner(scanner);
scannerName = String.valueOf(scannerId);
- ttl = leases.leasePeriod;
+ ttl = this.scannerLeaseTimeoutPeriod;
}
if (rows > 0) {
@@ -2999,7 +3015,7 @@ public ScanResponse scan(final RpcController controller,
// Adding resets expiration time on lease.
if (scanners.containsKey(scannerName)) {
if (lease != null) leases.addLease(lease);
- ttl = leases.leasePeriod;
+ ttl = this.scannerLeaseTimeoutPeriod;
}
}
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
index 0b7ed0e3861d..f2bd5680487d 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Leases.java
@@ -55,7 +55,6 @@
@InterfaceAudience.Private
public class Leases extends HasThread {
private static final Log LOG = LogFactory.getLog(Leases.class.getName());
- protected final int leasePeriod;
private final int leaseCheckFrequency;
private volatile DelayQueue<Lease> leaseQueue = new DelayQueue<Lease>();
protected final Map<String, Lease> leases = new HashMap<String, Lease>();
@@ -63,13 +62,11 @@ public class Leases extends HasThread {
/**
* Creates a lease monitor
- *
- * @param leasePeriod - length of time (milliseconds) that the lease is valid
+ *
* @param leaseCheckFrequency - how often the lease should be checked
- * (milliseconds)
+ * (milliseconds)
*/
- public Leases(final int leasePeriod, final int leaseCheckFrequency) {
- this.leasePeriod = leasePeriod;
+ public Leases(final int leaseCheckFrequency) {
this.leaseCheckFrequency = leaseCheckFrequency;
setDaemon(true);
}
@@ -135,15 +132,16 @@ public void close() {
}
/**
- * Obtain a lease
- *
+ * Obtain a lease.
+ *
* @param leaseName name of the lease
+ * @param leaseTimeoutPeriod length of the lease in milliseconds
* @param listener listener that will process lease expirations
* @throws LeaseStillHeldException
*/
- public void createLease(String leaseName, final LeaseListener listener)
- throws LeaseStillHeldException {
- addLease(new Lease(leaseName, listener));
+ public void createLease(String leaseName, int leaseTimeoutPeriod, final LeaseListener listener)
+ throws LeaseStillHeldException {
+ addLease(new Lease(leaseName, leaseTimeoutPeriod, listener));
}
/**
@@ -155,7 +153,7 @@ public void addLease(final Lease lease) throws LeaseStillHeldException {
if (this.stopRequested) {
return;
}
- lease.setExpirationTime(System.currentTimeMillis() + this.leasePeriod);
+ lease.resetExpirationTime();
synchronized (leaseQueue) {
if (leases.containsKey(lease.getLeaseName())) {
throw new LeaseStillHeldException(lease.getLeaseName());
@@ -202,7 +200,7 @@ public void renewLease(final String leaseName) throws LeaseException {
throw new LeaseException("lease '" + leaseName +
"' does not exist or has already expired");
}
- lease.setExpirationTime(System.currentTimeMillis() + leasePeriod);
+ lease.resetExpirationTime();
leaseQueue.add(lease);
}
}
@@ -241,16 +239,14 @@ Lease removeLease(final String leaseName) throws LeaseException {
static class Lease implements Delayed {
private final String leaseName;
private final LeaseListener listener;
+ private int leaseTimeoutPeriod;
private long expirationTime;
- Lease(final String leaseName, LeaseListener listener) {
- this(leaseName, listener, 0);
- }
-
- Lease(final String leaseName, LeaseListener listener, long expirationTime) {
+ Lease(final String leaseName, int leaseTimeoutPeriod, LeaseListener listener) {
this.leaseName = leaseName;
this.listener = listener;
- this.expirationTime = expirationTime;
+ this.leaseTimeoutPeriod = leaseTimeoutPeriod;
+ this.expirationTime = 0;
}
/** @return the lease name */
@@ -294,9 +290,11 @@ public int compareTo(Delayed o) {
return this.equals(o) ? 0 : (delta > 0 ? 1 : -1);
}
- /** @param expirationTime the expirationTime to set */
- public void setExpirationTime(long expirationTime) {
- this.expirationTime = expirationTime;
+ /**
+ * Resets the expiration time of the lease.
+ */
+ public void resetExpirationTime() {
+ this.expirationTime = System.currentTimeMillis() + this.leaseTimeoutPeriod;
}
}
-}
\ No newline at end of file
+}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
index 1f9358324973..362c094ba9e5 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestScannerTimeout.java
@@ -25,7 +25,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.*;
+import org.apache.hadoop.hbase.HBaseTestingUtility;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.LargeTests;
import org.apache.hadoop.hbase.catalog.MetaReader;
import org.apache.hadoop.hbase.regionserver.HRegionServer;
import org.apache.hadoop.hbase.util.Bytes;
@@ -48,7 +50,7 @@ public class TestScannerTimeout {
private final static byte[] SOME_BYTES = Bytes.toBytes("f");
private final static byte[] TABLE_NAME = Bytes.toBytes("t");
private final static int NB_ROWS = 10;
- // Be careful w/ what you set this timer too... it can get in the way of
+ // Be careful w/ what you set this timer to... it can get in the way of
// the mini cluster coming up -- the verification in particular.
private final static int SCANNER_TIMEOUT = 10000;
private final static int SCANNER_CACHING = 5;
@@ -59,7 +61,7 @@ public class TestScannerTimeout {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Configuration c = TEST_UTIL.getConfiguration();
- c.setInt("hbase.regionserver.lease.period", SCANNER_TIMEOUT);
+ c.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT);
// We need more than one region server for this test
TEST_UTIL.startMiniCluster(2);
HTable table = TEST_UTIL.createTable(TABLE_NAME, SOME_BYTES);
@@ -134,8 +136,7 @@ public void test2772() throws Exception {
// Since the RS is already created, this conf is client-side only for
// this new table
Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
- conf.setInt(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, SCANNER_TIMEOUT*100);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT * 100);
HTable higherScanTimeoutTable = new HTable(conf, TABLE_NAME);
ResultScanner r = higherScanTimeoutTable.getScanner(scan);
// This takes way less than SCANNER_TIMEOUT*100
@@ -201,8 +202,7 @@ public void test3686b() throws Exception {
// Since the RS is already created, this conf is client-side only for
// this new table
Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
- conf.setInt(
- HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, SCANNER_TIMEOUT*100);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, SCANNER_TIMEOUT * 100);
HTable higherScanTimeoutTable = new HTable(conf, TABLE_NAME);
ResultScanner r = higherScanTimeoutTable.getScanner(scan);
int count = 1;
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
index 7951b8a4dd22..25a0c0547483 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/coprocessor/TestCoprocessorInterface.java
@@ -325,8 +325,9 @@ Configuration initSplit() {
// Make lease timeout longer, lease checks less frequent
TEST_UTIL.getConfiguration().setInt(
"hbase.master.lease.thread.wakefrequency", 5 * 1000);
- TEST_UTIL.getConfiguration().setInt(
- "hbase.regionserver.lease.period", 10 * 1000);
+ TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, 10 * 1000);
+ TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD,
+ 10 * 1000);
// Increase the amount of time between client retries
TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 15 * 1000);
// This size should make it so we always split using the addContent
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
index 08949facf2a5..fbd17ba89540 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegion.java
@@ -3797,7 +3797,8 @@ private Configuration initSplit() {
// Make lease timeout longer, lease checks less frequent
conf.setInt("hbase.master.lease.thread.wakefrequency", 5 * 1000);
- conf.setInt(HConstants.HBASE_REGIONSERVER_LEASE_PERIOD_KEY, 10 * 1000);
+ conf.setInt(HConstants.HBASE_CLIENT_SCANNER_TIMEOUT_PERIOD, 10 * 1000);
+ conf.setInt(HConstants.HBASE_REGIONSERVER_ROWLOCK_TIMEOUT_PERIOD, 10 * 1000);
// Increase the amount of time between client retries
conf.setLong("hbase.client.pause", 15 * 1000);
|
9d3a1f0f0f6f7c1781e7f6b5785e23db6eb5703a
|
intellij-community
|
move statement should be enabled when moving to- the end of file--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/BaseMoveHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/BaseMoveHandler.java
index 7670facb22bad..6c8cbefcecf7f 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/BaseMoveHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/moveUpDown/BaseMoveHandler.java
@@ -65,7 +65,7 @@ public boolean isEnabled(Editor editor, DataContext dataContext) {
final LineRange range = mover.getInfo().toMove;
if (range.startLine == 0 && !isDown) return false;
- return range.endLine < maxLine || !isDown;
+ return range.endLine <= maxLine || !isDown;
}
@Nullable
|
cb8c0861e16bbab6ad11d1dc2b1820d054aa2fba
|
Delta Spike
|
DELTASPIKE-356 fix @Dependent handling for MessageContext
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/MessageContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/MessageContext.java
index 1faa08794..e765b10d9 100644
--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/MessageContext.java
+++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/MessageContext.java
@@ -31,7 +31,6 @@ public interface MessageContext extends LocaleResolver, Serializable, Cloneable
/**
* Clones the current MessageContext
*/
- @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
MessageContext clone();
/**
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageContext.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageContext.java
index 5f8a926a1..b77647197 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageContext.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessageContext.java
@@ -24,20 +24,30 @@
import org.apache.deltaspike.core.api.message.MessageInterpolator;
import org.apache.deltaspike.core.api.message.MessageResolver;
+import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Typed;
+import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
-@Typed()
+@Dependent
+@Typed(MessageContext.class)
class DefaultMessageContext implements MessageContext
{
private static final long serialVersionUID = -110779217295211303L;
+
+ @Inject
private MessageInterpolator messageInterpolator = null;
+
+ @Inject
private MessageResolver messageResolver = null;
+
+ @Inject
private LocaleResolver localeResolver = null;
+
private List<String> messageSources = new ArrayList<String>();
public DefaultMessageContext()
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java
index fc8ff2ef8..3bb99f7e9 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java
@@ -18,6 +18,8 @@
*/
package org.apache.deltaspike.core.impl.message;
+import javax.enterprise.context.Dependent;
+import javax.inject.Inject;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
@@ -36,8 +38,12 @@
import org.apache.deltaspike.core.util.ClassUtils;
+@Dependent
public class MessageBundleInvocationHandler implements InvocationHandler, Serializable
{
+ @Inject
+ private MessageContext baseMessageContext = null;
+
/**
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
* java.lang.reflect.Method, java.lang.Object[])
@@ -63,7 +69,7 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg
if (messageContext == null)
{
- messageContext = getDefaultMessageContext().clone();
+ messageContext = baseMessageContext.clone();
MessageContextConfig messageContextConfig =
method.getDeclaringClass().getAnnotation(MessageContextConfig.class);
@@ -163,8 +169,4 @@ private MessageContext resolveMessageContextFromArguments(Object[] args)
return null;
}
- private MessageContext getDefaultMessageContext()
- {
- return BeanProvider.getContextualReference(MessageContext.class);
- }
}
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageContextProducer.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageContextProducer.java
deleted file mode 100644
index e45d40fb6..000000000
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageContextProducer.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.deltaspike.core.impl.message;
-
-import org.apache.deltaspike.core.api.message.LocaleResolver;
-import org.apache.deltaspike.core.api.message.MessageContext;
-import org.apache.deltaspike.core.api.message.MessageInterpolator;
-import org.apache.deltaspike.core.api.message.MessageResolver;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.enterprise.context.Dependent;
-import javax.enterprise.inject.Produces;
-import javax.enterprise.inject.Typed;
-import javax.inject.Inject;
-
-@ApplicationScoped
-@SuppressWarnings("UnusedDeclaration")
-public class MessageContextProducer
-{
- @Inject
- private LocaleResolver localeResolver;
-
- @Inject
- private MessageInterpolator messageInterpolator;
-
- @Inject
- private MessageResolver messageResolver;
-
- @Produces
- @Typed(MessageContext.class) // needed for _not_ serving as LocaleResolver!
- @Dependent
- protected MessageContext createDefaultMessageContext()
- {
- MessageContext messageContext = new DefaultMessageContext();
-
- messageContext.messageInterpolator(messageInterpolator);
- messageContext.localeResolver(localeResolver);
- messageContext.messageResolver(messageResolver);
-
- return messageContext;
- }
-}
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/TypedMessageBundleProducer.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/TypedMessageBundleProducer.java
index f13ccb16f..fa8bc8ae5 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/TypedMessageBundleProducer.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/TypedMessageBundleProducer.java
@@ -22,6 +22,7 @@
import java.io.Serializable;
import java.lang.reflect.Proxy;
+import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
@@ -37,16 +38,17 @@ public class TypedMessageBundleProducer implements Serializable
private static final long serialVersionUID = -5077306523543940760L;
@Produces
+ @Dependent
@TypedMessageBundle
@SuppressWarnings("UnusedDeclaration")
- Object produceTypedMessageBundle(InjectionPoint injectionPoint)
+ Object produceTypedMessageBundle(InjectionPoint injectionPoint, MessageBundleInvocationHandler handler)
{
- return createMessageBundleProxy(ReflectionUtils.getRawType(injectionPoint.getType()));
+ return createMessageBundleProxy(ReflectionUtils.getRawType(injectionPoint.getType()), handler);
}
- private <T> T createMessageBundleProxy(Class<T> type)
+ private <T> T createMessageBundleProxy(Class<T> type, MessageBundleInvocationHandler handler)
{
return type.cast(Proxy.newProxyInstance(ClassUtils.getClassLoader(null),
- new Class<?>[]{type}, new MessageBundleInvocationHandler()));
+ new Class<?>[]{type}, handler));
}
}
diff --git a/deltaspike/examples/jsf-examples/pom.xml b/deltaspike/examples/jsf-examples/pom.xml
index 0a709df2b..131db2039 100644
--- a/deltaspike/examples/jsf-examples/pom.xml
+++ b/deltaspike/examples/jsf-examples/pom.xml
@@ -38,7 +38,13 @@
<profiles>
<profile>
- <!-- run it with: mvn clean package tomee:run -PtomeeConfig-->
+ <!--
+ * Run it with: mvn clean package tomee:run -PtomeeConfig
+ *
+ * For debugging add: -Dopenejb.server.debug=true
+ *
+ * The application can be browsed under http://localhost:8080/ds
+ -->
<id>tomeeConfig</id>
<build>
<defaultGoal>install</defaultGoal>
@@ -104,5 +110,9 @@
</dependency>
</dependencies>
+
+ <build>
+ <finalName>ds</finalName>
+ </build>
</project>
|
c447e0cf7766e1914296b648c56eb8d896eb0441
|
Vala
|
dbus-glib-1: Add bindings for DBusGProxy::destroy signal.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/dbus-glib-1.vapi b/vapi/dbus-glib-1.vapi
index 11f7bd6b75..92704111cd 100644
--- a/vapi/dbus-glib-1.vapi
+++ b/vapi/dbus-glib-1.vapi
@@ -128,6 +128,8 @@ namespace DBus {
public weak string get_path ();
public weak string get_bus_name ();
public weak string get_interface ();
+
+ public signal void destroy ();
}
[CCode (cname = "char", const_cname = "const char", copy_function = "g_strdup", free_function = "g_free", cheader_filename = "stdlib.h,string.h,glib.h", type_id = "DBUS_TYPE_G_OBJECT_PATH", marshaller_type_name = "STRING", get_value_function = "g_value_get_string", set_value_function = "g_value_set_string", type_signature = "o")]
|
afb690e2337caa1cb6b34ca921ae7d0edb7600b9
|
elasticsearch
|
refactor sub fetch phase to also allow for hits- level execution--
|
a
|
https://github.com/elastic/elasticsearch
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/SearchModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/SearchModule.java
index ab3d2d2909115..2251e3c64eeca 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/SearchModule.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/SearchModule.java
@@ -28,10 +28,10 @@
import org.elasticsearch.search.dfs.DfsPhase;
import org.elasticsearch.search.facet.FacetModule;
import org.elasticsearch.search.fetch.FetchPhase;
-import org.elasticsearch.search.fetch.explain.ExplainSearchHitPhase;
-import org.elasticsearch.search.fetch.matchedfilters.MatchedFiltersSearchHitPhase;
-import org.elasticsearch.search.fetch.script.ScriptFieldsSearchHitPhase;
-import org.elasticsearch.search.fetch.version.VersionSearchHitPhase;
+import org.elasticsearch.search.fetch.explain.ExplainFetchSubPhase;
+import org.elasticsearch.search.fetch.matchedfilters.MatchedFiltersFetchSubPhase;
+import org.elasticsearch.search.fetch.script.ScriptFieldsFetchSubPhase;
+import org.elasticsearch.search.fetch.version.VersionFetchSubPhase;
import org.elasticsearch.search.highlight.HighlightPhase;
import org.elasticsearch.search.query.QueryPhase;
@@ -51,10 +51,10 @@ public class SearchModule extends AbstractModule implements SpawnModules {
bind(SearchPhaseController.class).asEagerSingleton();
bind(FetchPhase.class).asEagerSingleton();
- bind(ExplainSearchHitPhase.class).asEagerSingleton();
- bind(ScriptFieldsSearchHitPhase.class).asEagerSingleton();
- bind(VersionSearchHitPhase.class).asEagerSingleton();
- bind(MatchedFiltersSearchHitPhase.class).asEagerSingleton();
+ bind(ExplainFetchSubPhase.class).asEagerSingleton();
+ bind(ScriptFieldsFetchSubPhase.class).asEagerSingleton();
+ bind(VersionFetchSubPhase.class).asEagerSingleton();
+ bind(MatchedFiltersFetchSubPhase.class).asEagerSingleton();
bind(HighlightPhase.class).asEagerSingleton();
bind(SearchServiceTransportAction.class).asEagerSingleton();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchPhase.java
index 88addc6cc1fbe..effa9bb1b8581 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchPhase.java
@@ -41,10 +41,10 @@
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.SearchPhase;
-import org.elasticsearch.search.fetch.explain.ExplainSearchHitPhase;
-import org.elasticsearch.search.fetch.matchedfilters.MatchedFiltersSearchHitPhase;
-import org.elasticsearch.search.fetch.script.ScriptFieldsSearchHitPhase;
-import org.elasticsearch.search.fetch.version.VersionSearchHitPhase;
+import org.elasticsearch.search.fetch.explain.ExplainFetchSubPhase;
+import org.elasticsearch.search.fetch.matchedfilters.MatchedFiltersFetchSubPhase;
+import org.elasticsearch.search.fetch.script.ScriptFieldsFetchSubPhase;
+import org.elasticsearch.search.fetch.version.VersionFetchSubPhase;
import org.elasticsearch.search.highlight.HighlightPhase;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.InternalSearchHitField;
@@ -62,18 +62,18 @@
*/
public class FetchPhase implements SearchPhase {
- private final SearchHitPhase[] hitPhases;
+ private final FetchSubPhase[] fetchSubPhases;
- @Inject public FetchPhase(HighlightPhase highlightPhase, ScriptFieldsSearchHitPhase scriptFieldsPhase,
- MatchedFiltersSearchHitPhase matchFiltersPhase, ExplainSearchHitPhase explainPhase, VersionSearchHitPhase versionPhase) {
- this.hitPhases = new SearchHitPhase[]{scriptFieldsPhase, matchFiltersPhase, explainPhase, highlightPhase, versionPhase};
+ @Inject public FetchPhase(HighlightPhase highlightPhase, ScriptFieldsFetchSubPhase scriptFieldsPhase,
+ MatchedFiltersFetchSubPhase matchFiltersPhase, ExplainFetchSubPhase explainPhase, VersionFetchSubPhase versionPhase) {
+ this.fetchSubPhases = new FetchSubPhase[]{scriptFieldsPhase, matchFiltersPhase, explainPhase, highlightPhase, versionPhase};
}
@Override public Map<String, ? extends SearchParseElement> parseElements() {
ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder();
parseElements.put("fields", new FieldsParseElement());
- for (SearchHitPhase hitPhase : hitPhases) {
- parseElements.putAll(hitPhase.parseElements());
+ for (FetchSubPhase fetchSubPhase : fetchSubPhases) {
+ parseElements.putAll(fetchSubPhase.parseElements());
}
return parseElements.build();
}
@@ -199,14 +199,21 @@ public void execute(SearchContext context) {
}
}
- for (SearchHitPhase hitPhase : hitPhases) {
- SearchHitPhase.HitContext hitContext = new SearchHitPhase.HitContext();
- if (hitPhase.executionNeeded(context)) {
+ for (FetchSubPhase fetchSubPhase : fetchSubPhases) {
+ FetchSubPhase.HitContext hitContext = new FetchSubPhase.HitContext();
+ if (fetchSubPhase.hitExecutionNeeded(context)) {
hitContext.reset(searchHit, subReader, subDoc, doc);
- hitPhase.execute(context, hitContext);
+ fetchSubPhase.hitExecute(context, hitContext);
}
}
}
+
+ for (FetchSubPhase fetchSubPhase : fetchSubPhases) {
+ if (fetchSubPhase.hitsExecutionNeeded(context)) {
+ fetchSubPhase.hitsExecute(context, hits);
+ }
+ }
+
context.fetchResult().hits(new InternalSearchHits(hits, context.queryResult().topDocs().totalHits, context.queryResult().topDocs().getMaxScore()));
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/SearchHitPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java
similarity index 85%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/SearchHitPhase.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java
index 7ce7ef9c13ad5..e234901fea855 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/SearchHitPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java
@@ -22,7 +22,6 @@
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.elasticsearch.ElasticSearchException;
-import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;
@@ -32,7 +31,7 @@
/**
* @author kimchy (shay.banon)
*/
-public interface SearchHitPhase {
+public interface FetchSubPhase {
public static class HitContext {
private InternalSearchHit hit;
@@ -66,10 +65,14 @@ public Document doc() {
Map<String, ? extends SearchParseElement> parseElements();
- boolean executionNeeded(SearchContext context);
+ boolean hitExecutionNeeded(SearchContext context);
/**
* Executes the hit level phase, with a reader and doc id (note, its a low level reader, and the matching doc).
*/
- void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException;
+ void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException;
+
+ boolean hitsExecutionNeeded(SearchContext context);
+
+ void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException;
}
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainSearchHitPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainFetchSubPhase.java
similarity index 75%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainSearchHitPhase.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainFetchSubPhase.java
index 0c51cd4c09396..396e10c7354d1 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainSearchHitPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/explain/ExplainFetchSubPhase.java
@@ -23,7 +23,8 @@
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchPhaseExecutionException;
-import org.elasticsearch.search.fetch.SearchHitPhase;
+import org.elasticsearch.search.fetch.FetchSubPhase;
+import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
@@ -32,17 +33,24 @@
/**
* @author kimchy (shay.banon)
*/
-public class ExplainSearchHitPhase implements SearchHitPhase {
+public class ExplainFetchSubPhase implements FetchSubPhase {
@Override public Map<String, ? extends SearchParseElement> parseElements() {
return ImmutableMap.of("explain", new ExplainParseElement());
}
- @Override public boolean executionNeeded(SearchContext context) {
+ @Override public boolean hitsExecutionNeeded(SearchContext context) {
+ return false;
+ }
+
+ @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException {
+ }
+
+ @Override public boolean hitExecutionNeeded(SearchContext context) {
return context.explain();
}
- @Override public void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
+ @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
try {
// we use the top level doc id, since we work with the top level searcher
hitContext.hit().explanation(context.searcher().explain(context.query(), hitContext.hit().docId()));
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersSearchHitPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersFetchSubPhase.java
similarity index 82%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersSearchHitPhase.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersFetchSubPhase.java
index 79322cde8e4ca..452337809c47f 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersSearchHitPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/matchedfilters/MatchedFiltersFetchSubPhase.java
@@ -19,7 +19,6 @@
package org.elasticsearch.search.fetch.matchedfilters;
-import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.elasticsearch.ElasticSearchException;
@@ -27,9 +26,8 @@
import org.elasticsearch.common.collect.Lists;
import org.elasticsearch.common.lucene.docset.DocSet;
import org.elasticsearch.common.lucene.docset.DocSets;
-import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.search.SearchParseElement;
-import org.elasticsearch.search.fetch.SearchHitPhase;
+import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;
@@ -40,17 +38,24 @@
/**
* @author kimchy (shay.banon)
*/
-public class MatchedFiltersSearchHitPhase implements SearchHitPhase {
+public class MatchedFiltersFetchSubPhase implements FetchSubPhase {
@Override public Map<String, ? extends SearchParseElement> parseElements() {
return ImmutableMap.of();
}
- @Override public boolean executionNeeded(SearchContext context) {
+ @Override public boolean hitsExecutionNeeded(SearchContext context) {
+ return false;
+ }
+
+ @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException {
+ }
+
+ @Override public boolean hitExecutionNeeded(SearchContext context) {
return !context.parsedQuery().namedFilters().isEmpty();
}
- @Override public void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
+ @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
List<String> matchedFilters = Lists.newArrayListWithCapacity(2);
for (Map.Entry<String, Filter> entry : context.parsedQuery().namedFilters().entrySet()) {
String name = entry.getKey();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsSearchHitPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsFetchSubPhase.java
similarity index 81%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsSearchHitPhase.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsFetchSubPhase.java
index 97945828a5809..7ca09ed4fd977 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsSearchHitPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/script/ScriptFieldsFetchSubPhase.java
@@ -24,7 +24,8 @@
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchParseElement;
-import org.elasticsearch.search.fetch.SearchHitPhase;
+import org.elasticsearch.search.fetch.FetchSubPhase;
+import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.InternalSearchHitField;
import org.elasticsearch.search.internal.SearchContext;
@@ -35,9 +36,9 @@
/**
* @author kimchy (shay.banon)
*/
-public class ScriptFieldsSearchHitPhase implements SearchHitPhase {
+public class ScriptFieldsFetchSubPhase implements FetchSubPhase {
- @Inject public ScriptFieldsSearchHitPhase() {
+ @Inject public ScriptFieldsFetchSubPhase() {
}
@Override public Map<String, ? extends SearchParseElement> parseElements() {
@@ -47,11 +48,18 @@ public class ScriptFieldsSearchHitPhase implements SearchHitPhase {
return parseElements.build();
}
- @Override public boolean executionNeeded(SearchContext context) {
+ @Override public boolean hitsExecutionNeeded(SearchContext context) {
+ return false;
+ }
+
+ @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException {
+ }
+
+ @Override public boolean hitExecutionNeeded(SearchContext context) {
return context.hasScriptFields();
}
- @Override public void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
+ @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
for (ScriptFieldsContext.ScriptField scriptField : context.scriptFields().fields()) {
scriptField.script().setNextReader(hitContext.reader());
scriptField.script().setNextDocId(hitContext.docId());
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionSearchHitPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionFetchSubPhase.java
similarity index 76%
rename from modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionSearchHitPhase.java
rename to modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionFetchSubPhase.java
index c44f1f02ce111..bbb42ca4d33f0 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionSearchHitPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/fetch/version/VersionFetchSubPhase.java
@@ -24,7 +24,8 @@
import org.elasticsearch.common.lucene.uid.UidField;
import org.elasticsearch.index.mapper.internal.UidFieldMapper;
import org.elasticsearch.search.SearchParseElement;
-import org.elasticsearch.search.fetch.SearchHitPhase;
+import org.elasticsearch.search.fetch.FetchSubPhase;
+import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;
import java.util.Map;
@@ -32,17 +33,24 @@
/**
* @author kimchy (shay.banon)
*/
-public class VersionSearchHitPhase implements SearchHitPhase {
+public class VersionFetchSubPhase implements FetchSubPhase {
@Override public Map<String, ? extends SearchParseElement> parseElements() {
return ImmutableMap.of("version", new VersionParseElement());
}
- @Override public boolean executionNeeded(SearchContext context) {
+ @Override public boolean hitsExecutionNeeded(SearchContext context) {
+ return false;
+ }
+
+ @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException {
+ }
+
+ @Override public boolean hitExecutionNeeded(SearchContext context) {
return context.version();
}
- @Override public void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
+ @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
// it might make sense to cache the TermDocs on a shared fetch context and just skip here)
// it is going to mean we work on the high level multi reader and not the lower level reader as is
// the case below...
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlightPhase.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlightPhase.java
index 34a7d357aa6d6..b4c54da436779 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlightPhase.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/highlight/HighlightPhase.java
@@ -40,9 +40,10 @@
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchPhaseExecutionException;
-import org.elasticsearch.search.fetch.SearchHitPhase;
+import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.highlight.vectorhighlight.SourceScoreOrderFragmentsBuilder;
import org.elasticsearch.search.highlight.vectorhighlight.SourceSimpleFragmentsBuilder;
+import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.lookup.SearchLookup;
@@ -58,7 +59,7 @@
/**
* @author kimchy (shay.banon)
*/
-public class HighlightPhase implements SearchHitPhase {
+public class HighlightPhase implements FetchSubPhase {
public static class Encoders {
public static Encoder DEFAULT = new DefaultEncoder();
@@ -69,11 +70,18 @@ public static class Encoders {
return ImmutableMap.of("highlight", new HighlighterParseElement());
}
- @Override public boolean executionNeeded(SearchContext context) {
+ @Override public boolean hitsExecutionNeeded(SearchContext context) {
+ return false;
+ }
+
+ @Override public void hitsExecute(SearchContext context, InternalSearchHit[] hits) throws ElasticSearchException {
+ }
+
+ @Override public boolean hitExecutionNeeded(SearchContext context) {
return context.highlight() != null;
}
- @Override public void execute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
+ @Override public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticSearchException {
try {
DocumentMapper documentMapper = context.mapperService().documentMapper(hitContext.hit().type());
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/internal/InternalSearchHit.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/internal/InternalSearchHit.java
index aae46cbf440df..33b763d964918 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/internal/InternalSearchHit.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/internal/InternalSearchHit.java
@@ -69,7 +69,7 @@ public class InternalSearchHit implements SearchHit {
private Map<String, SearchHitField> fields = ImmutableMap.of();
- private Map<String, HighlightField> highlightFields = ImmutableMap.of();
+ private Map<String, HighlightField> highlightFields = null;
private Object[] sortValues = EMPTY_SORT_VALUES;
@@ -230,7 +230,14 @@ public void fields(Map<String, SearchHitField> fields) {
this.fields = fields;
}
+ public Map<String, HighlightField> internalHighlightFields() {
+ return highlightFields;
+ }
+
@Override public Map<String, HighlightField> highlightFields() {
+ if (highlightFields == null) {
+ return ImmutableMap.of();
+ }
return this.highlightFields;
}
|
52bd53f5ea5eec84818d65b40e81d0a82ada6ba8
|
ReactiveX-RxJava
|
Restructure into smaller files--
|
p
|
https://github.com/ReactiveX/RxJava
|
diff --git a/.classpath b/.classpath
deleted file mode 100644
index b1ae8bae1c..0000000000
--- a/.classpath
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry exported="true" kind="con" path="GROOVY_DSL_SUPPORT"/>
- <classpathentry kind="con" path="GROOVY_SUPPORT"/>
- <classpathentry exported="true" kind="con" path="com.springsource.sts.gradle.classpathcontainer"/>
- <classpathentry kind="con" path="com.springsource.sts.gradle.dsld.classpathcontainer"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/.gitignore b/.gitignore
index 618e741f86..313af3cb82 100644
--- a/.gitignore
+++ b/.gitignore
@@ -38,3 +38,26 @@ Thumbs.db
# Gradle Files #
################
.gradle
+
+# Build output directies
+/target
+*/target
+/build
+*/build
+#
+# # IntelliJ specific files/directories
+out
+.idea
+*.ipr
+*.iws
+*.iml
+atlassian-ide-plugin.xml
+
+# Eclipse specific files/directories
+.classpath
+.project
+.settings
+.metadata
+
+# NetBeans specific files/directories
+.nbattrs
diff --git a/.project b/.project
deleted file mode 100644
index f2d845e45a..0000000000
--- a/.project
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>gradle-template</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>com.springsource.sts.gradle.core.nature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- <nature>org.eclipse.jdt.groovy.core.groovyNature</nature>
- </natures>
- <filteredResources>
- <filter>
- <id>1332049227118</id>
- <name></name>
- <type>10</type>
- <matcher>
- <id>org.eclipse.ui.ide.orFilterMatcher</id>
- <arguments>
- <matcher>
- <id>org.eclipse.ui.ide.multiFilter</id>
- <arguments>1.0-projectRelativePath-equals-true-false-template-server</arguments>
- </matcher>
- <matcher>
- <id>org.eclipse.ui.ide.multiFilter</id>
- <arguments>1.0-projectRelativePath-equals-true-false-template-client</arguments>
- </matcher>
- </arguments>
- </matcher>
- </filter>
- </filteredResources>
-</projectDescription>
diff --git a/.settings/gradle/com.springsource.sts.gradle.core.import.prefs b/.settings/gradle/com.springsource.sts.gradle.core.import.prefs
deleted file mode 100644
index e86c91081f..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.core.import.prefs
+++ /dev/null
@@ -1,9 +0,0 @@
-#com.springsource.sts.gradle.core.preferences.GradleImportPreferences
-#Sat Mar 17 22:40:13 PDT 2012
-enableAfterTasks=true
-afterTasks=afterEclipseImport;
-enableDependendencyManagement=true
-enableBeforeTasks=true
-projects=;template-client;template-server;
-enableDSLD=true
-beforeTasks=cleanEclipse;eclipse;
diff --git a/.settings/gradle/com.springsource.sts.gradle.core.prefs b/.settings/gradle/com.springsource.sts.gradle.core.prefs
deleted file mode 100644
index 445ff6da6f..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-#com.springsource.sts.gradle.core.preferences.GradleProjectPreferences
-#Sat Mar 17 22:40:29 PDT 2012
-com.springsource.sts.gradle.rootprojectloc=
-com.springsource.sts.gradle.linkedresources=
diff --git a/.settings/gradle/com.springsource.sts.gradle.refresh.prefs b/.settings/gradle/com.springsource.sts.gradle.refresh.prefs
deleted file mode 100644
index 01e59693e7..0000000000
--- a/.settings/gradle/com.springsource.sts.gradle.refresh.prefs
+++ /dev/null
@@ -1,9 +0,0 @@
-#com.springsource.sts.gradle.core.actions.GradleRefreshPreferences
-#Sat Mar 17 22:40:27 PDT 2012
-enableAfterTasks=true
-afterTasks=afterEclipseImport;
-useHierarchicalNames=false
-enableBeforeTasks=true
-addResourceFilters=true
-enableDSLD=true
-beforeTasks=cleanEclipse;eclipse;
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000000..7f8ced0d1f
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2012 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.
diff --git a/build.gradle b/build.gradle
index 5297034a51..9eef3329e1 100644
--- a/build.gradle
+++ b/build.gradle
@@ -5,18 +5,16 @@ ext.githubProjectName = rootProject.name // TEMPLATE: change to match github pro
apply from: file('gradle/convention.gradle')
apply from: file('gradle/maven.gradle')
apply from: file('gradle/check.gradle')
+apply from: file('gradle/license.gradle')
-subprojects
-{
- group = 'com.netflix'
+subprojects {
+ group = 'com.netflix.osstemplate' // TEMPLATE: Set to organization of project
- repositories
- {
+ repositories {
mavenCentral()
}
- dependencies
- {
+ dependencies {
compile 'javax.ws.rs:jsr311-api:1.1.1'
compile 'com.sun.jersey:jersey-core:1.11'
testCompile 'org.testng:testng:6.1.1'
@@ -24,21 +22,17 @@ subprojects
}
}
-project(':template-client')
-{
- dependencies
- {
+project(':template-client') {
+ dependencies {
compile 'org.slf4j:slf4j-api:1.6.3'
compile 'com.sun.jersey:jersey-client:1.11'
}
}
-project(':template-server')
-{
+project(':template-server') {
apply plugin: 'war'
apply plugin: 'jetty'
- dependencies
- {
+ dependencies {
compile 'com.sun.jersey:jersey-server:1.11'
compile 'com.sun.jersey:jersey-servlet:1.11'
compile project(':template-client')
diff --git a/codequality/HEADER b/codequality/HEADER
new file mode 100644
index 0000000000..b27b192925
--- /dev/null
+++ b/codequality/HEADER
@@ -0,0 +1,13 @@
+ Copyright 2012 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.
diff --git a/codequality/checkstyle.xml b/codequality/checkstyle.xml
index 3c8a8e6c75..481d2829fd 100644
--- a/codequality/checkstyle.xml
+++ b/codequality/checkstyle.xml
@@ -50,6 +50,7 @@
<property name="allowMissingReturnTag" value="true"/>
<property name="allowThrowsTagsForSubclasses" value="true"/>
<property name="allowUndeclaredRTE" value="true"/>
+ <property name="allowMissingPropertyJavadoc" value="true"/>
</module>
<module name="JavadocType">
<property name="scope" value="package"/>
diff --git a/gradle/check.gradle b/gradle/check.gradle
index cf6f0461ae..0f80516d45 100644
--- a/gradle/check.gradle
+++ b/gradle/check.gradle
@@ -9,8 +9,10 @@ subprojects {
// FindBugs
apply plugin: 'findbugs'
+ //tasks.withType(Findbugs) { reports.html.enabled true }
// PMD
apply plugin: 'pmd'
+ //tasks.withType(Pmd) { reports.html.enabled true }
}
diff --git a/gradle/license.gradle b/gradle/license.gradle
new file mode 100644
index 0000000000..9d04830321
--- /dev/null
+++ b/gradle/license.gradle
@@ -0,0 +1,5 @@
+buildscript {
+ dependencies { classpath 'nl.javadude.gradle.plugins:license-gradle-plugin:0.4' }
+}
+
+apply plugin: 'license'
\ No newline at end of file
diff --git a/gradle/local.gradle b/gradle/local.gradle
new file mode 100644
index 0000000000..6f2d204b8a
--- /dev/null
+++ b/gradle/local.gradle
@@ -0,0 +1 @@
+apply from: 'file://Users/jryan/Workspaces/jryan_build/Tools/nebula-boot/artifactory.gradle'
diff --git a/gradle/maven.gradle b/gradle/maven.gradle
index 8639564ce4..cb75dfb637 100644
--- a/gradle/maven.gradle
+++ b/gradle/maven.gradle
@@ -4,7 +4,7 @@ subprojects {
apply plugin: 'signing'
signing {
- required rootProject.performingRelease
+ required { performingRelease && gradle.taskGraph.hasTask("uploadMavenCentral")}
sign configurations.archives
}
diff --git a/template-client/bin/com/netflix/template/client/TalkClient.class b/template-client/bin/com/netflix/template/client/TalkClient.class
deleted file mode 100644
index 90bbaeb353..0000000000
Binary files a/template-client/bin/com/netflix/template/client/TalkClient.class and /dev/null differ
diff --git a/template-client/bin/com/netflix/template/common/Sentence.class b/template-client/bin/com/netflix/template/common/Sentence.class
deleted file mode 100644
index 0083f33477..0000000000
Binary files a/template-client/bin/com/netflix/template/common/Sentence.class and /dev/null differ
diff --git a/template-client/src/main/java/com/netflix/template/client/TalkClient.java b/template-client/src/main/java/com/netflix/template/client/TalkClient.java
index c3ebf86090..fc9d20d33d 100644
--- a/template-client/src/main/java/com/netflix/template/client/TalkClient.java
+++ b/template-client/src/main/java/com/netflix/template/client/TalkClient.java
@@ -8,26 +8,42 @@
import javax.ws.rs.core.MediaType;
+/**
+ * Delegates to remote TalkServer over REST.
+ * @author jryan
+ *
+ */
public class TalkClient implements Conversation {
- WebResource webResource;
+ private WebResource webResource;
- TalkClient(String location) {
+ /**
+ * Instantiate client.
+ *
+ * @param location URL to the base of resources, e.g. http://localhost:8080/template-server/rest
+ */
+ public TalkClient(String location) {
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
webResource = client.resource(location + "/talk");
}
+ @Override
public Sentence greeting() {
Sentence s = webResource.accept(MediaType.APPLICATION_XML).get(Sentence.class);
return s;
}
+ @Override
public Sentence farewell() {
Sentence s = webResource.accept(MediaType.APPLICATION_XML).delete(Sentence.class);
return s;
}
+ /**
+ * Tests out client.
+ * @param args Not applicable
+ */
public static void main(String[] args) {
TalkClient remote = new TalkClient("http://localhost:8080/template-server/rest");
System.out.println(remote.greeting().getWhole());
diff --git a/template-client/src/main/java/com/netflix/template/common/Conversation.java b/template-client/src/main/java/com/netflix/template/common/Conversation.java
index b85e23e98b..c190f03bb7 100644
--- a/template-client/src/main/java/com/netflix/template/common/Conversation.java
+++ b/template-client/src/main/java/com/netflix/template/common/Conversation.java
@@ -1,6 +1,21 @@
package com.netflix.template.common;
+/**
+ * Hold a conversation.
+ * @author jryan
+ *
+ */
public interface Conversation {
+
+ /**
+ * Initiates a conversation.
+ * @return Sentence words from geeting
+ */
Sentence greeting();
+
+ /**
+ * End the conversation.
+ * @return
+ */
Sentence farewell();
-}
\ No newline at end of file
+}
diff --git a/template-client/src/main/java/com/netflix/template/common/Sentence.java b/template-client/src/main/java/com/netflix/template/common/Sentence.java
index bf561a6d5a..616f72efb0 100644
--- a/template-client/src/main/java/com/netflix/template/common/Sentence.java
+++ b/template-client/src/main/java/com/netflix/template/common/Sentence.java
@@ -3,17 +3,31 @@
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
+/**
+ * Container for words going back and forth.
+ * @author jryan
+ *
+ */
@XmlRootElement
public class Sentence {
private String whole;
+ @SuppressWarnings("unused")
private Sentence() {
};
+ /**
+ * Initialize sentence.
+ * @param whole
+ */
public Sentence(String whole) {
this.whole = whole;
}
+ /**
+ * whole getter.
+ * @return
+ */
@XmlElement
public String getWhole() {
return whole;
@@ -22,4 +36,4 @@ public String getWhole() {
public void setWhole(String whole) {
this.whole = whole;
}
-}
\ No newline at end of file
+}
|
056a7494cc2a60370608f44e261cd9da75dfde3b
|
Valadoc
|
libvaladoc: accept "Vala ??.??.??-dirty" as driver format
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/moduleloader.vala b/src/libvaladoc/moduleloader.vala
index 903367084f..1571d51ebd 100644
--- a/src/libvaladoc/moduleloader.vala
+++ b/src/libvaladoc/moduleloader.vala
@@ -118,9 +118,13 @@ public class Valadoc.ModuleLoader : Object {
}
- // selected string is a version number:
+ // selected string is a `valac --version` number:
if (driverpath.has_prefix ("Vala ")) {
- driverpath = driverpath.substring (5);
+ if (driverpath.has_suffix ("-dirty")) {
+ driverpath = driverpath.substring (5, driverpath.length - 6 - 5);
+ } else {
+ driverpath = driverpath.substring (5);
+ }
}
string[] segments = driverpath.split (".");
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala
index d833883d46..6bc51e64ee 100644
--- a/src/libvaladoc/taglets/tagletthrows.vala
+++ b/src/libvaladoc/taglets/tagletthrows.vala
@@ -49,7 +49,7 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block {
error_domain = api_root.search_symbol_str (container, error_domain_name);
if (error_domain == null) {
// TODO use ContentElement's source reference
- reporter.simple_error ("%s: %s: @throws: warning: %s does not exist", file_path, container.get_full_name (), error_domain_name);
+ reporter.simple_error ("%s: %s: @throws: error: %s does not exist", file_path, container.get_full_name (), error_domain_name);
base.check (api_root, container, file_path, reporter, settings);
return ;
}
|
96d1fe8096874e6d5b7a0ad85e918756b5cf046a
|
intellij-community
|
annotation default value parsing fixed--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java
index 13e6715851dc9..6af96063c0ff9 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/declaration/VariableDefinitions.java
@@ -100,11 +100,11 @@ public static GroovyElementType parseDefinitions(PsiBuilder builder,
ParserUtils.getToken(builder, GroovyTokenTypes.kDEFAULT);
ParserUtils.getToken(builder, GroovyTokenTypes.mNLS);
- if (AnnotationArguments.parseAnnotationMemberValueInitializer(builder)) {
- defaultValueMarker.done(DEFAULT_ANNOTATION_VALUE);
- } else {
- defaultValueMarker.error(GroovyBundle.message("annotation.initializer.expected"));
+ if (!AnnotationArguments.parseAnnotationMemberValueInitializer(builder)) {
+ builder.error(GroovyBundle.message("annotation.initializer.expected"));
}
+
+ defaultValueMarker.done(DEFAULT_ANNOTATION_VALUE);
return DEFAULT_ANNOTATION_MEMBER;
}
|
69438cc0d3444c064f3555ef465176ef5c28f69e
|
orientdb
|
Fixed issue on missed saving of the configuration- when Local Data has multiple files. Reported by Ed Barbeau:- http://groups.google.com/group/orient-database/msg/0299391834b65b73--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OStorageConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OStorageConfiguration.java
index 2c004364862..6b0b13cd8a2 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OStorageConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OStorageConfiguration.java
@@ -23,6 +23,7 @@
import java.util.List;
import java.util.Locale;
+import com.orientechnologies.orient.core.exception.OConfigurationException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.impl.ORecordBytes;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
@@ -55,6 +56,8 @@ public class OStorageConfiguration implements OSerializableStream {
private transient OStorage storage;
private transient byte[] record;
+ private static final int FIXED_CONFIG_SIZE = 20000;
+
public OStorageConfiguration load() throws IOException {
record = storage.readRecord(-1, storage.getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME), CONFIG_RECORD_NUM).buffer;
fromStream(record);
@@ -136,7 +139,7 @@ public OSerializableStream fromStream(byte[] iStream) throws IOException {
clusterType = read(values[index++]);
// PHYSICAL CLUSTER
if (clusterType.equals("p")) {
- phyCluster = new OStoragePhysicalClusterConfiguration(i);
+ phyCluster = new OStoragePhysicalClusterConfiguration(this, i);
index = phySegmentFromStream(values, index, phyCluster);
phyCluster.holeFile = new OStorageClusterHoleConfiguration(phyCluster, read(values[index++]), read(values[index++]),
read(values[index++]));
@@ -153,7 +156,7 @@ public OSerializableStream fromStream(byte[] iStream) throws IOException {
dataSegments = new ArrayList<OStorageDataConfiguration>(size);
OStorageDataConfiguration data;
for (int i = 0; i < size; ++i) {
- data = new OStorageDataConfiguration();
+ data = new OStorageDataConfiguration(this);
index = phySegmentFromStream(values, index, data);
data.holeFile = new OStorageDataHoleConfiguration(data, read(values[index++]), read(values[index++]), read(values[index++]));
dataSegments.add(data);
@@ -211,6 +214,13 @@ public byte[] toStream() throws IOException {
for (OEntryConfiguration e : properties)
entryToStream(buffer, e);
+ if (buffer.length() > FIXED_CONFIG_SIZE)
+ throw new OConfigurationException("Configuration data exceeded size limit: " + FIXED_CONFIG_SIZE + " bytes");
+
+ // ALLOCATE ENOUGHT SPACE TO REUSE IT EVERY TIME
+ buffer.append("|");
+ buffer.setLength(FIXED_CONFIG_SIZE);
+
return buffer.toString().getBytes();
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OStorageDataConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OStorageDataConfiguration.java
index 3e411c1f253..280cafd0895 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OStorageDataConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OStorageDataConfiguration.java
@@ -22,7 +22,8 @@ public class OStorageDataConfiguration extends OStorageSegmentConfiguration {
private static final String START_SIZE = "10Mb";
private static final String INCREMENT_SIZE = "100%";
- public OStorageDataConfiguration() {
+ public OStorageDataConfiguration(final OStorageConfiguration iStorageConfiguration) {
+ root = iStorageConfiguration;
fileStartSize = START_SIZE;
fileIncrementSize = INCREMENT_SIZE;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OStoragePhysicalClusterConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OStoragePhysicalClusterConfiguration.java
index 3ee268b90db..52fb3eafb03 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/config/OStoragePhysicalClusterConfiguration.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/config/OStoragePhysicalClusterConfiguration.java
@@ -22,7 +22,8 @@ public class OStoragePhysicalClusterConfiguration extends OStorageSegmentConfigu
private static final String START_SIZE = "1Mb";
- public OStoragePhysicalClusterConfiguration(final int iId) {
+ public OStoragePhysicalClusterConfiguration(final OStorageConfiguration iStorageConfiguration, final int iId) {
+ root = iStorageConfiguration;
fileStartSize = START_SIZE;
id = iId;
}
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OMultiFileSegment.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OMultiFileSegment.java
index 72a405972d3..8e34ec57e6c 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OMultiFileSegment.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OMultiFileSegment.java
@@ -27,15 +27,15 @@
import com.orientechnologies.orient.core.storage.fs.OFileFactory;
public class OMultiFileSegment extends OSegment {
- protected OFile[] files = new OFile[0];
- private String fileExtension;
- private String type;
- private long maxSize;
- private String defrag;
- private int fileStartSize;
- private int fileMaxSize;
- private int fileIncrementSize;
- private OStorageSegmentConfiguration config;
+ protected OStorageSegmentConfiguration config;
+ protected OFile[] files = new OFile[0];
+ private String fileExtension;
+ private String type;
+ private long maxSize;
+ private String defrag;
+ private int fileStartSize;
+ private int fileMaxSize;
+ private int fileIncrementSize;
public OMultiFileSegment(final OStorageLocal iStorage, final OStorageSegmentConfiguration iConfig, final String iFileExtension,
final int iRoundMaxSize) throws IOException {
@@ -206,6 +206,8 @@ protected int[] allocateSpace(final int iRecordSize) throws IOException {
file = createNewFile();
file.allocateSpace(iRecordSize);
+ config.root.update();
+
return new int[] { files.length - 1, 0 };
}
@@ -232,7 +234,7 @@ protected int[] getRelativePosition(final long iPosition) {
if (fileNum >= files.length)
throw new ODatabaseException("Record position #" + iPosition + " was bound to file #" + fileNum
- + " that is out if limit (current=" + files.length + ")");
+ + " that is out of limit (current=" + (files.length - 1) + ")");
final int fileRec = (int) (iPosition % fileMaxSize);
@@ -257,7 +259,7 @@ private OFile createNewFile() throws IOException {
return file;
}
- private void addInfoFileConfigEntry(final OFile file) {
+ private void addInfoFileConfigEntry(final OFile file) throws IOException {
OStorageFileConfiguration[] newConfigFiles = new OStorageFileConfiguration[config.infoFiles.length + 1];
for (int i = 0; i < config.infoFiles.length; ++i)
newConfigFiles[i] = config.infoFiles[i];
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
index a8cbd078607..e90d87db627 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java
@@ -35,6 +35,7 @@
import com.orientechnologies.orient.core.config.OStorageDataConfiguration;
import com.orientechnologies.orient.core.config.OStorageLogicalClusterConfiguration;
import com.orientechnologies.orient.core.config.OStoragePhysicalClusterConfiguration;
+import com.orientechnologies.orient.core.config.OStorageSegmentConfiguration;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
@@ -631,8 +632,11 @@ protected int registerDataSegment(final OStorageDataConfiguration iConfig) throw
// CHECK FOR DUPLICATION OF NAMES
for (ODataLocal data : dataSegments)
- if (data.getName().equals(iConfig.name))
+ if (data.getName().equals(iConfig.name)) {
+ // OVERWRITE CONFIG
+ data.config = iConfig;
return -1;
+ }
pos = dataSegments.length;
// CREATE AND ADD THE NEW REF SEGMENT
@@ -654,9 +658,11 @@ protected int registerDataSegment(final OStorageDataConfiguration iConfig) throw
* @throws IOException
*/
private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException {
- if (clusterMap.containsKey(iConfig.getName()))
- // ALREADY CONFIGURED
+ if (clusterMap.containsKey(iConfig.getName())) {
+ // ALREADY CONFIGURED, JUST OVERWRITE CONFIG
+ ((OClusterLocal) clusterMap.get(iConfig.getName())).config = (OStorageSegmentConfiguration) iConfig;
return -1;
+ }
final OCluster cluster;
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java
index 0f0e8354cf5..258c216dff5 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java
@@ -41,20 +41,7 @@ public SQLSynchQuerySpeedTest(String iURL) {
public void cycle() throws UnsupportedEncodingException {
System.out.println("1 ----------------------");
List<ODocument> result = database.command(
- new OSQLSynchQuery<ODocument>("select * from animal where id = 10 and name like 'G%'")).execute();
-
- OrientTest.printRecords(result);
-
- System.out.println("2 ----------------------");
- result = database.command(
- new OSQLSynchQuery<ODocument>("select * from animal where column(0) < 5 or column(0) >= 3 and column(5) < 7")).execute();
-
- OrientTest.printRecords(result);
-
- /*
- * System.out.println("3 ----------------------"); printResults((List<String>) database.query(new OSQLSynchQuery<String>(
- * "select * from animal where column(0) < 5 and column(0) >= 3 or column(0) < 7"), 1000));
- */
+ new OSQLSynchQuery<ODocument>("select * from Account where id = 10 and name like 'G%'")).execute();
}
public boolean result(final Object iRecord) {
|
527370f8c142d373c4543d0eb26cb2f0912ed9f0
|
camel
|
CAMEL-1320: Created gzip data format--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@756039 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java b/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
index e2eba66852b99..24892a459aa40 100644
--- a/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
+++ b/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
@@ -18,13 +18,12 @@
import java.util.zip.Deflater;
-import org.w3c.dom.Node;
-
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.dataformat.ArtixDSContentType;
import org.apache.camel.model.dataformat.ArtixDSDataFormat;
import org.apache.camel.model.dataformat.CsvDataFormat;
import org.apache.camel.model.dataformat.DataFormatDefinition;
+import org.apache.camel.model.dataformat.GzipDataFormat;
import org.apache.camel.model.dataformat.HL7DataFormat;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.model.dataformat.JsonDataFormat;
@@ -36,6 +35,7 @@
import org.apache.camel.model.dataformat.XMLSecurityDataFormat;
import org.apache.camel.model.dataformat.XStreamDataFormat;
import org.apache.camel.model.dataformat.ZipDataFormat;
+import org.w3c.dom.Node;
/**
* An expression for constructing the different possible {@link org.apache.camel.spi.DataFormat}
@@ -242,6 +242,14 @@ public T zip(int compressionLevel) {
ZipDataFormat zdf = new ZipDataFormat(compressionLevel);
return dataFormat(zdf);
}
+
+ /**
+ * Uses the GZIP deflater data format
+ */
+ public T gzip() {
+ GzipDataFormat gzdf = new GzipDataFormat();
+ return dataFormat(gzdf);
+ }
@SuppressWarnings("unchecked")
private T dataFormat(DataFormatDefinition dataFormatType) {
diff --git a/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java b/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java
new file mode 100644
index 0000000000000..57cc53e148529
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/impl/GzipDataFormat.java
@@ -0,0 +1,59 @@
+/**
+ * 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.impl;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.spi.DataFormat;
+import org.apache.camel.util.ExchangeHelper;
+import org.apache.camel.util.IOHelper;
+
+public class GzipDataFormat implements DataFormat {
+
+ public void marshal(Exchange exchange, Object graph, OutputStream stream)
+ throws Exception {
+ InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, graph);
+ if (is == null) {
+ throw new IllegalArgumentException("Cannot get the inputstream for GzipDataFormat mashalling");
+ }
+
+ GZIPOutputStream zipOutput = new GZIPOutputStream(stream);
+ try {
+ IOHelper.copy(is, zipOutput);
+ } finally {
+ zipOutput.close();
+ }
+
+ }
+
+ public Object unmarshal(Exchange exchange, InputStream stream)
+ throws Exception {
+ InputStream is = ExchangeHelper.getMandatoryInBody(exchange, InputStream.class);
+ GZIPInputStream unzipInput = new GZIPInputStream(is);
+
+ // Create an expandable byte array to hold the inflated data
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ IOHelper.copy(unzipInput, bos);
+ return bos.toByteArray();
+ }
+
+}
diff --git a/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java b/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java
new file mode 100644
index 0000000000000..864c347a9eac4
--- /dev/null
+++ b/camel-core/src/main/java/org/apache/camel/model/dataformat/GzipDataFormat.java
@@ -0,0 +1,35 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.model.dataformat;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.camel.spi.DataFormat;
+import org.apache.camel.spi.RouteContext;
+
+/**
+ * Represents the GZip {@link DataFormat}
+ *
+ * @version $Revision: 750806 $
+ */
+@XmlRootElement(name = "gzip")
+public class GzipDataFormat extends DataFormatDefinition {
+ @Override
+ protected DataFormat createDataFormat(RouteContext routeContext) {
+ return new org.apache.camel.impl.GzipDataFormat();
+ }
+}
diff --git a/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java b/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java
new file mode 100644
index 0000000000000..16b1b8393669e
--- /dev/null
+++ b/camel-core/src/test/java/org/apache/camel/impl/GzipDataFormatTest.java
@@ -0,0 +1,75 @@
+/**
+ * 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.impl;
+
+import java.io.ByteArrayInputStream;
+import java.util.zip.GZIPInputStream;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.IOConverter;
+
+/**
+ * Unit test of the gzip data format.
+ */
+public class GzipDataFormatTest extends ContextTestSupport {
+ private static final String TEXT = "Hamlet by William Shakespeare\n" +
+ "To be, or not to be: that is the question:\n" +
+ "Whether 'tis nobler in the mind to suffer\n" +
+ "The slings and arrows of outrageous fortune,\n" +
+ "Or to take arms against a sea of troubles,\n" +
+ "And by opposing end them? To die: to sleep;";;
+
+ @Override
+ public boolean isUseRouteBuilder() {
+ return false;
+ }
+
+ private byte[] sendText() throws Exception {
+ return (byte[]) template.sendBody("direct:start", TEXT.getBytes("UTF-8"));
+ }
+
+ public void testMarshalTextToGZip() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("direct:start").marshal().gzip();
+ }
+ });
+ context.start();
+
+ byte[] output = sendText();
+
+ GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(output));
+ String result = IOConverter.toString(stream);
+ assertEquals("Uncompressed something different than compressed", TEXT, result);
+ }
+
+ public void testUnMarshalTextToGzip() throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ public void configure() {
+ from("direct:start").marshal().gzip().unmarshal().gzip().to("mock:result");
+ }
+ });
+ context.start();
+
+ MockEndpoint result = (MockEndpoint)context.getEndpoint("mock:result");
+ result.expectedBodiesReceived(TEXT.getBytes("UTF-8"));
+ sendText();
+ result.assertIsSatisfied();
+ }
+}
|
a34a8ed3eeb5f8e95ee9b4432ece9d25ad266525
|
Delta Spike
|
DELTASPIKE-507 fallback to TransactionSynchronisationRegistry
txs to sstrobl for the patch
also big txs to dblevins for the hint to this hidden gem.
|
c
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
index 556b6d8a0..660bf0fc9 100644
--- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
+++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/transaction/BeanManagedUserTransactionStrategy.java
@@ -31,6 +31,7 @@
import javax.persistence.EntityTransaction;
import javax.transaction.Status;
import javax.transaction.SystemException;
+import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import java.lang.annotation.Annotation;
import java.util.logging.Level;
@@ -49,6 +50,7 @@
public class BeanManagedUserTransactionStrategy extends ResourceLocalTransactionStrategy
{
protected static final String USER_TRANSACTION_JNDI_NAME = "java:comp/UserTransaction";
+ protected static final String TRANSACTION_SYNC_REGISTRY_JNDI_NAME = "java:comp/TransactionSynchronizationRegistry";
private static final long serialVersionUID = -2432802805095533499L;
@@ -80,7 +82,17 @@ protected void applyTransactionTimeout()
try
{
UserTransaction userTransaction = resolveUserTransaction();
- userTransaction.setTransactionTimeout(transactionTimeout);
+
+ if (userTransaction == null)
+ {
+ // if there is a CMT EJB call active, then we do not set any timeout
+ return;
+ }
+
+ if (userTransaction.getStatus() != Status.STATUS_ACTIVE)
+ {
+ userTransaction.setTransactionTimeout(transactionTimeout);
+ }
}
catch (SystemException e)
{
@@ -153,7 +165,6 @@ protected EntityTransaction getTransaction(EntityManagerEntry entityManagerEntry
*
* @param entityManagerEntry entry of the current entity-manager
*/
-
@Override
protected void beforeProceed(EntityManagerEntry entityManagerEntry)
{
@@ -167,16 +178,40 @@ protected UserTransaction resolveUserTransaction()
return userTransaction;
}
- return JndiUtils.lookup(USER_TRANSACTION_JNDI_NAME, UserTransaction.class);
+ try
+ {
+ return JndiUtils.lookup(USER_TRANSACTION_JNDI_NAME, UserTransaction.class);
+ }
+ catch (Exception ne)
+ {
+ // do nothing it was just a try
+ return null;
+ }
+ }
+
+ protected TransactionSynchronizationRegistry resolveTransactionRegistry()
+ {
+ return JndiUtils.lookup(TRANSACTION_SYNC_REGISTRY_JNDI_NAME, TransactionSynchronizationRegistry.class);
}
private class UserTransactionAdapter implements EntityTransaction
{
private final UserTransaction userTransaction;
+ private TransactionSynchronizationRegistry transactionSynchronizationRegistry = null;
public UserTransactionAdapter()
{
this.userTransaction = resolveUserTransaction();
+
+ if (this.userTransaction == null)
+ {
+ transactionSynchronizationRegistry = resolveTransactionRegistry();
+
+ if (transactionSynchronizationRegistry.getTransactionStatus() != Status.STATUS_ACTIVE)
+ {
+ throw new RuntimeException("invalid state/badly configured JTA datasource");
+ }
+ }
}
/**
@@ -187,6 +222,12 @@ public UserTransactionAdapter()
@Override
public void begin()
{
+
+ if (this.userTransaction == null)
+ {
+ throw new IllegalStateException("cannot begin UserTransaction in CMT environment");
+ }
+
try
{
//2nd check (already done by #isActive triggered by ResourceLocalTransactionStrategy directly before)
@@ -214,6 +255,12 @@ public void begin()
@Override
public void commit()
{
+ if (this.userTransaction == null)
+ {
+ throw new IllegalStateException("cannot commit UserTransaction in CMT environment");
+ }
+
+
try
{
if (isTransactionReadyToCommit())
@@ -241,6 +288,11 @@ public void commit()
@Override
public void rollback()
{
+ if (this.userTransaction == null)
+ {
+ throw new IllegalStateException("cannot rollback UserTransaction in CMT environment");
+ }
+
try
{
if (isTransactionAllowedToRollback())
@@ -259,7 +311,15 @@ public void setRollbackOnly()
{
try
{
- this.userTransaction.setRollbackOnly();
+ if (this.userTransaction != null)
+ {
+ this.userTransaction.setRollbackOnly();
+ }
+ else
+ {
+ this.transactionSynchronizationRegistry.setRollbackOnly();
+ }
+
}
catch (SystemException e)
{
@@ -272,7 +332,7 @@ public boolean getRollbackOnly()
{
try
{
- return this.userTransaction.getStatus() == Status.STATUS_MARKED_ROLLBACK;
+ return this.getStatus() == Status.STATUS_MARKED_ROLLBACK;
}
catch (SystemException e)
{
@@ -289,8 +349,8 @@ public boolean isActive()
//we can't use the status of the overall
try
{
- return this.userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION &&
- this.userTransaction.getStatus() != Status.STATUS_UNKNOWN; //TODO re-visit it
+ return this.getStatus() != Status.STATUS_NO_TRANSACTION &&
+ this.getStatus() != Status.STATUS_UNKNOWN; //TODO re-visit it
}
catch (SystemException e)
{
@@ -302,16 +362,28 @@ protected boolean isTransactionAllowedToRollback() throws SystemException
{
//if the following gets changed, it needs to be tested with different constellations
//(normal exception, timeout,...) as well as servers
- return this.userTransaction.getStatus() != Status.STATUS_COMMITTED &&
- this.userTransaction.getStatus() != Status.STATUS_NO_TRANSACTION &&
- this.userTransaction.getStatus() != Status.STATUS_UNKNOWN;
+ return this.getStatus() != Status.STATUS_COMMITTED &&
+ this.getStatus() != Status.STATUS_NO_TRANSACTION &&
+ this.getStatus() != Status.STATUS_UNKNOWN;
}
protected boolean isTransactionReadyToCommit() throws SystemException
{
- return this.userTransaction.getStatus() == Status.STATUS_ACTIVE ||
- this.userTransaction.getStatus() == Status.STATUS_PREPARING ||
- this.userTransaction.getStatus() == Status.STATUS_PREPARED;
+ return this.getStatus() == Status.STATUS_ACTIVE ||
+ this.getStatus() == Status.STATUS_PREPARING ||
+ this.getStatus() == Status.STATUS_PREPARED;
+ }
+
+ protected int getStatus() throws SystemException
+ {
+ if (this.userTransaction != null)
+ {
+ return this.userTransaction.getStatus();
+ }
+ else
+ {
+ return this.transactionSynchronizationRegistry.getTransactionStatus();
+ }
}
}
}
|
72d9872fffa2b8f6d534612436b1613ed062e026
|
ReactiveX-RxJava
|
updated a test and added another one
|
a
|
https://github.com/ReactiveX/RxJava
|
diff --git a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
index 725d7781ae..53a11e0b24 100644
--- a/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
+++ b/rxjava-core/src/main/java/rx/operators/OperationCombineLatest.java
@@ -304,7 +304,7 @@ public void testCombineLatestDifferentLengthObservableSequences1() {
/* we should have been called 4 times on the Observer */
InOrder inOrder = inOrder(w);
- inOrder.verify(w).onNext("1a2a3a");
+ inOrder.verify(w).onNext("1a2b3a");
inOrder.verify(w).onNext("1a2b3b");
inOrder.verify(w).onNext("1a2b3c");
inOrder.verify(w).onNext("1a2b3d");
@@ -348,6 +348,45 @@ public void testCombineLatestDifferentLengthObservableSequences2() {
}
+ @SuppressWarnings("unchecked")
+ /* mock calls don't do generics */
+ @Test
+ public void testCombineLatestWithInterleavingSequences() {
+ Observer<String> w = mock(Observer.class);
+
+ TestObservable w1 = new TestObservable();
+ TestObservable w2 = new TestObservable();
+ TestObservable w3 = new TestObservable();
+
+ Observable<String> combineLatestW = Observable.create(combineLatest(w1, w2, w3, getConcat3StringsCombineLatestFunction()));
+ combineLatestW.subscribe(w);
+
+ /* simulate sending data */
+ w1.Observer.onNext("1a");
+ w2.Observer.onNext("2a");
+ w2.Observer.onNext("2b");
+ w3.Observer.onNext("3a");
+
+ w1.Observer.onNext("1b");
+ w2.Observer.onNext("2c");
+ w2.Observer.onNext("2d");
+ w3.Observer.onNext("3b");
+
+ w1.Observer.onCompleted();
+ w2.Observer.onCompleted();
+ w3.Observer.onCompleted();
+
+ /* we should have been called 5 times on the Observer */
+ InOrder inOrder = inOrder(w);
+ inOrder.verify(w).onNext("1a2b3a");
+ inOrder.verify(w).onNext("1b2b3a");
+ inOrder.verify(w).onNext("1b2c3a");
+ inOrder.verify(w).onNext("1b2d3a");
+ inOrder.verify(w).onNext("1b2d3b");
+
+ inOrder.verify(w, times(1)).onCompleted();
+ }
+
/**
* Testing internal private logic due to the complexity so I want to use TDD to test as a I build it rather than relying purely on the overall functionality expected by the public methods.
*/
|
c65e0bd91c6d4092efd7526a8021ab9b0f1e7b7c
|
drools
|
JBRULES-393 Xml dump with illegal characters -fixed- by Javier Prieto--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@5949 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/xml/XmlDumper.java b/drools-compiler/src/main/java/org/drools/xml/XmlDumper.java
index 428186c1ba4..87945759802 100644
--- a/drools-compiler/src/main/java/org/drools/xml/XmlDumper.java
+++ b/drools-compiler/src/main/java/org/drools/xml/XmlDumper.java
@@ -75,7 +75,7 @@ public void visitAttributeDescr(final AttributeDescr attributeDescr) {
public void visitVariableRestrictionDescr(final VariableRestrictionDescr descr) {
this.template = new String();
- this.template = "<variable-restriction evaluator=\"" + getEvaluator( descr.getEvaluator() ) + "\" identifier=\"" + descr.getIdentifier() + "\" />" + XmlDumper.eol;
+ this.template = "<variable-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" identifier=\"" + descr.getIdentifier() + "\" />" + XmlDumper.eol;
}
public void visitColumnDescr(final ColumnDescr descr) {
@@ -99,12 +99,12 @@ public void visitColumnDescr(final ColumnDescr descr) {
public void visitFieldConstraintDescr(final FieldConstraintDescr descr) {
if ( !descr.getRestrictions().isEmpty() ) {
processFieldConstraint( descr.getRestrictions() );
- }
- }
-
+ }
+ }
+
public void visitEvalDescr(final EvalDescr descr) {
this.template = new String();
- this.template = "<eval>" + descr.getText() + "</eval>" + XmlDumper.eol;
+ this.template = "<eval>" + replaceIllegalChars( descr.getText() ) + "</eval>" + XmlDumper.eol;
}
public void visitExistsDescr(final ExistsDescr descr) {
@@ -124,14 +124,15 @@ public void visitFieldBindingDescr(final FieldBindingDescr descr) {
public void visitFunctionDescr(final FunctionDescr functionDescr) {
this.template = new String();
final String parameterTemplate = processParameters( functionDescr.getParameterNames(),
- functionDescr.getParameterTypes() );
+ functionDescr.getParameterTypes() );
- this.template = "<function return-type=\"" + functionDescr.getReturnType() + "\" name=\"" + functionDescr.getName() + "\">" + XmlDumper.eol + parameterTemplate + "<body>" + XmlDumper.eol + functionDescr.getText() + XmlDumper.eol + "</body>" + XmlDumper.eol + "</function>" + XmlDumper.eol;
+ this.template = "<function return-type=\"" + functionDescr.getReturnType() + "\" name=\"" + functionDescr.getName() + "\">" + XmlDumper.eol + parameterTemplate + "<body>" + XmlDumper.eol + replaceIllegalChars( functionDescr.getText() ) + XmlDumper.eol + "</body>"
+ + XmlDumper.eol + "</function>" + XmlDumper.eol;
}
public void visitLiteralRestrictionDescr(final LiteralRestrictionDescr descr) {
this.template = new String();
- this.template = "<literal-restriction evaluator=\"" + getEvaluator( descr.getEvaluator() ) + "\" value=\"" + descr.getText() + "\" />" + XmlDumper.eol;
+ this.template = "<literal-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" value=\"" + replaceIllegalChars( descr.getText() ) + "\" />" + XmlDumper.eol;
}
public void visitNotDescr(final NotDescr descr) {
@@ -155,8 +156,8 @@ public void visitOrDescr(final OrDescr descr) {
public void visitPackageDescr(final PackageDescr packageDescr) {
final String packageName = packageDescr.getName();
- final String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + XmlDumper.eol + " <package name=\"" + packageName + "\" " + XmlDumper.eol + "\txmlns=\"http://drools.org/drools-3.0\" " + XmlDumper.eol + "\txmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\" " + XmlDumper.eol
- + "\txs:schemaLocation=\"http://drools.org/drools-3.0 drools-3.0.xsd\"> " + XmlDumper.eol;
+ final String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + XmlDumper.eol + " <package name=\"" + packageName + "\" " + XmlDumper.eol + "\txmlns=\"http://drools.org/drools-3.0\" " + XmlDumper.eol
+ + "\txmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\" " + XmlDumper.eol + "\txs:schemaLocation=\"http://drools.org/drools-3.0 drools-3.0.xsd\"> " + XmlDumper.eol;
appendXmlDump( xmlString );
appendXmlDump( processImportsList( packageDescr.getImports() ) );
appendXmlDump( processGlobalsMap( packageDescr.getGlobals() ) );
@@ -167,12 +168,12 @@ public void visitPackageDescr(final PackageDescr packageDescr) {
public void visitPredicateDescr(final PredicateDescr descr) {
this.template = new String();
- this.template = "<predicate field-name=\"" + descr.getFieldName() + "\" identifier=\"" + descr.getDeclaration() + "\" >" + descr.getText() + "</predicate>" + XmlDumper.eol;
+ this.template = "<predicate field-name=\"" + descr.getFieldName() + "\" identifier=\"" + descr.getDeclaration() + "\" >" + replaceIllegalChars( descr.getText() ) + "</predicate>" + XmlDumper.eol;
}
public void visitReturnValueRestrictionDescr(final ReturnValueRestrictionDescr descr) {
this.template = new String();
- this.template = "<return-value-restriction evaluator=\"" + getEvaluator( descr.getEvaluator() ) + "\" >" + descr.getText() + "</return-value>" + XmlDumper.eol;
+ this.template = "<return-value-restriction evaluator=\"" + replaceIllegalChars( descr.getEvaluator() ) + "\" >" + replaceIllegalChars( descr.getText() ) + "</return-value>" + XmlDumper.eol;
}
public void visitQueryDescr(final QueryDescr descr) {
@@ -196,7 +197,7 @@ private String processRules(final List rules) {
lhs = "<lhs> </lhs>";
}
- final String rhs = "<rhs>" + ruleDescr.getConsequence() + "</rhs>" + XmlDumper.eol;
+ final String rhs = "<rhs>" + replaceIllegalChars( ruleDescr.getConsequence() ) + "</rhs>" + XmlDumper.eol;
rule += attribute;
rule += lhs;
rule += rhs;
@@ -206,19 +207,19 @@ private String processRules(final List rules) {
return ruleList + XmlDumper.eol;
}
-
+
private String processFieldConstraint(List list) {
String descrString = "";
for ( final Iterator it = list.iterator(); it.hasNext(); ) {
final Object temp = it.next();
- descrString += "<field-restrictions name=\"" +((FieldConstraintDescr) temp).getFieldName() + "\"> ";
+ descrString += "<field-restrictions name=\"" + ((FieldConstraintDescr) temp).getFieldName() + "\"> ";
visit( temp );
- descrString += "</field-restrictions>";
+ descrString += "</field-restrictions>";
descrString += this.template;
}
return descrString.substring( 0,
descrString.length() - 2 );
- }
+ }
private String processDescrList(final List descr) {
String descrString = "";
@@ -292,13 +293,30 @@ private String processImportsList(final List imports) {
private void appendXmlDump(final String temp) {
this.xmlDump.append( temp );
}
-
- private String getEvaluator(String eval) {
-
- eval = eval.replaceAll( "<",
- "<" );
- eval = eval.replaceAll( ">",
- ">" );
- return eval;
- }
+
+ /**
+ * Replace illegal xml characters with their escaped equivalent
+ * <P>The escaped characters are :
+ * <ul>
+ * <li> <
+ * <li> >
+ * <li> &
+ * </ul>
+ * </p>
+ * @author <a href="mailto:[email protected]">Author Javier Prieto</a>
+ */
+ private String replaceIllegalChars(String code) {
+ StringBuffer sb = new StringBuffer();
+ int n = code.length();
+ for (int i = 0; i < n; i++) {
+ char c = code.charAt(i);
+ switch (c) {
+ case '<': sb.append("<"); break;
+ case '>': sb.append(">"); break;
+ case '&': sb.append("&"); break;
+ default: sb.append(c); break;
+ }
+ }
+ return sb.toString();
+ }
}
\ No newline at end of file
diff --git a/drools-compiler/src/test/resources/org/drools/integrationtests/test_Dumpers.drl b/drools-compiler/src/test/resources/org/drools/integrationtests/test_Dumpers.drl
index d79f225ab65..5dd5634db9d 100644
--- a/drools-compiler/src/test/resources/org/drools/integrationtests/test_Dumpers.drl
+++ b/drools-compiler/src/test/resources/org/drools/integrationtests/test_Dumpers.drl
@@ -9,8 +9,12 @@ rule "test MAIN 1"
when
Cheese( )
then
- list.add( "MAIN" );
- drools.setFocus( "agenda group 1" );
+ // lets also make sure that special chars are converted
+ if ( 3 < 4 && 4 > 3 ) {
+ list.add( "MAIN" );
+ drools.setFocus( "agenda group 1" );
+ }
+
end
rule "test group1 1"
@@ -29,7 +33,7 @@ rule "test group3 1"
when
Cheese( )
then
- list.add( "3 1" );
+ list.add( "3 1" );
end
|
ecbe69e87d908f4cc8bfec5f9a47244b8947fb0b
|
intellij-community
|
NPE fix--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/ui/impl/com/intellij/ide/ui/search/SearchUtil.java b/ui/impl/com/intellij/ide/ui/search/SearchUtil.java
index 4b333642d9593..058e68931b919 100644
--- a/ui/impl/com/intellij/ide/ui/search/SearchUtil.java
+++ b/ui/impl/com/intellij/ide/ui/search/SearchUtil.java
@@ -14,7 +14,6 @@
import com.intellij.ui.TabbedPaneWrapper;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.border.Border;
@@ -212,7 +211,8 @@ else if (rootComponent instanceof JRadioButton) {
return highlight;
}
- public static boolean isComponentHighlighted(@NotNull String text, @NotNull String option, final boolean force, final SearchableConfigurable configurable){
+ public static boolean isComponentHighlighted(String text, String option, final boolean force, final SearchableConfigurable configurable){
+ if (text == null || option == null) return false;
SearchableOptionsRegistrar searchableOptionsRegistrar = SearchableOptionsRegistrar.getInstance();
final Set<String> options = searchableOptionsRegistrar.replaceSynonyms(searchableOptionsRegistrar.getProcessedWords(option), configurable);
final Set<String> tokens = searchableOptionsRegistrar.getProcessedWords(text);
|
4becfb06985f23704a42a9699963f5bbe0366e7a
|
intellij-community
|
Fixed ipnb editor layout.--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/src/org/jetbrains/plugins/ipnb/editor/IpnbEditorUtil.java b/src/org/jetbrains/plugins/ipnb/editor/IpnbEditorUtil.java
index 1ee82a6327b02..6ffcceffb3a8c 100644
--- a/src/org/jetbrains/plugins/ipnb/editor/IpnbEditorUtil.java
+++ b/src/org/jetbrains/plugins/ipnb/editor/IpnbEditorUtil.java
@@ -17,13 +17,21 @@
import com.google.common.collect.Lists;
import com.intellij.execution.impl.ConsoleViewUtil;
+import com.intellij.ide.ui.UISettings;
+import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.EditorSettings;
+import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
+import com.intellij.openapi.editor.colors.EditorColorsScheme;
+import com.intellij.openapi.editor.colors.impl.DelegateColorScheme;
import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
+import com.intellij.ui.JBColor;
import com.intellij.util.ui.UIUtil;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl;
@@ -40,7 +48,8 @@
public class IpnbEditorUtil {
public static Editor createPythonCodeEditor(@NotNull Project project, @NotNull String text) {
- EditorEx editor = (EditorEx)EditorFactory.getInstance().createEditor(createPythonCodeDocument(project, text), project, PythonFileType.INSTANCE, false);
+ EditorEx editor =
+ (EditorEx)EditorFactory.getInstance().createEditor(createPythonCodeDocument(project, text), project, PythonFileType.INSTANCE, false);
noScrolling(editor);
ConsoleViewUtil.setupConsoleEditor(editor, false, false);
return editor;
@@ -50,7 +59,7 @@ private static void noScrolling(EditorEx editor) {
editor.getScrollPane().setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
editor.getScrollPane().setWheelScrollingEnabled(false);
List<MouseWheelListener> listeners = Lists.newArrayList(editor.getScrollPane().getMouseWheelListeners());
- for (MouseWheelListener l: listeners) {
+ for (MouseWheelListener l : listeners) {
editor.getScrollPane().removeMouseWheelListener(l);
}
}
@@ -64,17 +73,12 @@ public static Document createPythonCodeDocument(@NotNull final Project project,
return PsiDocumentManager.getInstance(project).getDocument(fragment);
}
- public static JPanel createPanelWithPrompt(@NotNull String promptText, @NotNull final JComponent component) {
- JPanel container = new JPanel(new BorderLayout());
- JPanel p = new JPanel(new BorderLayout());
- p.add(new JLabel(promptText), BorderLayout.WEST);
- container.add(p, BorderLayout.NORTH);
-
- container.add(component, BorderLayout.CENTER);
-
- p.setBackground(getBackground());
-
- return container;
+ public static JComponent createPromptPanel(@NotNull String promptText) {
+ JLabel promptLabel = new JLabel(promptText);
+ promptLabel.setFont(promptLabel.getFont().deriveFont(Font.BOLD));
+ promptLabel.setForeground(JBColor.BLUE);
+ promptLabel.setBackground(getBackground());
+ return promptLabel;
}
public static Color getBackground() {
diff --git a/src/org/jetbrains/plugins/ipnb/editor/panels/CodeOutputPanel.java b/src/org/jetbrains/plugins/ipnb/editor/panels/CodeOutputPanel.java
index ba75c4781d3e1..4588b7fcde317 100644
--- a/src/org/jetbrains/plugins/ipnb/editor/panels/CodeOutputPanel.java
+++ b/src/org/jetbrains/plugins/ipnb/editor/panels/CodeOutputPanel.java
@@ -2,26 +2,14 @@
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.ipnb.editor.IpnbEditorUtil;
-import org.jetbrains.plugins.ipnb.format.cells.output.CellOutput;
import javax.swing.*;
import java.awt.*;
public class CodeOutputPanel extends JPanel {
- private final Project myProject;
+ public CodeOutputPanel(@NotNull String outputText) {
+ super(new BorderLayout());
- public CodeOutputPanel(@NotNull final Project project, @NotNull final CellOutput cell, int promptNumber) {
- myProject = project;
- setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
-
- final String text = cell.getSourceAsString();
- if (text != null) {
- add(IpnbEditorUtil.createPanelWithPrompt(outputPrompt(promptNumber), new JTextArea(text)));
- }
- }
-
- private String outputPrompt(int promptNumber) {
- return String.format("Out[%d]:", promptNumber);
+ add(new JTextArea(outputText), BorderLayout.CENTER);
}
}
diff --git a/src/org/jetbrains/plugins/ipnb/editor/panels/CodeSourcePanel.java b/src/org/jetbrains/plugins/ipnb/editor/panels/CodeSourcePanel.java
index 15f6540f244ec..afdb85cd491a0 100644
--- a/src/org/jetbrains/plugins/ipnb/editor/panels/CodeSourcePanel.java
+++ b/src/org/jetbrains/plugins/ipnb/editor/panels/CodeSourcePanel.java
@@ -20,6 +20,7 @@
import org.jetbrains.plugins.ipnb.editor.IpnbEditorUtil;
import javax.swing.*;
+import java.awt.*;
/**
* @author traff
@@ -27,16 +28,10 @@
public class CodeSourcePanel extends JPanel implements EditorPanel {
private final Editor myEditor;
- public CodeSourcePanel(Project project, String source, int promptNumber) {
- setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
-
+ public CodeSourcePanel(Project project, String source) {
+ super(new BorderLayout());
myEditor = IpnbEditorUtil.createPythonCodeEditor(project, source);
-
- add(IpnbEditorUtil.createPanelWithPrompt(inputPrompt(promptNumber), myEditor.getComponent()));
- }
-
- private String inputPrompt(int promptNumber) {
- return String.format("In[%d]:", promptNumber);
+ add(myEditor.getComponent(), BorderLayout.CENTER);
}
@Override
diff --git a/src/org/jetbrains/plugins/ipnb/editor/panels/IpnbFilePanel.java b/src/org/jetbrains/plugins/ipnb/editor/panels/IpnbFilePanel.java
index 4286af11c80fc..f1ae99f7bb13d 100644
--- a/src/org/jetbrains/plugins/ipnb/editor/panels/IpnbFilePanel.java
+++ b/src/org/jetbrains/plugins/ipnb/editor/panels/IpnbFilePanel.java
@@ -16,7 +16,6 @@
package org.jetbrains.plugins.ipnb.editor.panels;
import com.intellij.openapi.Disposable;
-import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -38,54 +37,75 @@ public class IpnbFilePanel extends JPanel {
public IpnbFilePanel(@NotNull Project project, @Nullable Disposable parent, @NotNull IpnbFile file) {
super();
setLayout(new GridBagLayout());
+ setBackground(IpnbEditorUtil.getBackground());
- int row = 0;
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
- c.gridx = 0;
+ c.gridx = 1;
+ c.gridy = 0;
+ c.gridwidth = 1;
+
+ c.insets = new Insets(10, 0, 0, 0);
for (IpnbCell cell : file.getCells()) {
- JPanel panel = createPanelForCell(project, cell);
- c.gridy = row;
- row++;
- add(panel, c);
- if (cell instanceof CodeCell) {
- for (CellOutput cellOutput : ((CodeCell)cell).getCellOutputs()) {
- final JPanel outputPanel = createPanelForCellOutput(project, cellOutput, ((CodeCell)cell).getPromptNumber());
- c.gridy = row;
- row++;
- add(outputPanel, c);
- }
- }
+ c.gridy = addCellToPanel(project, cell, c);
}
c.weighty = 1;
add(createEmptyPanel(), c);
}
- private JPanel createEmptyPanel() {
- JPanel panel = new JPanel();
- panel.setBackground(IpnbEditorUtil.getBackground());
- return panel;
+ protected static String prompt(int promptNumber, String type) {
+ return String.format(type + "[%d]:", promptNumber);
}
- private JPanel createPanelForCellOutput(@NotNull final Project project, @NotNull final CellOutput cell, int number) {
- return new CodeOutputPanel(project, cell, number);
+ public static void addPromptPanel(JComponent container,
+ int promptNumber,
+ String promptType,
+ JComponent component,
+ GridBagConstraints c) {
+ c.gridx = 0;
+ container.add(IpnbEditorUtil.createPromptPanel(prompt(promptNumber, promptType)), c);
+ c.gridx = 1;
+ container.add(component, c);
}
- private JPanel createPanelForCell(@NotNull final Project project, @NotNull final IpnbCell cell) {
+ private int addCellToPanel(Project project, IpnbCell cell, GridBagConstraints c) {
if (cell instanceof CodeCell) {
- return new CodeSourcePanel(project, ((CodeCell)cell).getSourceAsString(), ((CodeCell)cell).getPromptNumber());
+ c.gridwidth = 2;
+ c.gridx = 0;
+
+ CodeCell codeCell = (CodeCell)cell;
+
+ addPromptPanel(this, codeCell.getPromptNumber(), "In", new CodeSourcePanel(project, codeCell.getSourceAsString()), c);
+
+ c.gridx = 1;
+ c.gridwidth = 1;
+
+ for (CellOutput cellOutput : codeCell.getCellOutputs()) {
+ c.gridy++;
+ if (cellOutput.getSourceAsString() != null) {
+ addPromptPanel(this, codeCell.getPromptNumber(), "Out",
+ new CodeOutputPanel(cellOutput.getSourceAsString()), c);
+ }
+ }
}
else if (cell instanceof MarkdownCell) {
- return new MarkdownPanel(project, (MarkdownCell)cell);
+ add(new MarkdownPanel(project, (MarkdownCell)cell), c);
}
else if (cell instanceof HeadingCell) {
- return new HeadingPanel(project, (HeadingCell)cell);
+ add(new HeadingPanel(project, (HeadingCell)cell), c);
}
else {
throw new UnsupportedOperationException(cell.getClass().toString());
}
+ return c.gridy + 1;
+ }
+
+ private JPanel createEmptyPanel() {
+ JPanel panel = new JPanel();
+ panel.setBackground(IpnbEditorUtil.getBackground());
+ return panel;
}
}
|
78cd19e253c72260935fc04610f7f22784c957a3
|
Valadoc
|
gtkdoc-scanner: Add support for , ", '
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/documentation/gtkdoccommentscanner.vala b/src/libvaladoc/documentation/gtkdoccommentscanner.vala
index 7cbc06a8d1..8f97416859 100644
--- a/src/libvaladoc/documentation/gtkdoccommentscanner.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentscanner.vala
@@ -157,6 +157,21 @@ public class Valadoc.Gtkdoc.Scanner {
start = (string) ((char*) pos + 8);
pos = (string) ((char*) pos + 7);
builder.append_c ('@');
+ } else if (pos.has_prefix (" ")) {
+ builder.append_len (start, (ssize_t) ((char*) pos - (char*) start));
+ start = (string) ((char*) pos + 6);
+ pos = (string) ((char*) pos + 5);
+ builder.append_c (' ');
+ } else if (pos.has_prefix (""")) {
+ builder.append_len (start, (ssize_t) ((char*) pos - (char*) start));
+ start = (string) ((char*) pos + 6);
+ pos = (string) ((char*) pos + 5);
+ builder.append_c ('"');
+ } else if (pos.has_prefix ("'")) {
+ builder.append_len (start, (ssize_t) ((char*) pos - (char*) start));
+ start = (string) ((char*) pos + 6);
+ pos = (string) ((char*) pos + 5);
+ builder.append_c ('\'');
} else if (pos.has_prefix ("(")) {
builder.append_len (start, (ssize_t) ((char*) pos - (char*) start));
start = (string) ((char*) pos + 6);
|
074f83c80b2fcb400e4e7102a882a0bcb4536e7e
|
hbase
|
HBASE-11671 TestEndToEndSplitTransaction fails on- master (Mikhail Antonov)--
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java
index 5cad147faf82..8de605de29d0 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestEndToEndSplitTransaction.java
@@ -45,7 +45,6 @@
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.Stoppable;
import org.apache.hadoop.hbase.client.Get;
-import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTable;
@@ -58,6 +57,7 @@
import org.apache.hadoop.hbase.protobuf.RequestConverter;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
+import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ConfigUtil;
import org.apache.hadoop.hbase.util.Pair;
@@ -126,7 +126,15 @@ public void testMasterOpsWhileSplitting() throws Exception {
// 3. finish phase II
// note that this replicates some code from SplitTransaction
// 2nd daughter first
- server.postOpenDeployTasks(regions.getSecond());
+ if (split.useZKForAssignment) {
+ server.postOpenDeployTasks(regions.getSecond());
+ } else {
+ server.reportRegionStateTransition(
+ RegionServerStatusProtos.RegionStateTransition.TransitionCode.SPLIT,
+ region.getRegionInfo(), regions.getFirst().getRegionInfo(),
+ regions.getSecond().getRegionInfo());
+ }
+
// Add to online regions
server.addToOnlineRegions(regions.getSecond());
// THIS is the crucial point:
@@ -136,7 +144,9 @@ public void testMasterOpsWhileSplitting() throws Exception {
assertTrue(test(con, tableName, lastRow, server));
// first daughter second
- server.postOpenDeployTasks(regions.getFirst());
+ if (split.useZKForAssignment) {
+ server.postOpenDeployTasks(regions.getFirst());
+ }
// Add to online regions
server.addToOnlineRegions(regions.getFirst());
assertTrue(test(con, tableName, firstRow, server));
|
161c9260542aead8826db802b524a75cb6fb8932
|
spring-framework
|
SPR-5624 - A default HandlerExceptionResolver- that resolves standard Spring exceptions--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
index f245b41b4bf1..231967867fbd 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
@@ -22,7 +22,6 @@
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
@@ -48,7 +47,6 @@
import org.springframework.ui.context.ThemeSource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
-import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
@@ -57,88 +55,65 @@
import org.springframework.web.util.WebUtils;
/**
- * Central dispatcher for HTTP request handlers/controllers,
- * e.g. for web UI controllers or HTTP-based remote service exporters.
- * Dispatches to registered handlers for processing a web request,
- * providing convenient mapping and exception handling facilities.
+ * Central dispatcher for HTTP request handlers/controllers, e.g. for web UI controllers or HTTP-based remote service
+ * exporters. Dispatches to registered handlers for processing a web request, providing convenient mapping and exception
+ * handling facilities.
*
- * <p>This servlet is very flexible: It can be used with just about any workflow,
- * with the installation of the appropriate adapter classes. It offers the
- * following functionality that distinguishes it from other request-driven
+ * <p>This servlet is very flexible: It can be used with just about any workflow, with the installation of the
+ * appropriate adapter classes. It offers the following functionality that distinguishes it from other request-driven
* web MVC frameworks:
*
- * <ul>
- * <li>It is based around a JavaBeans configuration mechanism.
+ * <ul> <li>It is based around a JavaBeans configuration mechanism.
*
- * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided
- * as part of an application - to control the routing of requests to handler objects.
- * Default is {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping} and
- * {@link org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping}.
- * HandlerMapping objects can be defined as beans in the servlet's application context,
- * implementing the HandlerMapping interface, overriding the default HandlerMapping if present.
- * HandlerMappings can be given any bean name (they are tested by type).
+ * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided as part of an application - to
+ * control the routing of requests to handler objects. Default is {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}
+ * and {@link org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping}. HandlerMapping objects
+ * can be defined as beans in the servlet's application context, implementing the HandlerMapping interface, overriding
+ * the default HandlerMapping if present. HandlerMappings can be given any bean name (they are tested by type).
*
- * <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
- * Default adapters are {@link org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter},
- * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter},
- * for Spring's {@link org.springframework.web.HttpRequestHandler} and
- * {@link org.springframework.web.servlet.mvc.Controller} interfaces, respectively. A default
- * {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
- * will be registered as well. HandlerAdapter objects can be added as beans in the
- * application context, overriding the default HandlerAdapters. Like HandlerMappings,
- * HandlerAdapters can be given any bean name (they are tested by type).
+ * <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface. Default adapters are {@link
+ * org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter}, {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter},
+ * for Spring's {@link org.springframework.web.HttpRequestHandler} and {@link org.springframework.web.servlet.mvc.Controller}
+ * interfaces, respectively. A default {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
+ * will be registered as well. HandlerAdapter objects can be added as beans in the application context, overriding the
+ * default HandlerAdapters. Like HandlerMappings, HandlerAdapters can be given any bean name (they are tested by type).
*
- * <li>The dispatcher's exception resolution strategy can be specified via a
- * {@link HandlerExceptionResolver}, for example mapping certain exceptions to
- * error pages. Default is none. Additional HandlerExceptionResolvers can be added
- * through the application context. HandlerExceptionResolver can be given any
- * bean name (they are tested by type).
+ * <li>The dispatcher's exception resolution strategy can be specified via a {@link HandlerExceptionResolver}, for
+ * example mapping certain exceptions to error pages. Default is none. Additional HandlerExceptionResolvers can be added
+ * through the application context. HandlerExceptionResolver can be given any bean name (they are tested by type).
*
- * <li>Its view resolution strategy can be specified via a {@link ViewResolver}
- * implementation, resolving symbolic view names into View objects. Default is
- * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
- * ViewResolver objects can be added as beans in the application context,
- * overriding the default ViewResolver. ViewResolvers can be given any bean name
- * (they are tested by type).
+ * <li>Its view resolution strategy can be specified via a {@link ViewResolver} implementation, resolving symbolic view
+ * names into View objects. Default is {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
+ * ViewResolver objects can be added as beans in the application context, overriding the default ViewResolver.
+ * ViewResolvers can be given any bean name (they are tested by type).
*
- * <li>If a {@link View} or view name is not supplied by the user, then the configured
- * {@link RequestToViewNameTranslator} will translate the current request into a
- * view name. The corresponding bean name is "viewNameTranslator"; the default is
- * {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}.
+ * <li>If a {@link View} or view name is not supplied by the user, then the configured {@link
+ * RequestToViewNameTranslator} will translate the current request into a view name. The corresponding bean name is
+ * "viewNameTranslator"; the default is {@link org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator}.
*
- * <li>The dispatcher's strategy for resolving multipart requests is determined by
- * a {@link org.springframework.web.multipart.MultipartResolver} implementation.
- * Implementations for Jakarta Commons FileUpload and Jason Hunter's COS are
- * included; the typical choise is
- * {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
+ * <li>The dispatcher's strategy for resolving multipart requests is determined by a {@link
+ * org.springframework.web.multipart.MultipartResolver} implementation. Implementations for Jakarta Commons FileUpload
+ * and Jason Hunter's COS are included; the typical choise is {@link org.springframework.web.multipart.commons.CommonsMultipartResolver}.
* The MultipartResolver bean name is "multipartResolver"; default is none.
*
- * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}.
- * Out-of-the-box implementations work via HTTP accept header, cookie, or session.
- * The LocaleResolver bean name is "localeResolver"; default is
- * {@link org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver}.
+ * <li>Its locale resolution strategy is determined by a {@link LocaleResolver}. Out-of-the-box implementations work via
+ * HTTP accept header, cookie, or session. The LocaleResolver bean name is "localeResolver"; default is {@link
+ * org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver}.
*
- * <li>Its theme resolution strategy is determined by a {@link ThemeResolver}.
- * Implementations for a fixed theme and for cookie and session storage are included.
- * The ThemeResolver bean name is "themeResolver"; default is
- * {@link org.springframework.web.servlet.theme.FixedThemeResolver}.
- * </ul>
+ * <li>Its theme resolution strategy is determined by a {@link ThemeResolver}. Implementations for a fixed theme and for
+ * cookie and session storage are included. The ThemeResolver bean name is "themeResolver"; default is {@link
+ * org.springframework.web.servlet.theme.FixedThemeResolver}. </ul>
*
- * <p><b>NOTE: The <code>@RequestMapping</code> annotation will only be processed
- * if a corresponding <code>HandlerMapping</code> (for type level annotations)
- * and/or <code>HandlerAdapter</code> (for method level annotations)
- * is present in the dispatcher.</b> This is the case by default.
- * However, if you are defining custom <code>HandlerMappings</code> or
- * <code>HandlerAdapters</code>, then you need to make sure that a
- * corresponding custom <code>DefaultAnnotationHandlerMapping</code>
- * and/or <code>AnnotationMethodHandlerAdapter</code> is defined as well
- * - provided that you intend to use <code>@RequestMapping</code>.
+ * <p><b>NOTE: The <code>@RequestMapping</code> annotation will only be processed if a corresponding
+ * <code>HandlerMapping</code> (for type level annotations) and/or <code>HandlerAdapter</code> (for method level
+ * annotations) is present in the dispatcher.</b> This is the case by default. However, if you are defining custom
+ * <code>HandlerMappings</code> or <code>HandlerAdapters</code>, then you need to make sure that a corresponding custom
+ * <code>DefaultAnnotationHandlerMapping</code> and/or <code>AnnotationMethodHandlerAdapter</code> is defined as well -
+ * provided that you intend to use <code>@RequestMapping</code>.
*
- * <p><b>A web application can define any number of DispatcherServlets.</b>
- * Each servlet will operate in its own namespace, loading its own application
- * context with mappings, handlers, etc. Only the root application context
- * as loaded by {@link org.springframework.web.context.ContextLoaderListener},
- * if any, will be shared.
+ * <p><b>A web application can define any number of DispatcherServlets.</b> Each servlet will operate in its own
+ * namespace, loading its own application context with mappings, handlers, etc. Only the root application context as
+ * loaded by {@link org.springframework.web.context.ContextLoaderListener}, if any, will be shared.
*
* @author Rod Johnson
* @author Juergen Hoeller
@@ -149,102 +124,92 @@
*/
public class DispatcherServlet extends FrameworkServlet {
- /**
- * Well-known name for the MultipartResolver object in the bean factory for this namespace.
- */
+ /** Well-known name for the MultipartResolver object in the bean factory for this namespace. */
public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver";
- /**
- * Well-known name for the LocaleResolver object in the bean factory for this namespace.
- */
+ /** Well-known name for the LocaleResolver object in the bean factory for this namespace. */
public static final String LOCALE_RESOLVER_BEAN_NAME = "localeResolver";
- /**
- * Well-known name for the ThemeResolver object in the bean factory for this namespace.
- */
+ /** Well-known name for the ThemeResolver object in the bean factory for this namespace. */
public static final String THEME_RESOLVER_BEAN_NAME = "themeResolver";
/**
- * Well-known name for the HandlerMapping object in the bean factory for this namespace.
- * Only used when "detectAllHandlerMappings" is turned off.
+ * Well-known name for the HandlerMapping object in the bean factory for this namespace. Only used when
+ * "detectAllHandlerMappings" is turned off.
+ *
* @see #setDetectAllHandlerMappings
*/
public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
/**
- * Well-known name for the HandlerAdapter object in the bean factory for this namespace.
- * Only used when "detectAllHandlerAdapters" is turned off.
+ * Well-known name for the HandlerAdapter object in the bean factory for this namespace. Only used when
+ * "detectAllHandlerAdapters" is turned off.
+ *
* @see #setDetectAllHandlerAdapters
*/
public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
/**
- * Well-known name for the HandlerExceptionResolver object in the bean factory for this
- * namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off.
+ * Well-known name for the HandlerExceptionResolver object in the bean factory for this namespace. Only used when
+ * "detectAllHandlerExceptionResolvers" is turned off.
+ *
* @see #setDetectAllHandlerExceptionResolvers
*/
public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
- /**
- * Well-known name for the RequestToViewNameTranslator object in the bean factory for
- * this namespace.
- */
+ /** Well-known name for the RequestToViewNameTranslator object in the bean factory for this namespace. */
public static final String REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator";
/**
- * Well-known name for the ViewResolver object in the bean factory for this namespace.
- * Only used when "detectAllViewResolvers" is turned off.
+ * Well-known name for the ViewResolver object in the bean factory for this namespace. Only used when
+ * "detectAllViewResolvers" is turned off.
+ *
* @see #setDetectAllViewResolvers
*/
public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver";
- /**
- * Request attribute to hold the currently chosen HandlerExecutionChain.
- * Only used for internal optimizations.
- */
+ /** Request attribute to hold the currently chosen HandlerExecutionChain. Only used for internal optimizations. */
public static final String HANDLER_EXECUTION_CHAIN_ATTRIBUTE = DispatcherServlet.class.getName() + ".HANDLER";
/**
- * Request attribute to hold the current web application context.
- * Otherwise only the global web app context is obtainable by tags etc.
+ * Request attribute to hold the current web application context. Otherwise only the global web app context is
+ * obtainable by tags etc.
+ *
* @see org.springframework.web.servlet.support.RequestContextUtils#getWebApplicationContext
*/
public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.class.getName() + ".CONTEXT";
/**
* Request attribute to hold the current LocaleResolver, retrievable by views.
+ *
* @see org.springframework.web.servlet.support.RequestContextUtils#getLocaleResolver
*/
public static final String LOCALE_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".LOCALE_RESOLVER";
/**
* Request attribute to hold the current ThemeResolver, retrievable by views.
+ *
* @see org.springframework.web.servlet.support.RequestContextUtils#getThemeResolver
*/
public static final String THEME_RESOLVER_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_RESOLVER";
/**
* Request attribute to hold the current ThemeSource, retrievable by views.
+ *
* @see org.springframework.web.servlet.support.RequestContextUtils#getThemeSource
*/
public static final String THEME_SOURCE_ATTRIBUTE = DispatcherServlet.class.getName() + ".THEME_SOURCE";
-
- /**
- * Log category to use when no mapped handler is found for a request.
- */
+ /** Log category to use when no mapped handler is found for a request. */
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
/**
- * Name of the class path resource (relative to the DispatcherServlet class)
- * that defines DispatcherServlet's default strategy names.
+ * Name of the class path resource (relative to the DispatcherServlet class) that defines DispatcherServlet's default
+ * strategy names.
*/
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
-
- /**
- * Additional logger to use when no mapped handler is found for a request.
- */
+ /** Additional logger to use when no mapped handler is found for a request. */
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
private static final Properties defaultStrategies;
@@ -262,7 +227,6 @@ public class DispatcherServlet extends FrameworkServlet {
}
}
-
/** Detect all HandlerMappings or just expect "handlerMapping" bean? */
private boolean detectAllHandlerMappings = true;
@@ -278,7 +242,6 @@ public class DispatcherServlet extends FrameworkServlet {
/** Perform cleanup of request attributes after include request? */
private boolean cleanupAfterInclude = true;
-
/** MultipartResolver used by this servlet */
private MultipartResolver multipartResolver;
@@ -303,80 +266,65 @@ public class DispatcherServlet extends FrameworkServlet {
/** List of ViewResolvers used by this servlet */
private List<ViewResolver> viewResolvers;
-
/**
- * Set whether to detect all HandlerMapping beans in this servlet's context.
- * Else, just a single bean with name "handlerMapping" will be expected.
- * <p>Default is "true". Turn this off if you want this servlet to use a
- * single HandlerMapping, despite multiple HandlerMapping beans being
- * defined in the context.
+ * Set whether to detect all HandlerMapping beans in this servlet's context. Else, just a single bean with name
+ * "handlerMapping" will be expected. <p>Default is "true". Turn this off if you want this servlet to use a single
+ * HandlerMapping, despite multiple HandlerMapping beans being defined in the context.
*/
public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
this.detectAllHandlerMappings = detectAllHandlerMappings;
}
/**
- * Set whether to detect all HandlerAdapter beans in this servlet's context.
- * Else, just a single bean with name "handlerAdapter" will be expected.
- * <p>Default is "true". Turn this off if you want this servlet to use a
- * single HandlerAdapter, despite multiple HandlerAdapter beans being
- * defined in the context.
+ * Set whether to detect all HandlerAdapter beans in this servlet's context. Else, just a single bean with name
+ * "handlerAdapter" will be expected. <p>Default is "true". Turn this off if you want this servlet to use a single
+ * HandlerAdapter, despite multiple HandlerAdapter beans being defined in the context.
*/
public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
this.detectAllHandlerAdapters = detectAllHandlerAdapters;
}
/**
- * Set whether to detect all HandlerExceptionResolver beans in this servlet's context.
- * Else, just a single bean with name "handlerExceptionResolver" will be expected.
- * <p>Default is "true". Turn this off if you want this servlet to use a
- * single HandlerExceptionResolver, despite multiple HandlerExceptionResolver
- * beans being defined in the context.
+ * Set whether to detect all HandlerExceptionResolver beans in this servlet's context. Else, just a single bean with
+ * name "handlerExceptionResolver" will be expected. <p>Default is "true". Turn this off if you want this servlet to
+ * use a single HandlerExceptionResolver, despite multiple HandlerExceptionResolver beans being defined in the
+ * context.
*/
public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
}
/**
- * Set whether to detect all ViewResolver beans in this servlet's context.
- * Else, just a single bean with name "viewResolver" will be expected.
- * <p>Default is "true". Turn this off if you want this servlet to use a
- * single ViewResolver, despite multiple ViewResolver beans being
- * defined in the context.
+ * Set whether to detect all ViewResolver beans in this servlet's context. Else, just a single bean with name
+ * "viewResolver" will be expected. <p>Default is "true". Turn this off if you want this servlet to use a single
+ * ViewResolver, despite multiple ViewResolver beans being defined in the context.
*/
public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
this.detectAllViewResolvers = detectAllViewResolvers;
}
/**
- * Set whether to perform cleanup of request attributes after an include request,
- * that is, whether to reset the original state of all request attributes after
- * the DispatcherServlet has processed within an include request. Else, just the
- * DispatcherServlet's own request attributes will be reset, but not model
- * attributes for JSPs or special attributes set by views (for example, JSTL's).
- * <p>Default is "true", which is strongly recommended. Views should not rely on
- * request attributes having been set by (dynamic) includes. This allows JSP views
- * rendered by an included controller to use any model attributes, even with the
- * same names as in the main JSP, without causing side effects. Only turn this
- * off for special needs, for example to deliberately allow main JSPs to access
- * attributes from JSP views rendered by an included controller.
+ * Set whether to perform cleanup of request attributes after an include request, that is, whether to reset the
+ * original state of all request attributes after the DispatcherServlet has processed within an include request. Else,
+ * just the DispatcherServlet's own request attributes will be reset, but not model attributes for JSPs or special
+ * attributes set by views (for example, JSTL's). <p>Default is "true", which is strongly recommended. Views should not
+ * rely on request attributes having been set by (dynamic) includes. This allows JSP views rendered by an included
+ * controller to use any model attributes, even with the same names as in the main JSP, without causing side effects.
+ * Only turn this off for special needs, for example to deliberately allow main JSPs to access attributes from JSP
+ * views rendered by an included controller.
*/
public void setCleanupAfterInclude(boolean cleanupAfterInclude) {
this.cleanupAfterInclude = cleanupAfterInclude;
}
-
- /**
- * This implementation calls {@link #initStrategies}.
- */
+ /** This implementation calls {@link #initStrategies}. */
@Override
protected void onRefresh(ApplicationContext context) throws BeansException {
initStrategies(context);
}
/**
- * Initialize the strategy objects that this servlet uses.
- * <p>May be overridden in subclasses in order to initialize
+ * Initialize the strategy objects that this servlet uses. <p>May be overridden in subclasses in order to initialize
* further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
@@ -391,8 +339,7 @@ protected void initStrategies(ApplicationContext context) {
}
/**
- * Initialize the MultipartResolver used by this class.
- * <p>If no bean is defined with the given name in the BeanFactory
+ * Initialize the MultipartResolver used by this class. <p>If no bean is defined with the given name in the BeanFactory
* for this namespace, no multipart handling is provided.
*/
private void initMultipartResolver(ApplicationContext context) {
@@ -406,15 +353,14 @@ private void initMultipartResolver(ApplicationContext context) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isDebugEnabled()) {
- logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
+ logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
"': no multipart request handling provided");
}
}
}
/**
- * Initialize the LocaleResolver used by this class.
- * <p>If no bean is defined with the given name in the BeanFactory
+ * Initialize the LocaleResolver used by this class. <p>If no bean is defined with the given name in the BeanFactory
* for this namespace, we default to AcceptHeaderLocaleResolver.
*/
private void initLocaleResolver(ApplicationContext context) {
@@ -435,9 +381,8 @@ private void initLocaleResolver(ApplicationContext context) {
}
/**
- * Initialize the ThemeResolver used by this class.
- * <p>If no bean is defined with the given name in the BeanFactory
- * for this namespace, we default to a FixedThemeResolver.
+ * Initialize the ThemeResolver used by this class. <p>If no bean is defined with the given name in the BeanFactory for
+ * this namespace, we default to a FixedThemeResolver.
*/
private void initThemeResolver(ApplicationContext context) {
try {
@@ -450,24 +395,24 @@ private void initThemeResolver(ApplicationContext context) {
// We need to use the default.
this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
if (logger.isDebugEnabled()) {
- logger.debug("Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME +
- "': using default [" + this.themeResolver + "]");
+ logger.debug(
+ "Unable to locate ThemeResolver with name '" + THEME_RESOLVER_BEAN_NAME + "': using default [" +
+ this.themeResolver + "]");
}
}
}
/**
- * Initialize the HandlerMappings used by this class.
- * <p>If no HandlerMapping beans are defined in the BeanFactory
- * for this namespace, we default to BeanNameUrlHandlerMapping.
+ * Initialize the HandlerMappings used by this class. <p>If no HandlerMapping beans are defined in the BeanFactory for
+ * this namespace, we default to BeanNameUrlHandlerMapping.
*/
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
- Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, HandlerMapping.class, true, false);
+ Map<String, HandlerMapping> matchingBeans =
+ BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
@@ -495,17 +440,16 @@ private void initHandlerMappings(ApplicationContext context) {
}
/**
- * Initialize the HandlerAdapters used by this class.
- * <p>If no HandlerAdapter beans are defined in the BeanFactory
- * for this namespace, we default to SimpleControllerHandlerAdapter.
+ * Initialize the HandlerAdapters used by this class. <p>If no HandlerAdapter beans are defined in the BeanFactory for
+ * this namespace, we default to SimpleControllerHandlerAdapter.
*/
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
- Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, HandlerAdapter.class, true, false);
+ Map<String, HandlerAdapter> matchingBeans =
+ BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<HandlerAdapter>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
@@ -533,17 +477,16 @@ private void initHandlerAdapters(ApplicationContext context) {
}
/**
- * Initialize the HandlerExceptionResolver used by this class.
- * <p>If no bean is defined with the given name in the BeanFactory
- * for this namespace, we default to no exception resolver.
+ * Initialize the HandlerExceptionResolver used by this class. <p>If no bean is defined with the given name in the
+ * BeanFactory for this namespace, we default to no exception resolver.
*/
private void initHandlerExceptionResolvers(ApplicationContext context) {
this.handlerExceptionResolvers = null;
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
- Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, HandlerExceptionResolver.class, true, false);
+ Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
+ .beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
@@ -552,8 +495,8 @@ private void initHandlerExceptionResolvers(ApplicationContext context) {
}
else {
try {
- HandlerExceptionResolver her = context.getBean(
- HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
+ HandlerExceptionResolver her =
+ context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -561,8 +504,8 @@ private void initHandlerExceptionResolvers(ApplicationContext context) {
}
}
- // Just for consistency, check for default HandlerExceptionResolvers...
- // There aren't any in usual scenarios.
+ // Ensure we have at least some HandlerExceptionResolvers, by registering
+ // default HandlerExceptionResolvers if no other resolvers are found.
if (this.handlerExceptionResolvers == null) {
this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
if (logger.isDebugEnabled()) {
@@ -572,13 +515,13 @@ private void initHandlerExceptionResolvers(ApplicationContext context) {
}
/**
- * Initialize the RequestToViewNameTranslator used by this servlet instance. If no
- * implementation is configured then we default to DefaultRequestToViewNameTranslator.
+ * Initialize the RequestToViewNameTranslator used by this servlet instance. If no implementation is configured then we
+ * default to DefaultRequestToViewNameTranslator.
*/
private void initRequestToViewNameTranslator(ApplicationContext context) {
try {
- this.viewNameTranslator = context.getBean(
- REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
+ this.viewNameTranslator =
+ context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
if (logger.isDebugEnabled()) {
logger.debug("Using RequestToViewNameTranslator [" + this.viewNameTranslator + "]");
}
@@ -588,24 +531,23 @@ private void initRequestToViewNameTranslator(ApplicationContext context) {
this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate RequestToViewNameTranslator with name '" +
- REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME +
- "': using default [" + this.viewNameTranslator + "]");
+ REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME + "': using default [" + this.viewNameTranslator +
+ "]");
}
}
}
/**
- * Initialize the ViewResolvers used by this class.
- * <p>If no ViewResolver beans are defined in the BeanFactory
- * for this namespace, we default to InternalResourceViewResolver.
+ * Initialize the ViewResolvers used by this class. <p>If no ViewResolver beans are defined in the BeanFactory for this
+ * namespace, we default to InternalResourceViewResolver.
*/
private void initViewResolvers(ApplicationContext context) {
this.viewResolvers = null;
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
- Map<String, ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
- context, ViewResolver.class, true, false);
+ Map<String, ViewResolver> matchingBeans =
+ BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList<ViewResolver>(matchingBeans.values());
// We keep ViewResolvers in sorted order.
@@ -633,9 +575,9 @@ private void initViewResolvers(ApplicationContext context) {
}
/**
- * Return this servlet's ThemeSource, if any; else return <code>null</code>.
- * <p>Default is to return the WebApplicationContext as ThemeSource,
- * provided that it implements the ThemeSource interface.
+ * Return this servlet's ThemeSource, if any; else return <code>null</code>. <p>Default is to return the
+ * WebApplicationContext as ThemeSource, provided that it implements the ThemeSource interface.
+ *
* @return the ThemeSource, if any
* @see #getWebApplicationContext()
*/
@@ -650,18 +592,18 @@ public final ThemeSource getThemeSource() {
/**
* Obtain this servlet's MultipartResolver, if any.
- * @return the MultipartResolver used by this servlet, or <code>null</code>
- * if none (indicating that no multipart support is available)
+ *
+ * @return the MultipartResolver used by this servlet, or <code>null</code> if none (indicating that no multipart
+ * support is available)
*/
public final MultipartResolver getMultipartResolver() {
return this.multipartResolver;
}
-
/**
- * Return the default strategy object for the given strategy interface.
- * <p>The default implementation delegates to {@link #getDefaultStrategies},
- * expecting a single object in the list.
+ * Return the default strategy object for the given strategy interface. <p>The default implementation delegates to
+ * {@link #getDefaultStrategies}, expecting a single object in the list.
+ *
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the corresponding strategy object
@@ -677,10 +619,10 @@ protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategy
}
/**
- * Create a List of default strategy objects for the given strategy interface.
- * <p>The default implementation uses the "DispatcherServlet.properties" file
- * (in the same package as the DispatcherServlet class) to determine the class names.
- * It instantiates the strategy objects through the context's BeanFactory.
+ * Create a List of default strategy objects for the given strategy interface. <p>The default implementation uses the
+ * "DispatcherServlet.properties" file (in the same package as the DispatcherServlet class) to determine the class
+ * names. It instantiates the strategy objects through the context's BeanFactory.
+ *
* @param context the current WebApplicationContext
* @param strategyInterface the strategy interface
* @return the List of corresponding strategy objects
@@ -717,13 +659,12 @@ protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T>
}
/**
- * Create a default strategy.
- * <p>The default implementation uses
- * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
+ * Create a default strategy. <p>The default implementation uses {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
+ *
* @param context the current WebApplicationContext
* @param clazz the strategy implementation class to instantiate
- * @throws BeansException if initialization failed
* @return the fully configured strategy instance
+ * @throws BeansException if initialization failed
* @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean
*/
@@ -731,17 +672,16 @@ protected Object createDefaultStrategy(ApplicationContext context, Class clazz)
return context.getAutowireCapableBeanFactory().createBean(clazz);
}
-
/**
- * Exposes the DispatcherServlet-specific request attributes and
- * delegates to {@link #doDispatch} for the actual dispatching.
+ * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch} for the actual
+ * dispatching.
*/
@Override
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isDebugEnabled()) {
String requestUri = new UrlPathHelper().getRequestUri(request);
- logger.debug("DispatcherServlet with name '" + getServletName() +
- "' processing " + request.getMethod() + " request for [" + requestUri + "]");
+ logger.debug("DispatcherServlet with name '" + getServletName() + "' processing " + request.getMethod() +
+ " request for [" + requestUri + "]");
}
// Keep a snapshot of the request attributes in case of an include,
@@ -777,12 +717,11 @@ protected void doService(HttpServletRequest request, HttpServletResponse respons
}
/**
- * Process the actual dispatching to the handler.
- * <p>The handler will be obtained by applying the servlet's HandlerMappings in order.
- * The HandlerAdapter will be obtained by querying the servlet's installed
- * HandlerAdapters to find the first that supports the handler class.
- * <p>All HTTP methods are handled by this method. It's up to HandlerAdapters or
- * handlers themselves to decide which methods are acceptable.
+ * Process the actual dispatching to the handler. <p>The handler will be obtained by applying the servlet's
+ * HandlerMappings in order. The HandlerAdapter will be obtained by querying the servlet's installed HandlerAdapters to
+ * find the first that supports the handler class. <p>All HTTP methods are handled by this method. It's up to
+ * HandlerAdapters or handlers themselves to decide which methods are acceptable.
+ *
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception in case of any kind of processing failure
@@ -855,8 +794,8 @@ protected void doDispatch(HttpServletRequest request, HttpServletResponse respon
}
else {
if (logger.isDebugEnabled()) {
- logger.debug("Null ModelAndView returned to DispatcherServlet with name '" +
- getServletName() + "': assuming HandlerAdapter completed request handling");
+ logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() +
+ "': assuming HandlerAdapter completed request handling");
}
}
@@ -885,15 +824,16 @@ protected void doDispatch(HttpServletRequest request, HttpServletResponse respon
}
/**
- * Override HttpServlet's <code>getLastModified</code> method to evaluate
- * the Last-Modified value of the mapped handler.
+ * Override HttpServlet's <code>getLastModified</code> method to evaluate the Last-Modified value of the mapped
+ * handler.
*/
@Override
protected long getLastModified(HttpServletRequest request) {
if (logger.isDebugEnabled()) {
String requestUri = new UrlPathHelper().getRequestUri(request);
- logger.debug("DispatcherServlet with name '" + getServletName() +
- "' determining Last-Modified value for [" + requestUri + "]");
+ logger.debug(
+ "DispatcherServlet with name '" + getServletName() + "' determining Last-Modified value for [" +
+ requestUri + "]");
}
try {
HandlerExecutionChain mappedHandler = getHandler(request, true);
@@ -918,12 +858,11 @@ protected long getLastModified(HttpServletRequest request) {
}
}
-
/**
- * Build a LocaleContext for the given request, exposing the request's
- * primary locale as current locale.
- * <p>The default implementation uses the dispatcher's LocaleResolver
- * to obtain the current locale, which might change during a request.
+ * Build a LocaleContext for the given request, exposing the request's primary locale as current locale. <p>The default
+ * implementation uses the dispatcher's LocaleResolver to obtain the current locale, which might change during a
+ * request.
+ *
* @param request current HTTP request
* @return the corresponding LocaleContext
*/
@@ -933,6 +872,7 @@ protected LocaleContext buildLocaleContext(final HttpServletRequest request) {
public Locale getLocale() {
return localeResolver.resolveLocale(request);
}
+
@Override
public String toString() {
return getLocale().toString();
@@ -941,8 +881,9 @@ public String toString() {
}
/**
- * Convert the request into a multipart request, and make multipart resolver available.
- * If no multipart resolver is set, simply use the existing request.
+ * Convert the request into a multipart request, and make multipart resolver available. If no multipart resolver is
+ * set, simply use the existing request.
+ *
* @param request current HTTP request
* @return the processed request (multipart wrapper if necessary)
* @see MultipartResolver#resolveMultipart
@@ -963,6 +904,7 @@ protected HttpServletRequest checkMultipart(HttpServletRequest request) throws M
/**
* Clean up any resources used by the given multipart request (if any).
+ *
* @param request current HTTP request
* @see MultipartResolver#cleanupMultipart
*/
@@ -973,15 +915,14 @@ protected void cleanupMultipart(HttpServletRequest request) {
}
/**
- * Return the HandlerExecutionChain for this request.
- * Try all handler mappings in order.
+ * Return the HandlerExecutionChain for this request. Try all handler mappings in order.
+ *
* @param request current HTTP request
* @param cache whether to cache the HandlerExecutionChain in a request attribute
* @return the HandlerExceutionChain, or <code>null</code> if no handler could be found
*/
protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception {
- HandlerExecutionChain handler =
- (HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
+ HandlerExecutionChain handler = (HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
if (handler != null) {
if (!cache) {
request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
@@ -1007,6 +948,7 @@ protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean c
/**
* No handler found -> set appropriate HTTP response status.
+ *
* @param request current HTTP request
* @param response current HTTP response
* @throws Exception if preparing the response failed
@@ -1014,17 +956,17 @@ protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean c
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
String requestUri = new UrlPathHelper().getRequestUri(request);
- pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" +
- requestUri + "] in DispatcherServlet with name '" + getServletName() + "'");
+ pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + requestUri +
+ "] in DispatcherServlet with name '" + getServletName() + "'");
}
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/**
* Return the HandlerAdapter for this handler object.
+ *
* @param handler the handler object to find an adapter for
- * @throws ServletException if no HandlerAdapter can be found for the handler.
- * This is a fatal error.
+ * @throws ServletException if no HandlerAdapter can be found for the handler. This is a fatal error.
*/
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
for (HandlerAdapter ha : this.handlerAdapters) {
@@ -1041,17 +983,19 @@ protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletExcepti
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
+ *
* @param request current HTTP request
* @param response current HTTP response
- * @param handler the executed handler, or <code>null</code> if none chosen at the time of
- * the exception (for example, if multipart resolution failed)
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
- protected ModelAndView processHandlerException(
- HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
- throws Exception {
+ protected ModelAndView processHandlerException(HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception ex) throws Exception {
// Check registerer HandlerExceptionResolvers...
ModelAndView exMv = null;
@@ -1066,35 +1010,26 @@ protected ModelAndView processHandlerException(
return null;
}
if (logger.isDebugEnabled()) {
- logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv, ex);
+ logger.debug("Handler execution resulted in exception - forwarding to resolved error view: " + exMv,
+ ex);
}
WebUtils.exposeErrorRequestAttributes(request, ex, getServletName());
return exMv;
}
- // Send default responses for well-known exceptions, if possible.
- if (ex instanceof HttpRequestMethodNotSupportedException && !response.isCommitted()) {
- String[] supportedMethods = ((HttpRequestMethodNotSupportedException) ex).getSupportedMethods();
- if (supportedMethods != null) {
- response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
- }
- response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
- return null;
- }
-
throw ex;
}
/**
- * Render the given ModelAndView. This is the last stage in handling a request.
- * It may involve resolving the view by name.
+ * Render the given ModelAndView. This is the last stage in handling a request. It may involve resolving the view by
+ * name.
+ *
* @param mv the ModelAndView to render
* @param request current HTTP servlet request
* @param response current HTTP servlet response
* @throws Exception if there's a problem rendering the view
*/
- protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response)
- throws Exception {
+ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Determine locale for request and apply it to the response.
Locale locale = this.localeResolver.resolveLocale(request);
@@ -1106,8 +1041,9 @@ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletRe
// We need to resolve the view name.
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
if (view == null) {
- throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
- "' in servlet with name '" + getServletName() + "'");
+ throw new ServletException(
+ "Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" +
+ getServletName() + "'");
}
}
else {
@@ -1128,6 +1064,7 @@ protected void render(ModelAndView mv, HttpServletRequest request, HttpServletRe
/**
* Translate the supplied request into a default view name.
+ *
* @param request current HTTP servlet request
* @return the view name (or <code>null</code> if no default found)
* @throws Exception if view name translation failed
@@ -1137,22 +1074,22 @@ protected String getDefaultViewName(HttpServletRequest request) throws Exception
}
/**
- * Resolve the given view name into a View object (to be rendered).
- * <p>Default implementations asks all ViewResolvers of this dispatcher.
- * Can be overridden for custom resolution strategies, potentially based
- * on specific model attributes or request parameters.
+ * Resolve the given view name into a View object (to be rendered). <p>Default implementations asks all ViewResolvers
+ * of this dispatcher. Can be overridden for custom resolution strategies, potentially based on specific model
+ * attributes or request parameters.
+ *
* @param viewName the name of the view to resolve
* @param model the model to be passed to the view
* @param locale the current locale
* @param request current HTTP servlet request
* @return the View object, or <code>null</code> if none found
- * @throws Exception if the view cannot be resolved
- * (typically in case of problems creating an actual View object)
+ * @throws Exception if the view cannot be resolved (typically in case of problems creating an actual View object)
* @see ViewResolver#resolveViewName
*/
- protected View resolveViewName(
- String viewName, Map<String, Object> model, Locale locale, HttpServletRequest request)
- throws Exception {
+ protected View resolveViewName(String viewName,
+ Map<String, Object> model,
+ Locale locale,
+ HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
@@ -1164,18 +1101,19 @@ protected View resolveViewName(
}
/**
- * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
- * Will just invoke afterCompletion for all interceptors whose preHandle
- * invocation has successfully completed and returned true.
+ * Trigger afterCompletion callbacks on the mapped HandlerInterceptors. Will just invoke afterCompletion for all
+ * interceptors whose preHandle invocation has successfully completed and returned true.
+ *
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or <code>null</code> if none
* @see HandlerInterceptor#afterCompletion
*/
- private void triggerAfterCompletion(
- HandlerExecutionChain mappedHandler, int interceptorIndex,
- HttpServletRequest request, HttpServletResponse response, Exception ex)
- throws Exception {
+ private void triggerAfterCompletion(HandlerExecutionChain mappedHandler,
+ int interceptorIndex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Exception ex) throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
@@ -1196,9 +1134,9 @@ private void triggerAfterCompletion(
/**
* Restore the request attributes after an include.
+ *
* @param request current HTTP request
- * @param attributesSnapshot the snapshot of the request attributes
- * before the include
+ * @param attributesSnapshot the snapshot of the request attributes before the include
*/
private void restoreAttributesAfterInclude(HttpServletRequest request, Map attributesSnapshot) {
logger.debug("Restoring snapshot of request attributes after include");
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties
index 95404a75500c..c550bd71275e 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/DispatcherServlet.properties
@@ -13,6 +13,8 @@ org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.m
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
+org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.handler.DefaultHandlerExceptionResolver
+
org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java
new file mode 100644
index 000000000000..a32f626da161
--- /dev/null
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java
@@ -0,0 +1,190 @@
+/*
+ * Copyright 2002-2009 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.servlet.handler;
+
+import java.util.Set;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.springframework.core.Ordered;
+import org.springframework.web.servlet.HandlerExceptionResolver;
+import org.springframework.web.servlet.ModelAndView;
+
+/**
+ * Abstract base class for {@link HandlerExceptionResolver} implementations. <p>Provides a set of mapped handlers that
+ * the resolver should map to, and the {@link Ordered} implementation.
+ *
+ * @author Arjen Poutsma
+ * @since 3.0
+ */
+public abstract class AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {
+
+ /** Logger available to subclasses */
+ protected final Log logger = LogFactory.getLog(getClass());
+
+ private int order = Ordered.LOWEST_PRECEDENCE;
+
+ private Set mappedHandlers;
+
+ private Class[] mappedHandlerClasses;
+
+ private Log warnLogger;
+
+ public void setOrder(int order) {
+ this.order = order;
+ }
+
+ public int getOrder() {
+ return this.order;
+ }
+
+ /**
+ * Specify the set of handlers that this exception resolver should apply to. The exception mappings and the default
+ * error view will only apply to the specified handlers. <p>If no handlers and handler classes are set, the exception
+ * mappings and the default error view will apply to all handlers. This means that a specified default error view will
+ * be used as fallback for all exceptions; any further HandlerExceptionResolvers in the chain will be ignored in this
+ * case.
+ */
+ public void setMappedHandlers(Set mappedHandlers) {
+ this.mappedHandlers = mappedHandlers;
+ }
+
+ /**
+ * Specify the set of classes that this exception resolver should apply to. The exception mappings and the default
+ * error view will only apply to handlers of the specified type; the specified types may be interfaces and superclasses
+ * of handlers as well. <p>If no handlers and handler classes are set, the exception mappings and the default error
+ * view will apply to all handlers. This means that a specified default error view will be used as fallback for all
+ * exceptions; any further HandlerExceptionResolvers in the chain will be ignored in this case.
+ */
+ public void setMappedHandlerClasses(Class[] mappedHandlerClasses) {
+ this.mappedHandlerClasses = mappedHandlerClasses;
+ }
+
+ /**
+ * Set the log category for warn logging. The name will be passed to the underlying logger implementation through
+ * Commons Logging, getting interpreted as log category according to the logger's configuration. <p>Default is no warn
+ * logging. Specify this setting to activate warn logging into a specific category. Alternatively, override the {@link
+ * #logException} method for custom logging.
+ *
+ * @see org.apache.commons.logging.LogFactory#getLog(String)
+ * @see org.apache.log4j.Logger#getLogger(String)
+ * @see java.util.logging.Logger#getLogger(String)
+ */
+ public void setWarnLogCategory(String loggerName) {
+ this.warnLogger = LogFactory.getLog(loggerName);
+ }
+
+ /**
+ * Checks whether this resolver is supposed to apply (i.e. the handler matches in case of "mappedHandlers" having been
+ * specified), then delegates to the {@link #doResolveException} template method.
+ */
+ public ModelAndView resolveException(HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception ex) {
+
+ if (shouldApplyTo(request, handler)) {
+ // Log exception, both at debug log level and at warn level, if desired.
+ if (logger.isDebugEnabled()) {
+ logger.debug("Resolving exception from handler [" + handler + "]: " + ex);
+ }
+ logException(ex, request);
+ return doResolveException(request, response, handler, ex);
+ }
+ else {
+ return null;
+ }
+ }
+
+ /**
+ * Check whether this resolver is supposed to apply to the given handler. <p>The default implementation checks against
+ * the specified mapped handlers and handler classes, if any.
+ *
+ * @param request current HTTP request
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return whether this resolved should proceed with resolving the exception for the given request and handler
+ * @see #setMappedHandlers
+ * @see #setMappedHandlerClasses
+ */
+ protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
+ if (handler != null) {
+ if (this.mappedHandlers != null && this.mappedHandlers.contains(handler)) {
+ return true;
+ }
+ if (this.mappedHandlerClasses != null) {
+ for (Class handlerClass : this.mappedHandlerClasses) {
+ if (handlerClass.isInstance(handler)) {
+ return true;
+ }
+ }
+ }
+ }
+ // Else only apply if there are no explicit handler mappings.
+ return (this.mappedHandlers == null && this.mappedHandlerClasses == null);
+ }
+
+ /**
+ * Log the given exception at warn level, provided that warn logging has been activated through the {@link
+ * #setWarnLogCategory "warnLogCategory"} property. <p>Calls {@link #buildLogMessage} in order to determine the
+ * concrete message to log. Always passes the full exception to the logger.
+ *
+ * @param ex the exception that got thrown during handler execution
+ * @param request current HTTP request (useful for obtaining metadata)
+ * @see #setWarnLogCategory
+ * @see #buildLogMessage
+ * @see org.apache.commons.logging.Log#warn(Object, Throwable)
+ */
+ protected void logException(Exception ex, HttpServletRequest request) {
+ if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
+ this.warnLogger.warn(buildLogMessage(ex, request), ex);
+ }
+ }
+
+ /**
+ * Build a log message for the given exception, occured during processing the given request.
+ *
+ * @param ex the exception that got thrown during handler execution
+ * @param request current HTTP request (useful for obtaining metadata)
+ * @return the log message to use
+ */
+ protected String buildLogMessage(Exception ex, HttpServletRequest request) {
+ return "Handler execution resulted in exception";
+ }
+
+ /**
+ * Actually resolve the given exception that got thrown during on handler execution, returning a ModelAndView that
+ * represents a specific error page if appropriate. <p>May be overridden in subclasses, in order to apply specific
+ * exception checks. Note that this template method will be invoked <i>after</i> checking whether this resolved applies
+ * ("mappedHandlers" etc), so an implementation may simply proceed with its actual exception handling.
+ *
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @param ex the exception that got thrown during handler execution
+ * @return a corresponding ModelAndView to forward to, or <code>null</code> for default processing
+ */
+ protected abstract ModelAndView doResolveException(HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception ex);
+
+}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolver.java
new file mode 100644
index 000000000000..03f837719aa2
--- /dev/null
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolver.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright 2002-2009 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.servlet.handler;
+
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.springframework.beans.TypeMismatchException;
+import org.springframework.core.Ordered;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.util.StringUtils;
+import org.springframework.web.HttpMediaTypeNotSupportedException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MissingServletRequestParameterException;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
+
+/**
+ * Default implementation of the {@link org.springframework.web.servlet.HandlerExceptionResolver
+ * HandlerExceptionResolver} interface that resolves standard Spring exceptions. <p>Default implementations typically
+ * set the response status.
+ *
+ * @author Arjen Poutsma
+ * @see #handleNoSuchRequestHandlingMethod
+ * @see #handleHttpRequestMethodNotSupported
+ * @see #handleHttpMediaTypeNotSupported
+ * @see #handleMissingServletRequestParameter
+ * @see #handleTypeMismatch
+ * @see #handleHttpMessageNotReadable
+ * @see #handleHttpMessageNotWritable
+ * @since 3.0
+ */
+public class DefaultHandlerExceptionResolver extends AbstractHandlerExceptionResolver {
+
+ /**
+ * Log category to use when no mapped handler is found for a request.
+ *
+ * @see #pageNotFoundLogger
+ */
+ public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
+
+ /**
+ * Additional logger to use when no mapped handler is found for a request.
+ *
+ * @see #PAGE_NOT_FOUND_LOG_CATEGORY
+ */
+ protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
+
+ /** Sets the {@linkplain #setOrder(int) order} to {@link #LOWEST_PRECEDENCE}. */
+ public DefaultHandlerExceptionResolver() {
+ setOrder(Ordered.LOWEST_PRECEDENCE);
+ }
+
+ @Override
+ protected ModelAndView doResolveException(HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception ex) {
+ try {
+ if (ex instanceof NoSuchRequestHandlingMethodException) {
+ return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response,
+ handler);
+ }
+ else if (ex instanceof HttpRequestMethodNotSupportedException) {
+ return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request,
+ response, handler);
+ }
+ else if (ex instanceof HttpMediaTypeNotSupportedException) {
+ return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response,
+ handler);
+ }
+ else if (ex instanceof MissingServletRequestParameterException) {
+ return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request,
+ response, handler);
+ }
+ else if (ex instanceof TypeMismatchException) {
+ return handleTypeMismatch((TypeMismatchException) ex, request, response, handler);
+ }
+ else if (ex instanceof HttpMessageNotReadableException) {
+ return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler);
+ }
+ else if (ex instanceof HttpMessageNotWritableException) {
+ return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler);
+ }
+ }
+ catch (Exception handlerException) {
+ logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
+ }
+ return null;
+ }
+
+ /**
+ * Handle the case where no request handler method was found. <p>The default implementation logs a warning, sends an
+ * HTTP 404 error, and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, or the
+ * NoSuchRequestHandlingMethodException could be rethrown as-is.
+ *
+ * @param ex the NoSuchRequestHandlingMethodException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ pageNotFoundLogger.warn(ex.getMessage());
+ response.sendError(HttpServletResponse.SC_NOT_FOUND);
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case where no request handler method was found for the particular HTTP request method. <p>The default
+ * implementation logs a warning, sends an HTTP 405 error, sets the "Allow" header, and returns an empty {@code
+ * ModelAndView}. Alternatively, a fallback view could be chosen, or the HttpRequestMethodNotSupportedException could
+ * be rethrown as-is.
+ *
+ * @param ex the HttpRequestMethodNotSupportedException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ pageNotFoundLogger.warn(ex.getMessage());
+ String[] supportedMethods = ex.getSupportedMethods();
+ if (supportedMethods != null) {
+ response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
+ }
+ response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case where no {@linkplain org.springframework.http.converter.HttpMessageConverter message converters}
+ * were found for the PUT or POSTed content. <p>The default implementation sends an HTTP 415 error, sets the "Allow"
+ * header, and returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, or the
+ * HttpMediaTypeNotSupportedException could be rethrown as-is.
+ *
+ * @param ex the HttpMediaTypeNotSupportedException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
+ List<MediaType> mediaTypes = ex.getSupportedMediaTypes();
+ if (mediaTypes != null) {
+ response.setHeader("Accept", MediaType.toString(mediaTypes));
+ }
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case when a required parameter is missing. <p>The default implementation sends an HTTP 400 error, and
+ * returns an empty {@code ModelAndView}. Alternatively, a fallback view could be chosen, or the
+ * MissingServletRequestParameterException could be rethrown as-is.
+ *
+ * @param ex the MissingServletRequestParameterException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case when a {@link org.springframework.web.bind.WebDataBinder} conversion error occurs. <p>The default
+ * implementation sends an HTTP 400 error, and returns an empty {@code ModelAndView}. Alternatively, a fallback view
+ * could be chosen, or the TypeMismatchException could be rethrown as-is.
+ *
+ * @param ex the TypeMismatchException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleTypeMismatch(TypeMismatchException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case where a {@linkplain org.springframework.http.converter.HttpMessageConverter message converter} can
+ * not read from a HTTP request. <p>The default implementation sends an HTTP 400 error, and returns an empty {@code
+ * ModelAndView}. Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotSupportedException could be
+ * rethrown as-is.
+ *
+ * @param ex the HttpMessageNotReadableException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+ return new ModelAndView();
+ }
+
+ /**
+ * Handle the case where a {@linkplain org.springframework.http.converter.HttpMessageConverter message converter} can
+ * not write to a HTTP request. <p>The default implementation sends an HTTP 500 error, and returns an empty {@code
+ * ModelAndView}. Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotSupportedException could be
+ * rethrown as-is.
+ *
+ * @param ex the HttpMessageNotWritableException to be handled
+ * @param request current HTTP request
+ * @param response current HTTP response
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
+ * @return a ModelAndView to render, or <code>null</code> if handled directly
+ * @throws Exception an Exception that should be thrown as result of the servlet request
+ */
+ protected ModelAndView handleHttpMessageNotWritable(HttpMessageNotWritableException ex,
+ HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler) throws Exception {
+
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return new ModelAndView();
+ }
+
+}
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java
index 8a5fade1ea06..f2f7affef7c9 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/handler/SimpleMappingExceptionResolver.java
@@ -18,51 +18,29 @@
import java.util.Enumeration;
import java.util.Properties;
-import java.util.Set;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import org.springframework.core.Ordered;
-import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
/**
- * {@link org.springframework.web.servlet.HandlerExceptionResolver} implementation
- * that allows for mapping exception class names to view names, either for a
- * set of given handlers or for all handlers in the DispatcherServlet.
+ * {@link org.springframework.web.servlet.HandlerExceptionResolver} implementation that allows for mapping exception
+ * class names to view names, either for a set of given handlers or for all handlers in the DispatcherServlet.
*
- * <p>Error views are analogous to error page JSPs, but can be used with any
- * kind of exception including any checked one, with fine-granular mappings for
- * specific handlers.
+ * <p>Error views are analogous to error page JSPs, but can be used with any kind of exception including any checked
+ * one, with fine-granular mappings for specific handlers.
*
* @author Juergen Hoeller
- * @since 22.11.2003
+ * @author Arjen Poutsma
* @see org.springframework.web.servlet.DispatcherServlet
+ * @since 22.11.2003
*/
-public class SimpleMappingExceptionResolver implements HandlerExceptionResolver, Ordered {
+public class SimpleMappingExceptionResolver extends AbstractHandlerExceptionResolver {
- /**
- * The default name of the exception attribute: "exception".
- */
+ /** The default name of the exception attribute: "exception". */
public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";
-
- /** Logger available to subclasses */
- protected final Log logger = LogFactory.getLog(getClass());
-
- private int order = Integer.MAX_VALUE; // default: same as non-Ordered
-
- private Set mappedHandlers;
-
- private Class[] mappedHandlerClasses;
-
- private Log warnLogger;
-
private Properties exceptionMappings;
private String defaultErrorView;
@@ -71,74 +49,18 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE;
-
- public void setOrder(int order) {
- this.order = order;
- }
-
- public int getOrder() {
- return this.order;
- }
-
/**
- * Specify the set of handlers that this exception resolver should apply to.
- * The exception mappings and the default error view will only apply
- * to the specified handlers.
- * <p>If no handlers and handler classes are set, the exception mappings
- * and the default error view will apply to all handlers. This means that
- * a specified default error view will be used as fallback for all exceptions;
- * any further HandlerExceptionResolvers in the chain will be ignored in
- * this case.
- */
- public void setMappedHandlers(Set mappedHandlers) {
- this.mappedHandlers = mappedHandlers;
- }
-
- /**
- * Specify the set of classes that this exception resolver should apply to.
- * The exception mappings and the default error view will only apply
- * to handlers of the specified type; the specified types may be interfaces
- * and superclasses of handlers as well.
- * <p>If no handlers and handler classes are set, the exception mappings
- * and the default error view will apply to all handlers. This means that
- * a specified default error view will be used as fallback for all exceptions;
- * any further HandlerExceptionResolvers in the chain will be ignored in
- * this case.
- */
- public void setMappedHandlerClasses(Class[] mappedHandlerClasses) {
- this.mappedHandlerClasses = mappedHandlerClasses;
- }
-
- /**
- * Set the log category for warn logging. The name will be passed to the
- * underlying logger implementation through Commons Logging, getting
- * interpreted as log category according to the logger's configuration.
- * <p>Default is no warn logging. Specify this setting to activate
- * warn logging into a specific category. Alternatively, override
- * the {@link #logException} method for custom logging.
- * @see org.apache.commons.logging.LogFactory#getLog(String)
- * @see org.apache.log4j.Logger#getLogger(String)
- * @see java.util.logging.Logger#getLogger(String)
- */
- public void setWarnLogCategory(String loggerName) {
- this.warnLogger = LogFactory.getLog(loggerName);
- }
-
- /**
- * Set the mappings between exception class names and error view names.
- * The exception class name can be a substring, with no wildcard support
- * at present. A value of "ServletException" would match
- * <code>javax.servlet.ServletException</code> and subclasses, for example.
- * <p><b>NB:</b> Consider carefully how specific the pattern is, and whether
- * to include package information (which isn't mandatory). For example,
- * "Exception" will match nearly anything, and will probably hide other rules.
- * "java.lang.Exception" would be correct if "Exception" was meant to define
- * a rule for all checked exceptions. With more unusual exception names such
- * as "BaseBusinessException" there's no need to use a FQN.
- * <p>Follows the same matching algorithm as RuleBasedTransactionAttribute
- * and RollbackRuleAttribute.
- * @param mappings exception patterns (can also be fully qualified class names)
- * as keys, and error view names as values
+ * Set the mappings between exception class names and error view names. The exception class name can be a substring,
+ * with no wildcard support at present. A value of "ServletException" would match
+ * <code>javax.servlet.ServletException</code> and subclasses, for example. <p><b>NB:</b> Consider carefully how
+ * specific the pattern is, and whether to include package information (which isn't mandatory). For example,
+ * "Exception" will match nearly anything, and will probably hide other rules. "java.lang.Exception" would be correct
+ * if "Exception" was meant to define a rule for all checked exceptions. With more unusual exception names such as
+ * "BaseBusinessException" there's no need to use a FQN. <p>Follows the same matching algorithm as
+ * RuleBasedTransactionAttribute and RollbackRuleAttribute.
+ *
+ * @param mappings exception patterns (can also be fully qualified class names) as keys, and error view names as
+ * values
* @see org.springframework.transaction.interceptor.RuleBasedTransactionAttribute
* @see org.springframework.transaction.interceptor.RollbackRuleAttribute
*/
@@ -147,24 +69,20 @@ public void setExceptionMappings(Properties mappings) {
}
/**
- * Set the name of the default error view.
- * This view will be returned if no specific mapping was found.
- * <p>Default is none.
+ * Set the name of the default error view. This view will be returned if no specific mapping was found. <p>Default is
+ * none.
*/
public void setDefaultErrorView(String defaultErrorView) {
this.defaultErrorView = defaultErrorView;
}
/**
- * Set the default HTTP status code that this exception resolver will apply
- * if it resolves an error view.
- * <p>Note that this error code will only get applied in case of a top-level
- * request. It will not be set for an include request, since the HTTP status
- * cannot be modified from within an include.
- * <p>If not specified, no status code will be applied, either leaving this to
- * the controller or view, or keeping the servlet engine's default of 200 (OK).
- * @param defaultStatusCode HTTP status code value, for example
- * 500 (SC_INTERNAL_SERVER_ERROR) or 404 (SC_NOT_FOUND)
+ * Set the default HTTP status code that this exception resolver will apply if it resolves an error view. <p>Note that
+ * this error code will only get applied in case of a top-level request. It will not be set for an include request,
+ * since the HTTP status cannot be modified from within an include. <p>If not specified, no status code will be
+ * applied, either leaving this to the controller or view, or keeping the servlet engine's default of 200 (OK).
+ *
+ * @param defaultStatusCode HTTP status code value, for example 500 (SC_INTERNAL_SERVER_ERROR) or 404 (SC_NOT_FOUND)
* @see javax.servlet.http.HttpServletResponse#SC_INTERNAL_SERVER_ERROR
* @see javax.servlet.http.HttpServletResponse#SC_NOT_FOUND
*/
@@ -173,84 +91,33 @@ public void setDefaultStatusCode(int defaultStatusCode) {
}
/**
- * Set the name of the model attribute as which the exception should
- * be exposed. Default is "exception".
- * <p>This can be either set to a different attribute name or to
- * <code>null</code> for not exposing an exception attribute at all.
+ * Set the name of the model attribute as which the exception should be exposed. Default is "exception". <p>This can be
+ * either set to a different attribute name or to <code>null</code> for not exposing an exception attribute at all.
+ *
* @see #DEFAULT_EXCEPTION_ATTRIBUTE
*/
public void setExceptionAttribute(String exceptionAttribute) {
this.exceptionAttribute = exceptionAttribute;
}
-
/**
- * Checks whether this resolver is supposed to apply (i.e. the handler
- * matches in case of "mappedHandlers" having been specified), then
- * delegates to the {@link #doResolveException} template method.
- */
- public ModelAndView resolveException(
- HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
-
- if (shouldApplyTo(request, handler)) {
- return doResolveException(request, response, handler, ex);
- }
- else {
- return null;
- }
- }
-
- /**
- * Check whether this resolver is supposed to apply to the given handler.
- * <p>The default implementation checks against the specified mapped handlers
- * and handler classes, if any.
- * @param request current HTTP request
- * @param handler the executed handler, or <code>null</code> if none chosen at the
- * time of the exception (for example, if multipart resolution failed)
- * @return whether this resolved should proceed with resolving the exception
- * for the given request and handler
- * @see #setMappedHandlers
- * @see #setMappedHandlerClasses
- */
- protected boolean shouldApplyTo(HttpServletRequest request, Object handler) {
- if (handler != null) {
- if (this.mappedHandlers != null && this.mappedHandlers.contains(handler)) {
- return true;
- }
- if (this.mappedHandlerClasses != null) {
- for (Class handlerClass : this.mappedHandlerClasses) {
- if (handlerClass.isInstance(handler)) {
- return true;
- }
- }
- }
- }
- // Else only apply if there are no explicit handler mappings.
- return (this.mappedHandlers == null && this.mappedHandlerClasses == null);
- }
-
- /**
- * Actually resolve the given exception that got thrown during on handler execution,
- * returning a ModelAndView that represents a specific error page if appropriate.
- * <p>May be overridden in subclasses, in order to apply specific exception checks.
- * Note that this template method will be invoked <i>after</i> checking whether
- * this resolved applies ("mappedHandlers" etc), so an implementation may simply
- * proceed with its actual exception handling.
+ * Actually resolve the given exception that got thrown during on handler execution, returning a ModelAndView that
+ * represents a specific error page if appropriate. <p>May be overridden in subclasses, in order to apply specific
+ * exception checks. Note that this template method will be invoked <i>after</i> checking whether this resolved applies
+ * ("mappedHandlers" etc), so an implementation may simply proceed with its actual exception handling.
+ *
* @param request current HTTP request
* @param response current HTTP response
- * @param handler the executed handler, or <code>null</code> if none chosen at the
- * time of the exception (for example, if multipart resolution failed)
+ * @param handler the executed handler, or <code>null</code> if none chosen at the time of the exception (for example,
+ * if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to, or <code>null</code> for default processing
*/
- protected ModelAndView doResolveException(
- HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
-
- // Log exception, both at debug log level and at warn level, if desired.
- if (logger.isDebugEnabled()) {
- logger.debug("Resolving exception from handler [" + handler + "]: " + ex);
- }
- logException(ex, request);
+ @Override
+ protected ModelAndView doResolveException(HttpServletRequest request,
+ HttpServletResponse response,
+ Object handler,
+ Exception ex) {
// Expose ModelAndView for chosen error view.
String viewName = determineViewName(ex, request);
@@ -268,40 +135,10 @@ protected ModelAndView doResolveException(
}
}
-
- /**
- * Log the given exception at warn level, provided that warn logging has been
- * activated through the {@link #setWarnLogCategory "warnLogCategory"} property.
- * <p>Calls {@link #buildLogMessage} in order to determine the concrete message
- * to log. Always passes the full exception to the logger.
- * @param ex the exception that got thrown during handler execution
- * @param request current HTTP request (useful for obtaining metadata)
- * @see #setWarnLogCategory
- * @see #buildLogMessage
- * @see org.apache.commons.logging.Log#warn(Object, Throwable)
- */
- protected void logException(Exception ex, HttpServletRequest request) {
- if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
- this.warnLogger.warn(buildLogMessage(ex, request), ex);
- }
- }
-
/**
- * Build a log message for the given exception, occured during processing
- * the given request.
- * @param ex the exception that got thrown during handler execution
- * @param request current HTTP request (useful for obtaining metadata)
- * @return the log message to use
- */
- protected String buildLogMessage(Exception ex, HttpServletRequest request) {
- return "Handler execution resulted in exception";
- }
-
-
- /**
- * Determine the view name for the given exception, searching the
- * {@link #setExceptionMappings "exceptionMappings"}, using the
- * {@link #setDefaultErrorView "defaultErrorView"} as fallback.
+ * Determine the view name for the given exception, searching the {@link #setExceptionMappings "exceptionMappings"},
+ * using the {@link #setDefaultErrorView "defaultErrorView"} as fallback.
+ *
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
* @return the resolved view name, or <code>null</code> if none found
@@ -315,8 +152,8 @@ protected String determineViewName(Exception ex, HttpServletRequest request) {
// Return default error view else, if defined.
if (viewName == null && this.defaultErrorView != null) {
if (logger.isDebugEnabled()) {
- logger.debug("Resolving to default view '" + this.defaultErrorView +
- "' for exception of type [" + ex.getClass().getName() + "]");
+ logger.debug("Resolving to default view '" + this.defaultErrorView + "' for exception of type [" +
+ ex.getClass().getName() + "]");
}
viewName = this.defaultErrorView;
}
@@ -325,6 +162,7 @@ protected String determineViewName(Exception ex, HttpServletRequest request) {
/**
* Find a matching view name in the given exception mappings.
+ *
* @param exceptionMappings mappings between exception class names and error view names
* @param ex the exception that got thrown during handler execution
* @return the view name, or <code>null</code> if none found
@@ -351,11 +189,9 @@ protected String findMatchingViewName(Properties exceptionMappings, Exception ex
}
/**
- * Return the depth to the superclass matching.
- * <p>0 means ex matches exactly. Returns -1 if there's no match.
- * Otherwise, returns depth. Lowest depth wins.
- * <p>Follows the same algorithm as
- * {@link org.springframework.transaction.interceptor.RollbackRuleAttribute}.
+ * Return the depth to the superclass matching. <p>0 means ex matches exactly. Returns -1 if there's no match.
+ * Otherwise, returns depth. Lowest depth wins. <p>Follows the same algorithm as {@link
+ * org.springframework.transaction.interceptor.RollbackRuleAttribute}.
*/
protected int getDepth(String exceptionMapping, Exception ex) {
return getDepth(exceptionMapping, ex.getClass(), 0);
@@ -373,17 +209,15 @@ private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {
return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);
}
-
/**
- * Determine the HTTP status code to apply for the given error view.
- * <p>The default implementation always returns the specified
- * {@link #setDefaultStatusCode "defaultStatusCode"}, as a common
- * status code for all error views. Override this in a custom subclass
- * to determine a specific status code for the given view.
+ * Determine the HTTP status code to apply for the given error view. <p>The default implementation always returns the
+ * specified {@link #setDefaultStatusCode "defaultStatusCode"}, as a common status code for all error views. Override
+ * this in a custom subclass to determine a specific status code for the given view.
+ *
* @param request current HTTP request
* @param viewName the name of the error view
- * @return the HTTP status code to use, or <code>null</code> for the
- * servlet container's default (200 in case of a standard error view)
+ * @return the HTTP status code to use, or <code>null</code> for the servlet container's default (200 in case of a
+ * standard error view)
* @see #setDefaultStatusCode
* @see #applyStatusCodeIfPossible
*/
@@ -392,8 +226,9 @@ protected Integer determineStatusCode(HttpServletRequest request, String viewNam
}
/**
- * Apply the specified HTTP status code to the given response, if possible
- * (that is, if not executing within an include request).
+ * Apply the specified HTTP status code to the given response, if possible (that is, if not executing within an include
+ * request).
+ *
* @param request current HTTP request
* @param response current HTTP response
* @param statusCode the status code to apply
@@ -412,8 +247,9 @@ protected void applyStatusCodeIfPossible(HttpServletRequest request, HttpServlet
}
/**
- * Return a ModelAndView for the given request, view name and exception.
- * <p>The default implementation delegates to {@link #getModelAndView(String, Exception)}.
+ * Return a ModelAndView for the given request, view name and exception. <p>The default implementation delegates to
+ * {@link #getModelAndView(String, Exception)}.
+ *
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @param request current HTTP request (useful for obtaining metadata)
@@ -424,9 +260,9 @@ protected ModelAndView getModelAndView(String viewName, Exception ex, HttpServle
}
/**
- * Return a ModelAndView for the given view name and exception.
- * <p>The default implementation adds the specified exception attribute.
- * Can be overridden in subclasses.
+ * Return a ModelAndView for the given view name and exception. <p>The default implementation adds the specified
+ * exception attribute. Can be overridden in subclasses.
+ *
* @param viewName the name of the error view
* @param ex the exception that got thrown during handler execution
* @return the ModelAndView instance
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
index 3b419798e3ee..4cc68680ce38 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
@@ -52,7 +52,6 @@
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpInputMessage;
-import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
@@ -68,7 +67,6 @@
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.validation.support.BindingAwareModelMap;
-import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.MissingServletRequestParameterException;
@@ -101,38 +99,36 @@
import org.springframework.web.util.WebUtils;
/**
- * Implementation of the {@link org.springframework.web.servlet.HandlerAdapter}
- * interface that maps handler methods based on HTTP paths, HTTP methods and
- * request parameters expressed through the {@link RequestMapping} annotation.
+ * Implementation of the {@link org.springframework.web.servlet.HandlerAdapter} interface that maps handler methods
+ * based on HTTP paths, HTTP methods and request parameters expressed through the {@link RequestMapping} annotation.
*
- * <p>Supports request parameter binding through the {@link RequestParam} annotation.
- * Also supports the {@link ModelAttribute} annotation for exposing model attribute
- * values to the view, as well as {@link InitBinder} for binder initialization methods
- * and {@link SessionAttributes} for automatic session management of specific attributes.
+ * <p>Supports request parameter binding through the {@link RequestParam} annotation. Also supports the {@link
+ * ModelAttribute} annotation for exposing model attribute values to the view, as well as {@link InitBinder} for binder
+ * initialization methods and {@link SessionAttributes} for automatic session management of specific attributes.
*
- * <p>This adapter can be customized through various bean properties.
- * A common use case is to apply shared binder initialization logic through
- * a custom {@link #setWebBindingInitializer WebBindingInitializer}.
+ * <p>This adapter can be customized through various bean properties. A common use case is to apply shared binder
+ * initialization logic through a custom {@link #setWebBindingInitializer WebBindingInitializer}.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
- * @since 2.5
* @see #setPathMatcher
* @see #setMethodNameResolver
* @see #setWebBindingInitializer
* @see #setSessionAttributeStore
+ * @since 2.5
*/
public class AnnotationMethodHandlerAdapter extends WebContentGenerator implements HandlerAdapter {
/**
* Log category to use when no mapped handler is found for a request.
+ *
* @see #pageNotFoundLogger
*/
public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";
-
/**
* Additional logger to use when no mapped handler is found for a request.
+ *
* @see #PAGE_NOT_FOUND_LOG_CATEGORY
*/
protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
@@ -167,12 +163,11 @@ public AnnotationMethodHandlerAdapter() {
super(false);
}
-
/**
- * Set if URL lookup should always use the full path within the current servlet
- * context. Else, the path within the current servlet mapping is used if applicable
- * (that is, in the case of a ".../*" servlet mapping in web.xml).
+ * Set if URL lookup should always use the full path within the current servlet context. Else, the path within the
+ * current servlet mapping is used if applicable (that is, in the case of a ".../*" servlet mapping in web.xml).
* <p>Default is "false".
+ *
* @see org.springframework.web.util.UrlPathHelper#setAlwaysUseFullPath
*/
public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
@@ -180,10 +175,10 @@ public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
}
/**
- * Set if context path and request URI should be URL-decoded. Both are returned
- * <i>undecoded</i> by the Servlet API, in contrast to the servlet path.
- * <p>Uses either the request encoding or the default encoding according
- * to the Servlet spec (ISO-8859-1).
+ * Set if context path and request URI should be URL-decoded. Both are returned <i>undecoded</i> by the Servlet API, in
+ * contrast to the servlet path. <p>Uses either the request encoding or the default encoding according to the Servlet
+ * spec (ISO-8859-1).
+ *
* @see org.springframework.web.util.UrlPathHelper#setUrlDecode
*/
public void setUrlDecode(boolean urlDecode) {
@@ -191,10 +186,8 @@ public void setUrlDecode(boolean urlDecode) {
}
/**
- * Set the UrlPathHelper to use for resolution of lookup paths.
- * <p>Use this to override the default UrlPathHelper with a custom subclass,
- * or to share common UrlPathHelper settings across multiple HandlerMappings
- * and HandlerAdapters.
+ * Set the UrlPathHelper to use for resolution of lookup paths. <p>Use this to override the default UrlPathHelper with
+ * a custom subclass, or to share common UrlPathHelper settings across multiple HandlerMappings and HandlerAdapters.
*/
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");
@@ -202,8 +195,9 @@ public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
}
/**
- * Set the PathMatcher implementation to use for matching URL paths
- * against registered URL patterns. Default is AntPathMatcher.
+ * Set the PathMatcher implementation to use for matching URL paths against registered URL patterns. Default is
+ * AntPathMatcher.
+ *
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
@@ -212,9 +206,8 @@ public void setPathMatcher(PathMatcher pathMatcher) {
}
/**
- * Set the MethodNameResolver to use for resolving default handler methods
- * (carrying an empty <code>@RequestMapping</code> annotation).
- * <p>Will only kick in when the handler method cannot be resolved uniquely
+ * Set the MethodNameResolver to use for resolving default handler methods (carrying an empty
+ * <code>@RequestMapping</code> annotation). <p>Will only kick in when the handler method cannot be resolved uniquely
* through the annotation metadata already.
*/
public void setMethodNameResolver(MethodNameResolver methodNameResolver) {
@@ -222,18 +215,16 @@ public void setMethodNameResolver(MethodNameResolver methodNameResolver) {
}
/**
- * Specify a WebBindingInitializer which will apply pre-configured
- * configuration to every DataBinder that this controller uses.
+ * Specify a WebBindingInitializer which will apply pre-configured configuration to every DataBinder that this
+ * controller uses.
*/
public void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) {
this.webBindingInitializer = webBindingInitializer;
}
/**
- * Specify the strategy to store session attributes with.
- * <p>Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore},
- * storing session attributes in the HttpSession, using the same
- * attribute name as in the model.
+ * Specify the strategy to store session attributes with. <p>Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore},
+ * storing session attributes in the HttpSession, using the same attribute name as in the model.
*/
public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) {
Assert.notNull(sessionAttributeStore, "SessionAttributeStore must not be null");
@@ -241,11 +232,11 @@ public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore
}
/**
- * Cache content produced by <code>@SessionAttributes</code> annotated handlers
- * for the given number of seconds. Default is 0, preventing caching completely.
- * <p>In contrast to the "cacheSeconds" property which will apply to all general
- * handlers (but not to <code>@SessionAttributes</code> annotated handlers), this
- * setting will apply to <code>@SessionAttributes</code> annotated handlers only.
+ * Cache content produced by <code>@SessionAttributes</code> annotated handlers for the given number of seconds.
+ * Default is 0, preventing caching completely. <p>In contrast to the "cacheSeconds" property which will apply to all
+ * general handlers (but not to <code>@SessionAttributes</code> annotated handlers), this setting will apply to
+ * <code>@SessionAttributes</code> annotated handlers only.
+ *
* @see #setCacheSeconds
* @see org.springframework.web.bind.annotation.SessionAttributes
*/
@@ -254,20 +245,15 @@ public void setCacheSecondsForSessionAttributeHandlers(int cacheSecondsForSessio
}
/**
- * Set if controller execution should be synchronized on the session,
- * to serialize parallel invocations from the same client.
- * <p>More specifically, the execution of each handler method will get
- * synchronized if this flag is "true". The best available session mutex
- * will be used for the synchronization; ideally, this will be a mutex
- * exposed by HttpSessionMutexListener.
- * <p>The session mutex is guaranteed to be the same object during
- * the entire lifetime of the session, available under the key defined
- * by the <code>SESSION_MUTEX_ATTRIBUTE</code> constant. It serves as a
- * safe reference to synchronize on for locking on the current session.
- * <p>In many cases, the HttpSession reference itself is a safe mutex
- * as well, since it will always be the same object reference for the
- * same active logical session. However, this is not guaranteed across
- * different servlet containers; the only 100% safe way is a session mutex.
+ * Set if controller execution should be synchronized on the session, to serialize parallel invocations from the same
+ * client. <p>More specifically, the execution of each handler method will get synchronized if this flag is "true". The
+ * best available session mutex will be used for the synchronization; ideally, this will be a mutex exposed by
+ * HttpSessionMutexListener. <p>The session mutex is guaranteed to be the same object during the entire lifetime of the
+ * session, available under the key defined by the <code>SESSION_MUTEX_ATTRIBUTE</code> constant. It serves as a safe
+ * reference to synchronize on for locking on the current session. <p>In many cases, the HttpSession reference itself
+ * is a safe mutex as well, since it will always be the same object reference for the same active logical session.
+ * However, this is not guaranteed across different servlet containers; the only 100% safe way is a session mutex.
+ *
* @see org.springframework.web.util.HttpSessionMutexListener
* @see org.springframework.web.util.WebUtils#getSessionMutex(javax.servlet.http.HttpSession)
*/
@@ -276,44 +262,38 @@ public void setSynchronizeOnSession(boolean synchronizeOnSession) {
}
/**
- * Set the ParameterNameDiscoverer to use for resolving method parameter
- * names if needed (e.g. for default attribute names).
- * <p>Default is a {@link org.springframework.core.LocalVariableTableParameterNameDiscoverer}.
+ * Set the ParameterNameDiscoverer to use for resolving method parameter names if needed (e.g. for default attribute
+ * names). <p>Default is a {@link org.springframework.core.LocalVariableTableParameterNameDiscoverer}.
*/
public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
- * Set a custom ArgumentResolvers to use for special method parameter types.
- * Such a custom ArgumentResolver will kick in first, having a chance to
- * resolve an argument value before the standard argument handling kicks in.
+ * Set a custom ArgumentResolvers to use for special method parameter types. Such a custom ArgumentResolver will kick
+ * in first, having a chance to resolve an argument value before the standard argument handling kicks in.
*/
public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) {
- this.customArgumentResolvers = new WebArgumentResolver[] {argumentResolver};
+ this.customArgumentResolvers = new WebArgumentResolver[]{argumentResolver};
}
/**
- * Set one or more custom ArgumentResolvers to use for special method
- * parameter types. Any such custom ArgumentResolver will kick in first,
- * having a chance to resolve an argument value before the standard
- * argument handling kicks in.
+ * Set one or more custom ArgumentResolvers to use for special method parameter types. Any such custom ArgumentResolver
+ * will kick in first, having a chance to resolve an argument value before the standard argument handling kicks in.
*/
public void setCustomArgumentResolvers(WebArgumentResolver[] argumentResolvers) {
this.customArgumentResolvers = argumentResolvers;
}
/**
- * Set the message body converters to use. These converters are used to convert
- * from and to HTTP requests and responses.
+ * Set the message body converters to use. These converters are used to convert from and to HTTP requests and
+ * responses.
*/
public void setMessageConverters(HttpMessageConverter<?>[] messageConverters) {
Assert.notEmpty(messageConverters, "'messageConverters' must not be empty");
this.messageConverters = messageConverters;
}
-
-
public boolean supports(Object handler) {
return getMethodResolver(handler).hasHandlerMethods();
}
@@ -345,122 +325,46 @@ public ModelAndView handle(HttpServletRequest request, HttpServletResponse respo
return invokeHandlerMethod(request, response, handler);
}
- protected ModelAndView invokeHandlerMethod(
- HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-
- try {
- ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);
- Method handlerMethod = methodResolver.resolveHandlerMethod(request);
- ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);
- ServletWebRequest webRequest = new ServletWebRequest(request, response);
- ExtendedModelMap implicitModel = new BindingAwareModelMap();
-
- Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
- ModelAndView mav =
- methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
- methodInvoker.updateModelAttributes(
- handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);
- return mav;
- }
- catch (NoSuchRequestHandlingMethodException ex) {
- return handleNoSuchRequestHandlingMethod(ex, request, response);
- }
- catch (HttpRequestMethodNotSupportedException ex) {
- return handleHttpRequestMethodNotSupportedException(ex, request, response);
- }
- catch (HttpMediaTypeNotSupportedException ex) {
- return handleHttpMediaTypeNotSupportedException(ex, request, response);
- }
- }
-
- public long getLastModified(HttpServletRequest request, Object handler) {
- return -1;
- }
-
- /**
- * Handle the case where no request handler method was found.
- * <p>The default implementation logs a warning and sends an HTTP 404 error.
- * Alternatively, a fallback view could be chosen, or the
- * NoSuchRequestHandlingMethodException could be rethrown as-is.
- * @param ex the NoSuchRequestHandlingMethodException to be handled
- * @param request current HTTP request
- * @param response current HTTP response
- * @return a ModelAndView to render, or <code>null</code> if handled directly
- * @throws Exception an Exception that should be thrown as result of the servlet request
- */
- protected ModelAndView handleNoSuchRequestHandlingMethod(
- NoSuchRequestHandlingMethodException ex, HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- pageNotFoundLogger.warn(ex.getMessage());
- response.sendError(HttpServletResponse.SC_NOT_FOUND);
- return null;
- }
-
- /**
- * Handle the case where no request handler method was found for the particular HTTP request method.
- * <p>The default implementation logs a warning, sends an HTTP 405 error and sets the "Allow" header.
- * Alternatively, a fallback view could be chosen, or the HttpRequestMethodNotSupportedException
- * could be rethrown as-is.
- * @param ex the HttpRequestMethodNotSupportedException to be handled
- * @param request current HTTP request
- * @param response current HTTP response
- * @return a ModelAndView to render, or <code>null</code> if handled directly
- * @throws Exception an Exception that should be thrown as result of the servlet request
- */
- protected ModelAndView handleHttpRequestMethodNotSupportedException(
- HttpRequestMethodNotSupportedException ex, HttpServletRequest request, HttpServletResponse response)
+ protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
- pageNotFoundLogger.warn(ex.getMessage());
- response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
- response.addHeader("Allow", StringUtils.arrayToDelimitedString(ex.getSupportedMethods(), ", "));
- return null;
+ ServletHandlerMethodResolver methodResolver = getMethodResolver(handler);
+ Method handlerMethod = methodResolver.resolveHandlerMethod(request);
+ ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver);
+ ServletWebRequest webRequest = new ServletWebRequest(request, response);
+ ExtendedModelMap implicitModel = new BindingAwareModelMap();
+
+ Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
+ ModelAndView mav =
+ methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
+ methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest);
+ return mav;
}
- /**
- * Handle the case where no {@linkplain HttpMessageConverter message converters} was found for the PUT or POSTed
- * content.
- * <p>The default implementation logs a warning, sends an HTTP 415 error and sets the "Allow" header.
- * Alternatively, a fallback view could be chosen, or the HttpMediaTypeNotSupportedException
- * could be rethrown as-is.
- * @param ex the HttpMediaTypeNotSupportedException to be handled
- * @param request current HTTP request
- * @param response current HTTP response
- * @return a ModelAndView to render, or <code>null</code> if handled directly
- * @throws Exception an Exception that should be thrown as result of the servlet request
- */
- protected ModelAndView handleHttpMediaTypeNotSupportedException(
- HttpMediaTypeNotSupportedException ex, HttpServletRequest request, HttpServletResponse response)
- throws Exception {
-
- response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
- response.addHeader("Accept", MediaType.toString(ex.getSupportedMediaTypes()));
- return null;
+ public long getLastModified(HttpServletRequest request, Object handler) {
+ return -1;
}
/**
- * Template method for creating a new ServletRequestDataBinder instance.
- * <p>The default implementation creates a standard ServletRequestDataBinder.
- * This can be overridden for custom ServletRequestDataBinder subclasses.
+ * Template method for creating a new ServletRequestDataBinder instance. <p>The default implementation creates a
+ * standard ServletRequestDataBinder. This can be overridden for custom ServletRequestDataBinder subclasses.
+ *
* @param request current HTTP request
- * @param target the target object to bind onto (or <code>null</code>
- * if the binder is just used to convert a plain parameter value)
+ * @param target the target object to bind onto (or <code>null</code> if the binder is just used to convert a plain
+ * parameter value)
* @param objectName the objectName of the target object
* @return the ServletRequestDataBinder instance to use
* @throws Exception in case of invalid state or arguments
* @see ServletRequestDataBinder#bind(javax.servlet.ServletRequest)
* @see ServletRequestDataBinder#convertIfNecessary(Object, Class, MethodParameter)
*/
- protected ServletRequestDataBinder createBinder(
- HttpServletRequest request, Object target, String objectName) throws Exception {
+ protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object target, String objectName)
+ throws Exception {
return new ServletRequestDataBinder(target, objectName);
}
- /**
- * Build a HandlerMethodResolver for the given handler type.
- */
+ /** Build a HandlerMethodResolver for the given handler type. */
private ServletHandlerMethodResolver getMethodResolver(Object handler) {
Class handlerClass = ClassUtils.getUserClass(handler);
ServletHandlerMethodResolver resolver = this.methodResolverCache.get(handlerClass);
@@ -471,10 +375,7 @@ private ServletHandlerMethodResolver getMethodResolver(Object handler) {
return resolver;
}
-
- /**
- * Servlet-specific subclass of {@link HandlerMethodResolver}.
- */
+ /** Servlet-specific subclass of {@link HandlerMethodResolver}. */
private class ServletHandlerMethodResolver extends HandlerMethodResolver {
private ServletHandlerMethodResolver(Class<?> handlerType) {
@@ -499,7 +400,7 @@ public Method resolveHandlerMethod(HttpServletRequest request) throws ServletExc
}
boolean match = false;
if (mappingInfo.paths.length > 0) {
- List<String> matchedPaths = new ArrayList<String>(mappingInfo.paths.length);
+ List<String> matchedPaths = new ArrayList<String>(mappingInfo.paths.length);
for (String mappedPath : mappingInfo.paths) {
if (isPathMatch(mappedPath, lookupPath)) {
if (checkParameters(mappingInfo, request)) {
@@ -515,7 +416,7 @@ public Method resolveHandlerMethod(HttpServletRequest request) throws ServletExc
}
}
Collections.sort(matchedPaths, pathComparator);
- mappingInfo.matchedPaths = matchedPaths.toArray(new String[matchedPaths.size()]);
+ mappingInfo.matchedPaths = matchedPaths.toArray(new String[matchedPaths.size()]);
}
else {
// No paths specified: parameter match sufficient.
@@ -548,17 +449,19 @@ public Method resolveHandlerMethod(HttpServletRequest request) throws ServletExc
}
}
if (oldMappedMethod != null) {
- throw new IllegalStateException("Ambiguous handler methods mapped for HTTP path '" +
- lookupPath + "': {" + oldMappedMethod + ", " + handlerMethod +
- "}. If you intend to handle the same path in multiple methods, then factor " +
- "them out into a dedicated handler class with that path mapped at the type level!");
+ throw new IllegalStateException(
+ "Ambiguous handler methods mapped for HTTP path '" + lookupPath + "': {" +
+ oldMappedMethod + ", " + handlerMethod +
+ "}. If you intend to handle the same path in multiple methods, then factor " +
+ "them out into a dedicated handler class with that path mapped at the type level!");
}
}
}
}
if (!targetHandlerMethods.isEmpty()) {
List<RequestMappingInfo> matches = new ArrayList<RequestMappingInfo>(targetHandlerMethods.keySet());
- RequestMappingInfoComparator requestMappingInfoComparator = new RequestMappingInfoComparator(pathComparator);
+ RequestMappingInfoComparator requestMappingInfoComparator =
+ new RequestMappingInfoComparator(pathComparator);
Collections.sort(matches, requestMappingInfoComparator);
RequestMappingInfo bestMappingMatch = matches.get(0);
if (bestMappingMatch.matchedPaths.length > 0) {
@@ -597,7 +500,9 @@ private boolean checkParameters(RequestMappingInfo mapping, HttpServletRequest r
}
@SuppressWarnings("unchecked")
- private void extractHandlerMethodUriTemplates(String mappedPath, String lookupPath, HttpServletRequest request) {
+ private void extractHandlerMethodUriTemplates(String mappedPath,
+ String lookupPath,
+ HttpServletRequest request) {
Map<String, String> variables = null;
boolean hasSuffix = (mappedPath.indexOf('.') != -1);
if (!hasSuffix && pathMatcher.match(mappedPath + ".*", lookupPath)) {
@@ -610,7 +515,8 @@ private void extractHandlerMethodUriTemplates(String mappedPath, String lookupPa
String realPath = "/**/" + mappedPath;
if (pathMatcher.match(realPath, lookupPath)) {
variables = pathMatcher.extractUriTemplateVariables(realPath, lookupPath);
- } else {
+ }
+ else {
realPath = realPath + ".*";
if (pathMatcher.match(realPath, lookupPath)) {
variables = pathMatcher.extractUriTemplateVariables(realPath, lookupPath);
@@ -628,17 +534,14 @@ private void extractHandlerMethodUriTemplates(String mappedPath, String lookupPa
}
}
-
- /**
- * Servlet-specific subclass of {@link HandlerMethodInvoker}.
- */
+ /** Servlet-specific subclass of {@link HandlerMethodInvoker}. */
private class ServletHandlerMethodInvoker extends HandlerMethodInvoker {
private boolean responseArgumentUsed = false;
private ServletHandlerMethodInvoker(HandlerMethodResolver resolver) {
- super(resolver, webBindingInitializer, sessionAttributeStore,
- parameterNameDiscoverer, customArgumentResolvers, messageConverters);
+ super(resolver, webBindingInitializer, sessionAttributeStore, parameterNameDiscoverer,
+ customArgumentResolvers, messageConverters);
}
@Override
@@ -655,8 +558,8 @@ protected void raiseSessionRequiredException(String message) throws Exception {
protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName)
throws Exception {
- return AnnotationMethodHandlerAdapter.this.createBinder(
- (HttpServletRequest) webRequest.getNativeRequest(), target, objectName);
+ return AnnotationMethodHandlerAdapter.this
+ .createBinder((HttpServletRequest) webRequest.getNativeRequest(), target, objectName);
}
@Override
@@ -699,14 +602,14 @@ protected String resolvePathVariable(String pathVarName, Class paramType, Native
Map<String, String> uriTemplateVariables =
(Map<String, String>) servletRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
if (uriTemplateVariables == null || !uriTemplateVariables.containsKey(pathVarName)) {
- throw new IllegalStateException("Could not find @PathVariable [" + pathVarName + "] in @RequestMapping");
+ throw new IllegalStateException(
+ "Could not find @PathVariable [" + pathVarName + "] in @RequestMapping");
}
return uriTemplateVariables.get(pathVarName);
}
@Override
- protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest)
- throws Exception {
+ protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) throws Exception {
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();
@@ -745,8 +648,11 @@ else if (Writer.class.isAssignableFrom(parameterType)) {
}
@SuppressWarnings("unchecked")
- public ModelAndView getModelAndView(Method handlerMethod, Class handlerType, Object returnValue,
- ExtendedModelMap implicitModel, ServletWebRequest webRequest) {
+ public ModelAndView getModelAndView(Method handlerMethod,
+ Class handlerType,
+ Object returnValue,
+ ExtendedModelMap implicitModel,
+ ServletWebRequest webRequest) {
if (returnValue instanceof ModelAndView) {
ModelAndView mav = (ModelAndView) returnValue;
@@ -792,7 +698,6 @@ else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) {
}
}
-
static class RequestMappingInfo {
String[] paths = new String[0];
@@ -806,7 +711,7 @@ static class RequestMappingInfo {
String bestMatchedPath() {
return matchedPaths.length > 0 ? matchedPaths[0] : null;
}
-
+
@Override
public boolean equals(Object obj) {
RequestMappingInfo other = (RequestMappingInfo) obj;
@@ -823,16 +728,12 @@ public int hashCode() {
/**
* Comparator capable of sorting {@link RequestMappingInfo}s (RHIs) so that sorting a list with this comparator will
- * result in:
- * <ul>
- * <li>RHIs with {@linkplain RequestMappingInfo#matchedPaths better matched paths} take prescedence over those with
- * a weaker match (as expressed by the {@linkplain PathMatcher#getPatternComparator(String) path pattern
- * comparator}.) Typically, this means that patterns without wild chards and uri templates will be ordered before those without.</li>
- * <li>RHIs with one single {@linkplain RequestMappingInfo#methods request method} will be ordered before those
- * without a method, or with more than one method.</li>
- * <li>RHIs with more {@linkplain RequestMappingInfo#params request parameters} will be ordered before those with
- * less parameters</li>
- * </ol>
+ * result in: <ul> <li>RHIs with {@linkplain RequestMappingInfo#matchedPaths better matched paths} take prescedence
+ * over those with a weaker match (as expressed by the {@linkplain PathMatcher#getPatternComparator(String) path
+ * pattern comparator}.) Typically, this means that patterns without wild chards and uri templates will be ordered
+ * before those without.</li> <li>RHIs with one single {@linkplain RequestMappingInfo#methods request method} will be
+ * ordered before those without a method, or with more than one method.</li> <li>RHIs with more {@linkplain
+ * RequestMappingInfo#params request parameters} will be ordered before those with less parameters</li> </ol>
*/
static class RequestMappingInfoComparator implements Comparator<RequestMappingInfo> {
@@ -867,5 +768,5 @@ else if (info2MethodCount == 1 & info1MethodCount > 1) {
return (info1ParamCount < info2ParamCount ? 1 : (info1ParamCount == info2ParamCount ? 0 : -1));
}
}
-
+
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolverTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolverTests.java
new file mode 100644
index 000000000000..9ee8b2035e0a
--- /dev/null
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/handler/DefaultHandlerExceptionResolverTests.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2002-2009 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.servlet.handler;
+
+import java.util.Collections;
+
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
+
+import org.springframework.beans.TypeMismatchException;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.web.HttpMediaTypeNotSupportedException;
+import org.springframework.web.HttpRequestMethodNotSupportedException;
+import org.springframework.web.bind.MissingServletRequestParameterException;
+import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
+
+/** @author Arjen Poutsma */
+public class DefaultHandlerExceptionResolverTests {
+
+ private DefaultHandlerExceptionResolver exceptionResolver;
+
+ private MockHttpServletRequest request;
+
+ private MockHttpServletResponse response;
+
+ @Before
+ public void setUp() {
+ exceptionResolver = new DefaultHandlerExceptionResolver();
+ request = new MockHttpServletRequest();
+ response = new MockHttpServletResponse();
+ request.setMethod("GET");
+ }
+
+ @Test
+ public void handleNoSuchRequestHandlingMethod() {
+ NoSuchRequestHandlingMethodException ex = new NoSuchRequestHandlingMethodException(request);
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 404, response.getStatus());
+ }
+
+ @Test
+ public void handleHttpRequestMethodNotSupported() {
+ HttpRequestMethodNotSupportedException ex =
+ new HttpRequestMethodNotSupportedException("GET", new String[]{"POST", "PUT"});
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 405, response.getStatus());
+ assertEquals("Invalid Allow header", "POST, PUT", response.getHeader("Allow"));
+ }
+
+ @Test
+ public void handleHttpMediaTypeNotSupported() {
+ HttpMediaTypeNotSupportedException ex = new HttpMediaTypeNotSupportedException(new MediaType("text", "plain"),
+ Collections.singletonList(new MediaType("application", "pdf")));
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 415, response.getStatus());
+ assertEquals("Invalid Accept header", "application/pdf", response.getHeader("Accept"));
+ }
+
+ @Test
+ public void handleMissingServletRequestParameter() {
+ MissingServletRequestParameterException ex = new MissingServletRequestParameterException("foo", "bar");
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 400, response.getStatus());
+ }
+
+ @Test
+ public void handleTypeMismatch() {
+ TypeMismatchException ex = new TypeMismatchException("foo", String.class);
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 400, response.getStatus());
+ }
+
+ @Test
+ public void handleHttpMessageNotReadable() {
+ HttpMessageNotReadableException ex = new HttpMessageNotReadableException("foo");
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 400, response.getStatus());
+ }
+
+ @Test
+ public void handleHttpMessageNotWritable() {
+ HttpMessageNotWritableException ex = new HttpMessageNotWritableException("foo");
+ exceptionResolver.resolveException(request, response, null, ex);
+ assertEquals("Invalid status code", 500, response.getStatus());
+ }
+
+
+}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
index 74efeaf73419..2e6771ae593c 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java
@@ -21,6 +21,7 @@
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
@@ -51,6 +52,12 @@
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.core.MethodParameter;
+import org.springframework.http.HttpInputMessage;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
@@ -62,7 +69,6 @@
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
-import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.InitBinder;
@@ -107,13 +113,25 @@ public void standardHandleMethod() throws Exception {
assertEquals("test", response.getContentAsString());
}
- @Test(expected = MissingServletRequestParameterException.class)
+ @Test
public void requiredParamMissing() throws Exception {
initServlet(RequiredParamController.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.service(request, response);
+ assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
+ }
+
+ @Test
+ public void typeConversionError() throws Exception {
+ initServlet(RequiredParamController.class);
+
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
+ request.addParameter("id", "foo");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}
@Test
@@ -157,7 +175,7 @@ public void methodNotAllowed() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.service(request, response);
assertEquals("Invalid response status", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus());
- String allowHeader = (String)response.getHeader("Allow");
+ String allowHeader = (String) response.getHeader("Allow");
assertNotNull("No Allow header", allowHeader);
Set<String> allowedMethods = new HashSet<String>();
allowedMethods.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", ")));
@@ -249,7 +267,6 @@ protected WebApplicationContext createWebApplicationContext(WebApplicationContex
servlet.init(new MockServletConfig());
}
-
private void doTestAdaptedHandleMethods(final Class<?> controllerClass) throws Exception {
initServlet(controllerClass);
@@ -878,6 +895,31 @@ public void unsupportedRequestBody() throws ServletException, IOException {
assertNotNull("No Accept response header set", response.getHeader("Accept"));
}
+ @Test
+ public void badRequestRequestBody() throws ServletException, IOException {
+ @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() {
+ @Override
+ protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
+ GenericWebApplicationContext wac = new GenericWebApplicationContext();
+ wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestBodyController.class));
+ RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
+ adapterDef.getPropertyValues().addPropertyValue("messageConverters", new MyMessageConverter());
+ wac.registerBeanDefinition("handlerAdapter", adapterDef);
+ wac.refresh();
+ return wac;
+ }
+ };
+ servlet.init(new MockServletConfig());
+
+ MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something");
+ String requestBody = "Hello World";
+ request.setContent(requestBody.getBytes("UTF-8"));
+ request.addHeader("Content-Type", "application/pdf");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
+ }
+
/*
* Controllers
*/
@@ -893,8 +935,7 @@ protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpSer
}
}
-
- /** @noinspection UnusedDeclaration*/
+ /** @noinspection UnusedDeclaration */
private static class BaseController {
@RequestMapping(method = RequestMethod.GET)
@@ -903,7 +944,6 @@ public void myPath2(HttpServletResponse response) throws IOException {
}
}
-
@Controller
private static class MyAdaptedController {
@@ -913,8 +953,10 @@ public void myHandle(HttpServletRequest request, HttpServletResponse response) t
}
@RequestMapping("/myPath2.do")
- public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2,
- @RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1,
+ public void myHandle(@RequestParam("param1") String p1,
+ @RequestParam("param2") int p2,
+ @RequestHeader("header1") long h1,
+ @CookieValue("cookie1") Cookie c1,
HttpServletResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue());
}
@@ -930,7 +972,6 @@ public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) t
}
}
-
@Controller
@RequestMapping("/*.do")
private static class MyAdaptedController2 {
@@ -941,8 +982,11 @@ public void myHandle(HttpServletRequest request, HttpServletResponse response) t
}
@RequestMapping("/myPath2.do")
- public void myHandle(@RequestParam("param1") String p1, int param2, HttpServletResponse response,
- @RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException {
+ public void myHandle(@RequestParam("param1") String p1,
+ int param2,
+ HttpServletResponse response,
+ @RequestHeader("header1") String h1,
+ @CookieValue("cookie1") String c1) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1);
}
@@ -957,13 +1001,15 @@ public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) t
}
}
-
@Controller
private static class MyAdaptedControllerBase<T> {
@RequestMapping("/myPath2.do")
- public void myHandle(@RequestParam("param1") T p1, int param2, @RequestHeader Integer header1,
- @CookieValue int cookie1, HttpServletResponse response) throws IOException {
+ public void myHandle(@RequestParam("param1") T p1,
+ int param2,
+ @RequestHeader Integer header1,
+ @CookieValue int cookie1,
+ HttpServletResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1);
}
@@ -976,7 +1022,6 @@ public void modelAttribute(@RequestParam("param1") T p1, int param2) {
}
}
-
@RequestMapping("/*.do")
private static class MyAdaptedController3 extends MyAdaptedControllerBase<String> {
@@ -986,8 +1031,11 @@ public void myHandle(HttpServletRequest request, HttpServletResponse response) t
}
@Override
- public void myHandle(@RequestParam("param1") String p1, int param2, @RequestHeader Integer header1,
- @CookieValue int cookie1, HttpServletResponse response) throws IOException {
+ public void myHandle(@RequestParam("param1") String p1,
+ int param2,
+ @RequestHeader Integer header1,
+ @CookieValue int cookie1,
+ HttpServletResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1);
}
@@ -1012,7 +1060,6 @@ public void modelAttribute(@RequestParam("param1") String p1, int param2) {
}
}
-
@Controller
@RequestMapping(method = RequestMethod.GET)
private static class EmptyParameterListHandlerMethodController {
@@ -1029,7 +1076,6 @@ public void nonEmptyParameterListHandler(HttpServletResponse response) {
}
}
-
@Controller
public static class MyFormController {
@@ -1042,7 +1088,7 @@ public List<TestBean> getTestBeans() {
}
@RequestMapping("/myPath.do")
- public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) {
+ public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
@@ -1050,7 +1096,6 @@ public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult er
}
}
-
@Controller
public static class MyModelFormController {
@@ -1063,7 +1108,7 @@ public List<TestBean> getTestBeans() {
}
@RequestMapping("/myPath.do")
- public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, Model model) {
+ public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, Model model) {
if (!model.containsAttribute("myKey")) {
model.addAttribute("myKey", "myValue");
}
@@ -1071,13 +1116,13 @@ public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult er
}
}
-
@Controller
private static class MyCommandProvidingFormController<T, TB, TB2> extends MyFormController {
@SuppressWarnings("unused")
@ModelAttribute("myCommand")
- private TestBean createTestBean(@RequestParam T defaultName, Map<String, Object> model,
+ private TestBean createTestBean(@RequestParam T defaultName,
+ Map<String, Object> model,
@RequestParam Date date) {
model.put("myKey", "myOriginalValue");
return new TestBean(defaultName.getClass().getSimpleName() + ":" + defaultName.toString());
@@ -1085,7 +1130,7 @@ private TestBean createTestBean(@RequestParam T defaultName, Map<String, Object>
@Override
@RequestMapping("/myPath.do")
- public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) {
+ public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
return super.myHandle(tb, errors, model);
}
@@ -1110,21 +1155,18 @@ protected TB2 getModelAttr() {
}
}
-
private static class MySpecialArg {
public MySpecialArg(String value) {
}
}
-
@Controller
private static class MyTypedCommandProvidingFormController
extends MyCommandProvidingFormController<Integer, TestBean, ITestBean> {
}
-
@Controller
private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController {
@@ -1138,7 +1180,6 @@ private void initBinder(WebDataBinder binder) {
}
}
-
@Controller
private static class MySpecificBinderInitializingCommandProvidingFormController
extends MyCommandProvidingFormController {
@@ -1155,7 +1196,6 @@ private void initBinder(WebDataBinder binder, String date, @RequestParam("date")
}
}
-
private static class MyWebBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
@@ -1166,7 +1206,6 @@ public void initBinder(WebDataBinder binder, WebRequest request) {
}
}
-
private static class MySpecialArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
@@ -1177,7 +1216,6 @@ public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest
}
}
-
@Controller
@RequestMapping("/myPath.do")
private static class MyParameterDispatchingController {
@@ -1223,7 +1261,6 @@ public void mySurpriseHandle(HttpServletResponse response) throws IOException {
}
}
-
@Controller
@RequestMapping(value = "/myPath.do", params = {"active"})
private static class MyConstrainedParameterDispatchingController {
@@ -1239,14 +1276,12 @@ public void myLangHandle(HttpServletResponse response) throws IOException {
}
}
-
@Controller
@RequestMapping(value = "/*.do", method = RequestMethod.POST, params = "myParam=myValue")
private static class MyPostMethodNameDispatchingController extends MethodNameDispatchingController {
}
-
@Controller
@RequestMapping("/myApp/*")
private static class MyRelativePathDispatchingController {
@@ -1272,7 +1307,6 @@ public void mySurpriseHandle(HttpServletResponse response) throws IOException {
}
}
-
@Controller
private static class MyNullCommandController {
@@ -1287,8 +1321,11 @@ public Principal getPrincipal() {
}
@RequestMapping("/myPath")
- public void handle(@ModelAttribute TestBean testBean, Errors errors, @ModelAttribute TestPrincipal modelPrinc,
- OtherPrincipal requestPrinc, Writer writer) throws IOException {
+ public void handle(@ModelAttribute TestBean testBean,
+ Errors errors,
+ @ModelAttribute TestPrincipal modelPrinc,
+ OtherPrincipal requestPrinc,
+ Writer writer) throws IOException {
assertNull(testBean);
assertNotNull(modelPrinc);
assertNotNull(requestPrinc);
@@ -1298,7 +1335,6 @@ public void handle(@ModelAttribute TestBean testBean, Errors errors, @ModelAttri
}
}
-
private static class TestPrincipal implements Principal {
public String getName() {
@@ -1306,7 +1342,6 @@ public String getName() {
}
}
-
private static class OtherPrincipal implements Principal {
public String getName() {
@@ -1314,7 +1349,6 @@ public String getName() {
}
}
-
private static class TestViewResolver implements ViewResolver {
public View resolveViewName(final String viewName, Locale locale) throws Exception {
@@ -1345,9 +1379,9 @@ public void render(Map model, HttpServletRequest request, HttpServletResponse re
}
List<TestBean> testBeans = (List<TestBean>) model.get("testBeanList");
if (errors.hasFieldErrors("age")) {
- response.getWriter().write(viewName + "-" + tb.getName() + "-" +
- errors.getFieldError("age").getCode() + "-" + testBeans.get(0).getName() + "-" +
- model.get("myKey"));
+ response.getWriter()
+ .write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() +
+ "-" + testBeans.get(0).getName() + "-" + model.get("myKey"));
}
else {
response.getWriter().write(viewName + "-" + tb.getName() + "-" + tb.getAge() + "-" +
@@ -1358,7 +1392,6 @@ public void render(Map model, HttpServletRequest request, HttpServletResponse re
}
}
-
public static class ParentController {
@RequestMapping(method = RequestMethod.GET)
@@ -1366,7 +1399,6 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) {
}
}
-
@Controller
@RequestMapping("/child/test")
public static class ChildController extends ParentController {
@@ -1376,68 +1408,66 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp, @RequestPara
}
}
-
@Controller
public static class RequiredParamController {
@RequestMapping("/myPath.do")
- public void myHandle(@RequestParam(value = "id", required = true) String id,
+ public void myHandle(@RequestParam(value = "id", required = true) int id,
@RequestHeader(value = "header", required = true) String header) {
}
}
-
@Controller
public static class OptionalParamController {
@RequestMapping("/myPath.do")
- public void myHandle(@RequestParam(required = false) String id, @RequestParam(required = false) boolean flag,
- @RequestHeader(value = "header", required = false) String header, HttpServletResponse response)
- throws IOException {
+ public void myHandle(@RequestParam(required = false) String id,
+ @RequestParam(required = false) boolean flag,
+ @RequestHeader(value = "header", required = false) String header,
+ HttpServletResponse response) throws IOException {
response.getWriter().write(String.valueOf(id) + "-" + flag + "-" + String.valueOf(header));
}
}
-
@Controller
public static class DefaultValueParamController {
@RequestMapping("/myPath.do")
public void myHandle(@RequestParam(value = "id", defaultValue = "foo") String id,
- @RequestHeader(defaultValue = "bar") String header, HttpServletResponse response)
- throws IOException {
+ @RequestHeader(defaultValue = "bar") String header,
+ HttpServletResponse response) throws IOException {
response.getWriter().write(String.valueOf(id) + "-" + String.valueOf(header));
}
}
-
@Controller
public static class MethodNotAllowedController {
- @RequestMapping(value="/myPath.do", method = RequestMethod.DELETE)
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.DELETE)
public void delete() {
}
- @RequestMapping(value="/myPath.do", method = RequestMethod.HEAD)
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.HEAD)
public void head() {
}
- @RequestMapping(value="/myPath.do", method = RequestMethod.OPTIONS)
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.OPTIONS)
public void options() {
}
- @RequestMapping(value="/myPath.do", method = RequestMethod.POST)
+
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.POST)
public void post() {
}
- @RequestMapping(value="/myPath.do", method = RequestMethod.PUT)
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.PUT)
public void put() {
}
- @RequestMapping(value="/myPath.do", method = RequestMethod.TRACE)
+ @RequestMapping(value = "/myPath.do", method = RequestMethod.TRACE)
public void trace() {
}
- @RequestMapping(value="/otherPath.do", method = RequestMethod.GET)
+ @RequestMapping(value = "/otherPath.do", method = RequestMethod.GET)
public void get() {
}
}
@@ -1445,7 +1475,6 @@ public void get() {
@Controller
public static class PathOrderingController {
-
@RequestMapping(value = {"/dir/myPath1.do", "/**/*.do"})
public void method1(Writer writer) throws IOException {
writer.write("method1");
@@ -1466,4 +1495,26 @@ public void handle(@RequestBody String body, Writer writer) throws IOException {
}
}
+ public static class MyMessageConverter implements HttpMessageConverter {
+
+ public boolean supports(Class clazz) {
+ return true;
+ }
+
+ public List getSupportedMediaTypes() {
+ return Collections.singletonList(new MediaType("application", "pdf"));
+ }
+
+ public Object read(Class clazz, HttpInputMessage inputMessage)
+ throws IOException, HttpMessageNotReadableException {
+ throw new HttpMessageNotReadableException("Could not read");
+ }
+
+ public void write(Object o, HttpOutputMessage outputMessage)
+ throws IOException, HttpMessageNotWritableException {
+ throw new UnsupportedOperationException("Not implemented");
+ }
+ }
+
+
}
diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
index 331ac63c9e42..df0549ae009f 100644
--- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
+++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java
@@ -5,6 +5,7 @@
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.*;
import org.junit.Test;
@@ -24,9 +25,7 @@
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
-/**
- * @author Arjen Poutsma
- */
+/** @author Arjen Poutsma */
public class UriTemplateServletAnnotationControllerTests {
private DispatcherServlet servlet;
@@ -92,6 +91,16 @@ public void extension() throws Exception {
}
+ @Test
+ public void typeConversionError() throws Exception {
+ initServlet(SimpleUriTemplateController.class);
+
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ servlet.service(request, response);
+ assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
+ }
+
private void initServlet(final Class<?> controllerclass) throws ServletException {
servlet = new DispatcherServlet() {
@Override
|
e14ead510bf4aad803cfdae96ae11cf709a597a2
|
griddynamics$jagger
|
functionality ready. Decisions per metric and per test group are saved
|
p
|
https://github.com/griddynamics/jagger
|
diff --git a/chassis/configuration/configuration/master/master.conf.xml b/chassis/configuration/configuration/master/master.conf.xml
index 4fbfb42f6..ba80f36fd 100644
--- a/chassis/configuration/configuration/master/master.conf.xml
+++ b/chassis/configuration/configuration/master/master.conf.xml
@@ -66,6 +66,7 @@
<property name="databaseValidator" ref="databaseValidator"/>
<property name="metaDataStorage" ref="metaDataStorage"/>
<property name="databaseService" ref="databaseService"/>
+ <property name="decisionMakerDistributionListener" ref="decisionMakerDistributionListener"/>
</bean>
<bean id="distributionStartTimeTimeout" class="com.griddynamics.jagger.util.Timeout">
diff --git a/chassis/configuration/configuration/master/session/default-aggregators.conf.xml b/chassis/configuration/configuration/master/session/default-aggregators.conf.xml
index 820331ca5..0ac55a74f 100644
--- a/chassis/configuration/configuration/master/session/default-aggregators.conf.xml
+++ b/chassis/configuration/configuration/master/session/default-aggregators.conf.xml
@@ -35,6 +35,11 @@
<property name="sessionMetaDataStorage" ref="metaDataStorage"/>
</bean>
+ <!--??? worst case -->
+ <bean id="decisionMakerDistributionListener" class="com.griddynamics.jagger.master.DecisionMakerDistributionListener">
+ <property name="sessionFactory" ref="sessionFactory"/>
+ </bean>
+
<bean id="standardPercentilesGlobal" class="java.util.ArrayList">
<constructor-arg>
<list>
diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java
index 5dbab14fc..bc5b0ca72 100644
--- a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java
+++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java
@@ -2,6 +2,10 @@
import com.griddynamics.jagger.coordinator.NodeContext;
import com.griddynamics.jagger.coordinator.NodeId;
+import com.griddynamics.jagger.dbapi.entity.DecisionPerMetricEntity;
+import com.griddynamics.jagger.dbapi.entity.DecisionPerTaskEntity;
+import com.griddynamics.jagger.dbapi.entity.MetricDescriptionEntity;
+import com.griddynamics.jagger.dbapi.entity.TaskData;
import com.griddynamics.jagger.engine.e1.ProviderUtil;
import com.griddynamics.jagger.engine.e1.collector.limits.*;
import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerInfo;
@@ -15,18 +19,25 @@
import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener;
import com.griddynamics.jagger.engine.e1.sessioncomparation.WorstCaseDecisionMaker;
import com.griddynamics.jagger.master.configuration.Task;
+import org.hibernate.*;
+import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.orm.hibernate3.HibernateCallback;
+import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
+import java.sql.SQLException;
import java.util.*;
-public class DecisionMakerDistributionListener implements DistributionListener {
+public class DecisionMakerDistributionListener extends HibernateDaoSupport implements DistributionListener {
private static final Logger log = LoggerFactory.getLogger(DecisionMakerDistributionListener.class);
private NodeContext nodeContext;
private WorstCaseDecisionMaker worstCaseDecisionMaker = new WorstCaseDecisionMaker();
- public DecisionMakerDistributionListener(NodeContext nodeContext) {
+ public DecisionMakerDistributionListener() {}
+
+ public void setNodeContext(NodeContext nodeContext) {
this.nodeContext = nodeContext;
}
@@ -137,14 +148,20 @@ public void onTaskDistributionCompleted(String sessionId, String taskId, Task ta
}
}
- // call test group listener
+ // Save decisions per metric if there were any
+ if (decisionsPerTest.size() > 0) {
+ saveDecisionsForMetrics(sessionId, taskId, decisionsPerTest);
+ }
+
+ // Call test group listener with basic or customer code
TestGroupDecisionMakerInfo testGroupDecisionMakerInfo =
new TestGroupDecisionMakerInfo((CompositeTask)task,sessionId,decisionsPerTest);
Decision decisionPerTestGroup = decisionMakerListener.onDecisionMaking(testGroupDecisionMakerInfo);
log.info("Decision for test group {} - {}",task.getTaskName(),decisionPerTestGroup);
- //todo ??? JFG_746 save/update decision
+ // Save decisions per test group
+ saveDecisionsForTestGroup(sessionId, taskId, decisionPerTestGroup);
}
}
@@ -153,6 +170,8 @@ private Set<MetricEntity> getMetricsForLimit(Limit limit, Map<String, MetricEnti
String metricId = limit.getMetricName();
Set<MetricEntity> metricsForLimit = new HashSet<MetricEntity>();
+ //??? remove duplicates
+
// Strict matching
if (idToEntity.keySet().contains(metricId)) {
metricsForLimit.add(idToEntity.get(metricId));
@@ -277,5 +296,130 @@ else if (value < limit.getLowerErrorThreshold()*refValue) {
return new DecisionPerLimit(limit,decisionsPerMetric,decisionPerLimit);
}
+
+ private void saveDecisionsForMetrics(String sessionId, String testGroupTaskId, Collection<DecisionPerTest> decisionsPerTest) {
+
+ final List<DecisionPerMetricEntity> decisionPerMetricEntityList = new ArrayList<DecisionPerMetricEntity>();
+
+ Set<MetricDescriptionEntity> metricDescriptionEntitiesPerTest = null;
+ Set<MetricDescriptionEntity> metricDescriptionEntitiesPerTestGroup = null;
+ Long testGroupId = null;
+
+ for (DecisionPerTest decisionPerTest : decisionsPerTest) {
+ Long testId = decisionPerTest.getTestEntity().getId();
+ metricDescriptionEntitiesPerTest = getMetricDescriptionEntitiesPerTest(testId);
+
+ for (DecisionPerLimit decisionPerLimit : decisionPerTest.getDecisionsPerLimit()) {
+ for (DecisionPerMetric decisionPerMetric : decisionPerLimit.getDecisionsPerMetric()) {
+
+ String metricId = decisionPerMetric.getMetricEntity().getMetricId();
+ MetricDescriptionEntity metricDescriptionEntity = findMetricDescriptionByMetricId(metricId,metricDescriptionEntitiesPerTest);
+
+ // metric description belongs to parent (test-group) of the test
+ if (metricDescriptionEntity == null) {
+ if (testGroupId == null) {
+ testGroupId = getTestGroupId(testGroupTaskId,sessionId);
+ metricDescriptionEntitiesPerTestGroup = getMetricDescriptionEntitiesPerTest(testGroupId);
+ }
+ metricDescriptionEntity = findMetricDescriptionByMetricId(metricId, metricDescriptionEntitiesPerTestGroup);
+ }
+
+ if (metricDescriptionEntity != null) {
+ decisionPerMetricEntityList.add(new DecisionPerMetricEntity(metricDescriptionEntity,
+ decisionPerMetric.getDecisionPerMetric().toString()));
+ }
+ else {
+ log.error("Unable to create MetricDescriptionEntity for metricId " + metricId +
+ ", testId " + testId +
+ ", testGroupId" + testGroupId);
+ }
+ }
+ }
+ }
+
+ getHibernateTemplate().execute(new HibernateCallback<Void>() {
+ @Override
+ public Void doInHibernate(Session session) throws HibernateException, SQLException {
+ for (DecisionPerMetricEntity decisionPerMetricEntity : decisionPerMetricEntityList) {
+ session.persist(decisionPerMetricEntity);
+ }
+ session.flush();
+ return null;
+ }
+ });
+
+ }
+
+ private void saveDecisionsForTestGroup(String sessionId, String testGroupTaskId, Decision decisionsPerTestGroup) {
+ TaskData taskData = getTaskData(testGroupTaskId,sessionId);
+ final DecisionPerTaskEntity decisionPerTaskEntity = new DecisionPerTaskEntity(taskData,decisionsPerTestGroup.toString());
+
+ getHibernateTemplate().execute(new HibernateCallback<Void>() {
+ @Override
+ public Void doInHibernate(Session session) throws HibernateException, SQLException {
+ session.persist(decisionPerTaskEntity);
+ session.flush();
+ return null;
+ }
+ });
+
+ }
+
+ private TaskData getTaskData(final String taskId, final String sessionId) {
+ return getHibernateTemplate().execute(new HibernateCallback<TaskData>() {
+ @Override
+ public TaskData doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
+ return (TaskData) session.createQuery("select t from TaskData t where sessionId=? and taskId=?")
+ .setParameter(0, sessionId)
+ .setParameter(1, taskId)
+ .uniqueResult();
+ }
+ });
+ }
+
+ private Long getTestGroupId(final String taskId, final String sessionId) {
+ return getTaskData(taskId, sessionId).getId();
+ }
+
+ private MetricDescriptionEntity findMetricDescriptionByMetricId (String metricId, Collection<MetricDescriptionEntity> metricDescriptionEntities) {
+
+ if (metricDescriptionEntities != null) {
+ for (MetricDescriptionEntity metricDescriptionEntity : metricDescriptionEntities) {
+ if (metricId.equals(metricDescriptionEntity.getMetricId())) {
+ return metricDescriptionEntity;
+ }
+ }
+ }
+
+ return null;
+ }
+
+//???
+// private MetricDescriptionEntity getMetricDescriptionEntity(final String metricId, final Long taskId) {
+// return getHibernateTemplate().execute(new HibernateCallback<MetricDescriptionEntity>() {
+// @Override
+// public MetricDescriptionEntity doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
+// return (MetricDescriptionEntity) session.createQuery("select m from MetricDescriptionEntity m where metricId=? and taskData.id=?")
+// .setParameter(0, metricId)
+// .setParameter(1, taskId)
+// .uniqueResult();
+// }
+// });
+// }
+
+ private Set<MetricDescriptionEntity> getMetricDescriptionEntitiesPerTest(final Long taskId) {
+ return getHibernateTemplate().execute(new HibernateCallback<Set<MetricDescriptionEntity>>() {
+ @Override
+ public Set<MetricDescriptionEntity> doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
+ Set<MetricDescriptionEntity> result = new HashSet<MetricDescriptionEntity>();
+ result.addAll(session.createQuery("select m from MetricDescriptionEntity m where taskData.id=?")
+ .setParameter(0, taskId)
+ .list());
+
+ return result;
+ }
+ });
+ }
+
}
diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java
index 57de9cdcb..4aeddd586 100644
--- a/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java
+++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java
@@ -90,6 +90,7 @@ public class Master implements Runnable {
private SessionMetaDataStorage metaDataStorage;
private DatabaseValidator databaseValidator;
private DatabaseService databaseService;
+ private DecisionMakerDistributionListener decisionMakerDistributionListener;
@Required
@@ -154,6 +155,11 @@ public void setDatabaseService(DatabaseService databaseService) {
this.databaseService = databaseService;
}
+ @Required
+ public void setDecisionMakerDistributionListener(DecisionMakerDistributionListener decisionMakerDistributionListener) {
+ this.decisionMakerDistributionListener = decisionMakerDistributionListener;
+ }
+
@Override
public void run() {
databaseValidator.validate();
@@ -180,7 +186,9 @@ public void run() {
NodeContext context = contextBuilder.build();
// add additional listener to configuration
- configuration.getDistributionListeners().add(new DecisionMakerDistributionListener(context));
+ // done here, because we need to set context
+ decisionMakerDistributionListener.setNodeContext(context);
+ configuration.getDistributionListeners().add(decisionMakerDistributionListener);
Map<NodeType, CountDownLatch> countDownLatchMap = Maps.newHashMap();
CountDownLatch agentCountDownLatch = new CountDownLatch(
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java
index 28a9c4e7e..e58e02aea 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseService.java
@@ -38,12 +38,12 @@ public interface DatabaseService {
* @return list of summary values */
List<MetricDto> getSummaryByMetricNameDto(List<MetricNameDto> metricNames);
- /** Returns test info for specify tests
+ /** Returns test info for specified tests
* @param taskDataDtos - selected tests
* @return map of test info */
Map<TaskDataDto, Map<String, TestInfoDto>> getTestInfoByTaskDataDto(Collection<TaskDataDto> taskDataDtos) throws RuntimeException;
- /** Returns test info for specify tests ids
+ /** Returns test info for specified tests ids
* @param taskIds - selected test ids
* @return map of test info */
Map<Long, Map<String, TestInfoDto>> getTestInfoByTaskIds(Set<Long> taskIds) throws RuntimeException;
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerMetricEntity.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerMetricEntity.java
new file mode 100644
index 000000000..fa64b19a7
--- /dev/null
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerMetricEntity.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved
+ * http://www.griddynamics.com
+ *
+ * This library is free software; you can redistribute it and/or modify it under the terms of
+ * the GNU Lesser General Public License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or any later version.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package com.griddynamics.jagger.dbapi.entity;
+
+import javax.persistence.*;
+
+@Entity
+public class DecisionPerMetricEntity {
+
+ @Id
+ // Identity strategy is not supported by Oracle DB from the box
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column
+ private Long id;
+
+ @OneToOne
+ private MetricDescriptionEntity metricDescriptionEntity;
+
+ @Column
+ private String decision;
+
+ public DecisionPerMetricEntity() {
+ }
+
+ public DecisionPerMetricEntity(MetricDescriptionEntity metricDescriptionEntity, String decision) {
+ this.metricDescriptionEntity = metricDescriptionEntity;
+ this.decision = decision;
+ }
+
+ public MetricDescriptionEntity getMetricDescriptionEntity() {
+ return metricDescriptionEntity;
+ }
+
+ public void setMetricDescriptionEntity(MetricDescriptionEntity metricDescriptionEntity) {
+ this.metricDescriptionEntity = metricDescriptionEntity;
+ }
+
+ public String getDecision() {
+ return decision;
+ }
+
+ public void setDecision(String decision) {
+ this.decision = decision;
+ }
+
+}
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerTaskEntity.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerTaskEntity.java
new file mode 100644
index 000000000..82e7174b7
--- /dev/null
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/entity/DecisionPerTaskEntity.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved
+ * http://www.griddynamics.com
+ *
+ * This library is free software; you can redistribute it and/or modify it under the terms of
+ * the GNU Lesser General Public License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or any later version.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package com.griddynamics.jagger.dbapi.entity;
+
+import javax.persistence.*;
+
+@Entity
+public class DecisionPerTaskEntity {
+
+ @Id
+ // Identity strategy is not supported by Oracle DB from the box
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column
+ private Long id;
+
+ @OneToOne
+ private TaskData taskData;
+
+ @Column
+ private String decision;
+
+ public DecisionPerTaskEntity() {
+ }
+
+ public DecisionPerTaskEntity(TaskData taskData, String decision) {
+ this.taskData = taskData;
+ this.decision = decision;
+ }
+
+ public TaskData getTaskData() {
+ return taskData;
+ }
+
+ public void setTaskData(TaskData taskData) {
+ this.taskData = taskData;
+ }
+
+ public String getDecision() {
+ return decision;
+ }
+
+ public void setDecision(String decision) {
+ this.decision = decision;
+ }
+
+}
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricPlotFetcher.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricPlotFetcher.java
index 5f1043fbf..a7e23bbab 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricPlotFetcher.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricPlotFetcher.java
@@ -25,7 +25,7 @@ protected List<Object[]> getRawData(Set<Long> taskIds, Set<String> metricIds) {
List<Object[]> resultList = new ArrayList<Object[]>();
- Multimap<Long, Long> testGroupMap = fetchUtil.getTestsInTestGroup(taskIds);
+ Multimap<Long, Long> testGroupMap = fetchUtil.getTestGroupIdsByTestIds(taskIds);
if (testGroupMap.isEmpty()) {
log.warn("Could not find testGroupTaskData for workloadTask ids {} ", taskIds);
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricSummaryFetcher.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricSummaryFetcher.java
index ecab15872..494dfa4d2 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricSummaryFetcher.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/fetcher/CustomTestGroupMetricSummaryFetcher.java
@@ -27,7 +27,7 @@ protected List<Object[]> getCustomMetricsDataOldModel(Set<Long> taskIds, Set<Str
@Override
protected List<Object[]> getCustomMetricsDataNewModel(Set<Long> taskIds, Set<String> metricId) {
- Multimap<Long, Long> testGroupMap = fetchUtil.getTestsInTestGroup(taskIds);
+ Multimap<Long, Long> testGroupMap = fetchUtil.getTestGroupIdsByTestIds(taskIds);
List<Object[]> testGroupsSummary = super.getCustomMetricsDataNewModel(testGroupMap.keySet(), metricId);
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricNameProvider.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricNameProvider.java
index d53407700..1afee349c 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricNameProvider.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricNameProvider.java
@@ -150,7 +150,7 @@ private Set<MetricNameDto> getCustomTestGroupMetricsNamesNewModel(List<TaskDataD
try {
Set<Long> taskIds = CommonUtils.getTestsIds(tests);
- Multimap<Long, Long> testGroupMap = fetchUtil.getTestsInTestGroup(taskIds);
+ Multimap<Long, Long> testGroupMap = fetchUtil.getTestGroupIdsByTestIds(taskIds);
List<Object[]> metricDescriptionEntities = getMetricNames(testGroupMap.keySet());
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricPlotNameProvider.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricPlotNameProvider.java
index 29dd1a8b5..0c4af1505 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricPlotNameProvider.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/provider/CustomMetricPlotNameProvider.java
@@ -140,7 +140,7 @@ public Set<MetricNameDto> getTestGroupPlotNamesNewModel(List<TaskDataDto> tests)
try {
Set<Long> testIds = CommonUtils.getTestsIds(tests);
- Multimap<Long, Long> testGroupMap = fetchUtil.getTestsInTestGroup(testIds);
+ Multimap<Long, Long> testGroupMap = fetchUtil.getTestGroupIdsByTestIds(testIds);
List<Object[]> plotNamesNew = getMetricNames(testGroupMap.keySet());
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/util/FetchUtil.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/util/FetchUtil.java
index 193d1bbcb..c5f36b6d8 100644
--- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/util/FetchUtil.java
+++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/util/FetchUtil.java
@@ -23,7 +23,7 @@ public void setEntityManager(EntityManager entityManager) {
/**
* @return multi map <test-group id, tests ids>
*/
- public Multimap<Long, Long> getTestsInTestGroup(Set<Long> taskIds){
+ public Multimap<Long, Long> getTestGroupIdsByTestIds(Set<Long> taskIds){
Multimap<Long, Long> resultMap = HashMultimap.create();
|
b48b41f97dfc0c37251beb07b1924af593bba8e1
|
Vala
|
gsl: Do not use `weak' modifier where it is not applicable
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gsl.vapi b/vapi/gsl.vapi
index 3a384c2f7a..0005d4f425 100644
--- a/vapi/gsl.vapi
+++ b/vapi/gsl.vapi
@@ -527,7 +527,7 @@ namespace Gsl
namespace Error
{
public static void error (string reason, string file, int line, int errno);
- public static weak string strerror (int errno);
+ public static unowned string strerror (int errno);
public static ErrorHandler set_error_handler (ErrorHandler? new_handler);
public static ErrorHandler set_error_handler_off ();
}
|
63ac06a6cd9bd368a81ce78e8afe316aaffd67fa
|
cyberfox$jbidwatcher
|
Split the thumbnail path-related functionality out of the thread that downloads the thumbnails, to clean up another tangle.
git-svn-id: svn://svn.jbidwatcher.com/jbidwatcher/trunk@506 b1acfa68-eb39-11db-b167-a3a8cd6b847e
|
p
|
https://github.com/cyberfox/jbidwatcher
|
diff --git a/src/com/jbidwatcher/app/JBidWatch.java b/src/com/jbidwatcher/app/JBidWatch.java
index 8b0016ea..df2b1bd4 100644
--- a/src/com/jbidwatcher/app/JBidWatch.java
+++ b/src/com/jbidwatcher/app/JBidWatch.java
@@ -518,7 +518,7 @@ public void messageAction(Object deQ) {
MQFactory.getConcrete("Swing").enqueue("LOGINSTATUS " + deQ.toString());
}
});
- ThumbnailManager.start();
+ ThumbnailLoader.start();
inSplash.message("Initializing Scripting");
try {
Scripting.initialize();
diff --git a/src/com/jbidwatcher/auction/AuctionInfo.java b/src/com/jbidwatcher/auction/AuctionInfo.java
index a0eedf34..5aab627f 100644
--- a/src/com/jbidwatcher/auction/AuctionInfo.java
+++ b/src/com/jbidwatcher/auction/AuctionInfo.java
@@ -265,7 +265,7 @@ protected boolean hasThumbnail() {
String imgPath = mThumbnailPath;
if(imgPath == null) {
- imgPath = ThumbnailManager.getValidImagePath(this);
+ imgPath = Thumbnail.getValidImagePath(getIdentifier());
if(imgPath == null) return false;
}
diff --git a/src/com/jbidwatcher/auction/Thumbnail.java b/src/com/jbidwatcher/auction/Thumbnail.java
new file mode 100644
index 00000000..c2195dec
--- /dev/null
+++ b/src/com/jbidwatcher/auction/Thumbnail.java
@@ -0,0 +1,65 @@
+package com.jbidwatcher.auction;
+
+import com.jbidwatcher.util.ByteBuffer;
+import com.jbidwatcher.util.IconFactory;
+import com.jbidwatcher.util.config.JConfig;
+import com.jbidwatcher.util.config.ErrorManagement;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Created by IntelliJ IDEA.
+ * User: Morgan
+ * Date: Jun 19, 2008
+ * Time: 4:58:45 PM
+ *
+ * Utility class to handle the thumbnail files, finding them, saving
+ * them, and loading them.
+ */
+public class Thumbnail {
+ public static String getValidImagePath(String identifier) {
+ return getValidImagePath(identifier, null);
+ }
+
+ static String getValidImagePath(String identifier, ByteBuffer buf) {
+ String outPath = JConfig.queryConfiguration("auctions.savepath");
+ String basePath = outPath + System.getProperty("file.separator") + identifier;
+ String thumbPath = basePath + "_t.jpg";
+ String imgPath = thumbPath;
+ if (buf != null) buf.save(basePath + ".jpg");
+ File f = new File(thumbPath);
+
+ if (!f.exists()) {
+ File img = new File(basePath + ".jpg");
+ if (!img.exists()) { return null; }
+ String badConversionPath = basePath + "_b.jpg";
+ File conversionAttempted = new File(badConversionPath);
+ imgPath = basePath + ".jpg";
+
+ if (!conversionAttempted.exists()) {
+ String maxWidthString = JConfig.queryConfiguration("thumbnail.maxWidth", "256");
+ String prefWidthString = JConfig.queryConfiguration("thumbnail.prefWidth", "128");
+ String maxHeightString = JConfig.queryConfiguration("thumbnail.maxHeight", "256");
+ String prefHeightString = JConfig.queryConfiguration("thumbnail.prefWidth", "128");
+ int maxWidth = Integer.parseInt(maxWidthString);
+ int prefWidth = Integer.parseInt(prefWidthString);
+ int maxHeight = Integer.parseInt(maxHeightString);
+ int prefHeight = Integer.parseInt(prefHeightString);
+ if (IconFactory.resizeImage(imgPath, thumbPath, maxWidth, prefWidth, maxHeight, prefHeight)) {
+ imgPath = thumbPath;
+ } else {
+ try {
+ // Create a mark file that notes that the thumbnail was
+ // attempted to be created, and failed. It'll default to
+ // using the standard image file.
+ conversionAttempted.createNewFile();
+ } catch (IOException e) {
+ ErrorManagement.handleException("Can't create 'bad' lock file.", e);
+ }
+ }
+ }
+ }
+ return imgPath;
+ }
+}
diff --git a/src/com/jbidwatcher/auction/ThumbnailLoader.java b/src/com/jbidwatcher/auction/ThumbnailLoader.java
new file mode 100644
index 00000000..c5f87f79
--- /dev/null
+++ b/src/com/jbidwatcher/auction/ThumbnailLoader.java
@@ -0,0 +1,56 @@
+package com.jbidwatcher.auction;
+/*
+ * Copyright (c) 2000-2007, CyberFOX Software, Inc. All Rights Reserved.
+ *
+ * Developed by mrs (Morgan Schweers)
+ */
+
+import com.jbidwatcher.util.config.JConfig;
+import com.jbidwatcher.util.queue.MQFactory;
+import com.jbidwatcher.util.queue.MessageQueue;
+import com.jbidwatcher.util.http.Http;
+import com.jbidwatcher.util.ByteBuffer;
+
+import java.net.*;
+
+/** @noinspection MagicNumber,Singleton*/
+public class ThumbnailLoader implements MessageQueue.Listener {
+ private static ThumbnailLoader sInstance = null;
+ private ThumbnailLoader() { }
+
+ public void messageAction(Object deQ) {
+ AuctionInfo ai = (AuctionInfo) deQ;
+
+ ByteBuffer thumbnail = ai.getSiteThumbnail();
+ // eBay has started including a 64x64 image instead of the 96x96 ones they used to have,
+ // but it's named '*6464.jpg' instead of '*.jpg'.
+ if(thumbnail == null) thumbnail = ai.getAlternateSiteThumbnail();
+ // If we retrieved 'something', but it was 0 bytes long, it's not a thumbnail.
+ if(thumbnail != null && thumbnail.getLength() == 0) thumbnail = null;
+
+ String imgPath = Thumbnail.getValidImagePath(ai.getIdentifier(), thumbnail);
+
+ ai.setThumbnail(imgPath);
+ }
+
+ public static ByteBuffer downloadThumbnail(URL img) {
+ ByteBuffer tmpThumb = Http.getURL(img);
+ // There's a specific image which is just 'click here to
+ // view item'. Boring, and misleading.
+ if(tmpThumb.getCRC() == 0xAEF9E727 ||
+ tmpThumb.getCRC() == 0x3D7BF54E ||
+ tmpThumb.getCRC() == 0x076AE9FB ||
+ tmpThumb.getCRC() == 0x0E1AE309 ||
+ tmpThumb.getCRC() == Long.parseLong(JConfig.queryConfiguration("thumbnail.crc", "0"), 16) ||
+ tmpThumb.getCRC() == 0x5DAB591F) {
+ tmpThumb = null;
+ }
+ return tmpThumb;
+ }
+
+ public static void start() {
+ if(sInstance == null) {
+ MQFactory.getConcrete("thumbnail").registerListener(sInstance = new ThumbnailLoader());
+ }
+ }
+}
diff --git a/src/com/jbidwatcher/auction/ThumbnailManager.java b/src/com/jbidwatcher/auction/ThumbnailManager.java
deleted file mode 100644
index bb999def..00000000
--- a/src/com/jbidwatcher/auction/ThumbnailManager.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package com.jbidwatcher.auction;
-/*
- * Copyright (c) 2000-2007, CyberFOX Software, Inc. All Rights Reserved.
- *
- * Developed by mrs (Morgan Schweers)
- */
-
-import com.jbidwatcher.util.config.JConfig;
-import com.jbidwatcher.util.config.ErrorManagement;
-import com.jbidwatcher.util.queue.MQFactory;
-import com.jbidwatcher.util.queue.MessageQueue;
-import com.jbidwatcher.util.http.Http;
-import com.jbidwatcher.util.ByteBuffer;
-import com.jbidwatcher.util.IconFactory;
-
-import java.net.*;
-import java.io.File;
-import java.io.IOException;
-
-/** @noinspection MagicNumber,Singleton*/
-public class ThumbnailManager implements MessageQueue.Listener {
- private static ThumbnailManager sInstance = null;
- private ThumbnailManager() { }
-
- public void messageAction(Object deQ) {
- AuctionInfo ai = (AuctionInfo) deQ;
-
- ByteBuffer thumbnail = ai.getSiteThumbnail();
- // eBay has started including a 64x64 image instead of the 96x96 ones they used to have,
- // but it's named '*6464.jpg' instead of '*.jpg'.
- if(thumbnail == null) thumbnail = ai.getAlternateSiteThumbnail();
- // If we retrieved 'something', but it was 0 bytes long, it's not a thumbnail.
- if(thumbnail != null && thumbnail.getLength() == 0) thumbnail = null;
-
- setThumbnail(ai, thumbnail);
- }
-
- public static void setThumbnail(AuctionInfo ai, ByteBuffer b) {
- String imgPath = getValidImagePath(ai, b);
-
- ai.setThumbnail(imgPath);
- }
-
- public static ByteBuffer downloadThumbnail(URL img) {
- ByteBuffer tmpThumb = Http.getURL(img);
- // There's a specific image which is just 'click here to
- // view item'. Boring, and misleading.
- if(tmpThumb.getCRC() == 0xAEF9E727 ||
- tmpThumb.getCRC() == 0x3D7BF54E ||
- tmpThumb.getCRC() == 0x076AE9FB ||
- tmpThumb.getCRC() == 0x0E1AE309 ||
- tmpThumb.getCRC() == Long.parseLong(JConfig.queryConfiguration("thumbnail.crc", "0"), 16) ||
- tmpThumb.getCRC() == 0x5DAB591F) {
- tmpThumb = null;
- }
- return tmpThumb;
- }
-
- public static String getValidImagePath(AuctionInfo ai) {
- return getValidImagePath(ai, null);
- }
-
- private static String getValidImagePath(AuctionInfo ai, ByteBuffer buf) {
- String outPath = JConfig.queryConfiguration("auctions.savepath");
- String basePath = outPath + System.getProperty("file.separator") + ai.getIdentifier();
- String thumbPath = basePath + "_t.jpg";
- String imgPath = thumbPath;
- if (buf != null) buf.save(basePath + ".jpg");
- File f = new File(thumbPath);
-
- if (!f.exists()) {
- File img = new File(basePath + ".jpg");
- if (!img.exists()) { return null; }
- String badConversionPath = basePath + "_b.jpg";
- File conversionAttempted = new File(badConversionPath);
- imgPath = basePath + ".jpg";
-
- if (!conversionAttempted.exists()) {
- String maxWidthString = JConfig.queryConfiguration("thumbnail.maxWidth", "256");
- String prefWidthString = JConfig.queryConfiguration("thumbnail.prefWidth", "128");
- String maxHeightString = JConfig.queryConfiguration("thumbnail.maxHeight", "256");
- String prefHeightString = JConfig.queryConfiguration("thumbnail.prefWidth", "128");
- int maxWidth = Integer.parseInt(maxWidthString);
- int prefWidth = Integer.parseInt(prefWidthString);
- int maxHeight = Integer.parseInt(maxHeightString);
- int prefHeight = Integer.parseInt(prefHeightString);
- if (IconFactory.resizeImage(imgPath, thumbPath, maxWidth, prefWidth, maxHeight, prefHeight)) {
- imgPath = thumbPath;
- } else {
- try {
- // Create a mark file that notes that the thumbnail was
- // attempted to be created, and failed. It'll default to
- // using the standard image file.
- conversionAttempted.createNewFile();
- } catch (IOException e) {
- ErrorManagement.handleException("Can't create 'bad' lock file.", e);
- }
- }
- }
- }
- return imgPath;
- }
-
- public static void start() {
- if(sInstance == null) {
- MQFactory.getConcrete("thumbnail").registerListener(sInstance = new ThumbnailManager());
- }
- }
-}
diff --git a/src/com/jbidwatcher/auction/server/ebay/ebayAuction.java b/src/com/jbidwatcher/auction/server/ebay/ebayAuction.java
index 16121e15..57c5f173 100644
--- a/src/com/jbidwatcher/auction/server/ebay/ebayAuction.java
+++ b/src/com/jbidwatcher/auction/server/ebay/ebayAuction.java
@@ -2,7 +2,7 @@
import com.jbidwatcher.auction.AuctionEntry;
import com.jbidwatcher.auction.SpecificAuction;
-import com.jbidwatcher.auction.ThumbnailManager;
+import com.jbidwatcher.auction.ThumbnailLoader;
import com.jbidwatcher.auction.server.AuctionServer;
import com.jbidwatcher.util.config.*;
import com.jbidwatcher.util.Externalized;
@@ -855,7 +855,7 @@ private ByteBuffer getThumbnailById(String id) {
private ByteBuffer getThumbnailByURL(String url) {
ByteBuffer tmpThumb;
try {
- tmpThumb = ThumbnailManager.downloadThumbnail(new URL(url));
+ tmpThumb = ThumbnailLoader.downloadThumbnail(new URL(url));
} catch(Exception ignored) {
tmpThumb = null;
}
|
5dde44de84cc90ad8f8fe554deaa64597e54ab64
|
Valadoc
|
gir-importer: Add support for <instance-parameter>
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/api/girsourcecomment.vala b/src/libvaladoc/api/girsourcecomment.vala
index e554092386..77bfb5f7a8 100644
--- a/src/libvaladoc/api/girsourcecomment.vala
+++ b/src/libvaladoc/api/girsourcecomment.vala
@@ -30,6 +30,7 @@ using Gee;
public class Valadoc.Api.GirSourceComment : SourceComment {
private Map<string, SourceComment> parameters = new HashMap<string, SourceComment> ();
+ public string? instance_param_name { set; get; }
public SourceComment return_comment { set; get; }
public MapIterator<string, SourceComment> parameter_iterator () {
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index 7b97bef655..5e0ce5ba8c 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -279,6 +279,12 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
}
taglet.parameter_name = iter.get_key ();
+
+ if (taglet.parameter_name == gir_comment.instance_param_name) {
+ taglet.parameter_name = "this";
+ taglet.is_c_self_param = true;
+ }
+
comment.taglets.add (taglet);
}
@@ -1718,32 +1724,39 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
run.content.add (this.create_type_link (current.content));
next ();
} else if (current.type == TokenType.GTKDOC_PARAM) {
- string? param_array_name;
- bool is_return_type_len;
- string? param_name;
-
- string? cname = resolve_parameter_ctype (current.content, out param_name, out param_array_name, out is_return_type_len);
- Run current_run = factory.create_run (Run.Style.MONOSPACED);
- run.content.add (current_run);
-
- if (is_return_type_len) {
- Run keyword_run = factory.create_run (Run.Style.LANG_KEYWORD);
- keyword_run.content.add (factory.create_text ("return"));
- current_run.content.add (keyword_run);
-
- current_run.content.add (factory.create_text (".length"));
- } else if (param_array_name != null) {
- current_run.content.add (factory.create_text (param_array_name + ".length"));
+ if (current.content == instance_param_name) {
+ Content.Run keyword_run = factory.create_run (Content.Run.Style.LANG_KEYWORD);
+ Content.Text text = factory.create_text ("this");
+ keyword_run.content.add (text);
+ run.content.add (keyword_run);
} else {
- current_run.content.add (factory.create_text (param_name));
- }
-
- if (cname != null) {
- run.content.add (factory.create_text ("."));
-
- Taglets.Link link = factory.create_taglet ("link") as Taglets.Link;
- link.symbol_name = cname;
- run.content.add (link);
+ string? param_array_name;
+ bool is_return_type_len;
+ string? param_name;
+
+ string? cname = resolve_parameter_ctype (current.content, out param_name, out param_array_name, out is_return_type_len);
+ Run current_run = factory.create_run (Run.Style.MONOSPACED);
+ run.content.add (current_run);
+
+ if (is_return_type_len) {
+ Run keyword_run = factory.create_run (Run.Style.LANG_KEYWORD);
+ keyword_run.content.add (factory.create_text ("return"));
+ current_run.content.add (keyword_run);
+
+ current_run.content.add (factory.create_text (".length"));
+ } else if (param_array_name != null) {
+ current_run.content.add (factory.create_text (param_array_name + ".length"));
+ } else {
+ current_run.content.add (factory.create_text (param_name));
+ }
+
+ if (cname != null) {
+ run.content.add (factory.create_text ("."));
+
+ Taglets.Link link = factory.create_taglet ("link") as Taglets.Link;
+ link.symbol_name = cname;
+ run.content.add (link);
+ }
}
next ();
} else if (current.type == TokenType.GTKDOC_SIGNAL) {
diff --git a/src/libvaladoc/importer/girdocumentationimporter.vala b/src/libvaladoc/importer/girdocumentationimporter.vala
index 73d7218428..02f9e85ab9 100644
--- a/src/libvaladoc/importer/girdocumentationimporter.vala
+++ b/src/libvaladoc/importer/girdocumentationimporter.vala
@@ -663,6 +663,25 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
start_element ("parameters");
next ();
+ if (current_token == MarkupTokenType.START_ELEMENT && reader.name == "instance-parameter") {
+ string instance_param_name = reader.get_attribute ("name");
+ next ();
+
+ Api.SourceComment? param_comment = parse_doc ();
+ parse_type (null);
+ end_element ("instance-parameter");
+
+ if (param_comment != null) {
+ if (comment == null) {
+ comment = new Api.GirSourceComment ("", file, begin.line, begin.column,
+ end.line, end.column);
+ }
+
+ comment.add_parameter_content (instance_param_name, param_comment);
+ comment.instance_param_name = instance_param_name;
+ }
+ }
+
for (int pcount = 0; current_token == MarkupTokenType.START_ELEMENT; pcount++) {
Api.SourceComment? param_comment;
int array_length_pos;
@@ -700,6 +719,7 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter {
attach_comment (c_identifier, comment, param_names, destroy_notifies, closures,
array_lengths, array_length_ret);
+
end_element (element_name);
}
diff --git a/src/libvaladoc/taglets/tagletparam.vala b/src/libvaladoc/taglets/tagletparam.vala
index 1fa30072a2..b2a42be3cd 100644
--- a/src/libvaladoc/taglets/tagletparam.vala
+++ b/src/libvaladoc/taglets/tagletparam.vala
@@ -32,6 +32,8 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
public int position { private set; get; default = -1; }
+ public bool is_c_self_param { internal set; get; }
+
public Rule? get_parser_rule (Rule run_rule) {
return Rule.seq ({
Rule.option ({ Rule.many ({ TokenType.SPACE }) }),
@@ -105,7 +107,7 @@ public class Valadoc.Taglets.Param : InlineContent, Taglet, Block {
if (is_implicit) {
reporter.simple_note ("%s: %s: @param: warning: Implicit parameter `%s' exposed in documentation",
file_path, container.get_full_name (), parameter_name);
- } else {
+ } else if (!is_c_self_param) {
reporter.simple_warning ("%s: %s: @param: warning: Unknown parameter `%s'",
file_path, container.get_full_name (), parameter_name);
}
|
cb8a374e5de0c186cb28258ff5124d7d8bdb5ff0
|
internetarchive$heritrix3
|
[HER-1636] H3: Failed get of replay char sequence due the OutOfMemoryError: Map failed (port HER-1482)
(from nlevitt's H2 commit message:)
* InMemoryReplayCharSequence.java
new, simple ReplayCharSequence that supports any encoding, keeping everything in memory
* GenericReplayCharSequence.java
If the encoding supports random access, memory maps the backing file directly; otherwise decodes to UTF-16 and maps that. Supports the first Integer.MAX_VALUE bytes of the file. Maps up to 64M; moves the map around as necessary for larger files.
* Latin1ByteReplayCharSequence.java
removed, functionality split between InMemoryReplayCharSequence and GenericReplayCharSequence
* ReplayCharSequenceTest.java
xestHugeReplayCharSequence() - uncomment to test a huge replay char sequence
testReplayCharSequenceByteToStringOverflow() - test both UTF-8 and windows-1252
* RecordingOutputStream.java
use the new ReplayCharSequences
|
p
|
https://github.com/internetarchive/heritrix3
|
diff --git a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
index b65a3574d..bf0a2fc39 100644
--- a/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
+++ b/commons/src/main/java/org/archive/io/GenericReplayCharSequence.java
@@ -23,6 +23,7 @@
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -30,56 +31,31 @@
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
+import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.text.NumberFormat;
+import java.util.logging.Level;
import java.util.logging.Logger;
-import org.archive.util.FileUtils;
+import org.archive.util.DevUtils;
/**
- * Provides a (Replay)CharSequence view on recorded streams (a prefix
- * buffer and overflow backing file) that can handle streams of multibyte
- * characters.
+ * (Replay)CharSequence view on recorded streams.
*
- * For better performance on ISO-8859-1 text, use
- * {@link Latin1ByteReplayCharSequence}.
- *
- * <p>Call close on this class when done so can clean up resources.
+ * For small streams, use {@link InMemoryReplayCharSequence}.
*
- * <p>Implementation currently works by checking to see if content to read
- * all fits the in-memory buffer. If so, we decode into a CharBuffer and
- * keep this around for CharSequence operations. This CharBuffer is
- * discarded on close.
- *
- * <p>If content length is greater than in-memory buffer, we decode the
- * buffer plus backing file into a new file named for the backing file w/
- * a suffix of the encoding we write the file as. We then run w/ a
- * memory-mapped CharBuffer against this file to implement CharSequence.
- * Reasons for this implemenation are that CharSequence wants to return the
- * length of the CharSequence.
- *
- * <p>Obvious optimizations would keep around decodings whether the
- * in-memory decoded buffer or the file of decodings written to disk but the
- * general usage pattern processing URIs is that the decoding is used by one
- * processor only. Also of note, files usually fit into the in-memory
- * buffer.
- *
- * <p>We might also be able to keep up 3 windows that moved across the file
- * decoding a window at a time trying to keep one of the buffers just in
- * front of the regex processing returning it a length that would be only
- * the length of current position to end of current block or else the length
- * could be got by multipling the backing files length by the decoders'
- * estimate of average character size. This would save us writing out the
- * decoded file. We'd have to do the latter for files that are
- * > Integer.MAX_VALUE.
+ * <p>Call {@link close()} on this class when done to clean up resources.
*
* @author stack
+ * @author nlevitt
* @version $Revision$, $Date$
*/
public class GenericReplayCharSequence implements ReplayCharSequence {
- protected static Logger logger =
- Logger.getLogger(GenericReplayCharSequence.class.getName());
-
+ protected static Logger logger = Logger
+ .getLogger(GenericReplayCharSequence.class.getName());
+
/**
* Name of the encoding we use writing out concatenated decoded prefix
* buffer and decoded backing file.
@@ -92,12 +68,47 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
*/
private static final String WRITE_ENCODING = "UTF-16BE";
+ private static final long MAP_MAX_BYTES = 64 * 1024 * 1024; // 64M
+
/**
- * CharBuffer of decoded content.
- *
- * Content of this buffer is unicode.
+ * When the memory map moves away from the beginning of the file
+ * (to the "right") in order to reach a certain index, it will
+ * map up to this many bytes preceding (to the left of) the target character.
+ * Consequently it will map up to
+ * <code>MAP_MAX_BYTES - MAP_TARGET_LEFT_PADDING</code>
+ * bytes to the right of the target.
+ */
+ private static final long MAP_TARGET_LEFT_PADDING_BYTES = (long) (MAP_MAX_BYTES * 0.2);
+
+ /**
+ * Total length of character stream to replay minus the HTTP headers
+ * if present.
+ *
+ * If the backing file is larger than <code>Integer.MAX_VALUE</code> (i.e. 2gb),
+ * only the first <code>Integer.MAX_VALUE</code> characters are available through this API.
+ * We're overriding <code>java.lang.CharSequence</code> so that we can use
+ * <code>java.util.regex</code> directly on the data, and the <code>CharSequence</code>
+ * API uses <code>int</code> for the length and index.
+ */
+ protected int length;
+
+ /**
+ * Byte offset into the file where the memory mapped portion begins.
*/
- private CharBuffer content = null;
+ private long mapByteOffset;
+
+ // XXX do we need to keep the input stream around?
+ private FileInputStream backingFileIn = null;
+
+ private FileChannel backingFileChannel = null;
+
+ private long bytesPerChar;
+
+ private ByteBuffer mappedBuffer = null;
+
+ private CharsetDecoder decoder = null;
+
+ private ByteBuffer tempBuf = null;
/**
* File that has decoded content.
@@ -106,9 +117,15 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
*/
private File decodedFile = null;
+ /*
+ * This portion of the CharSequence precedes what's in the backing file. In
+ * cases where we decodeToFile(), this is always empty, because we decode
+ * the entire input stream.
+ */
+ private CharBuffer prefixBuffer = null;
/**
- * Constructor for all in-memory operation.
+ * Constructor.
*
* @param buffer In-memory buffer of recordings prefix. We read from
* here first and will only go to the backing file if <code>size</code>
@@ -116,225 +133,257 @@ public class GenericReplayCharSequence implements ReplayCharSequence {
* @param size Total size of stream to replay in bytes. Used to find
* EOS. This is total length of content including HTTP headers if
* present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
+ * @param contentReplayInputStream inputStream of content
+ * @param charsetName Encoding to use reading the passed prefix
+ * buffer and backing file. For now, should be java canonical name for the
+ * encoding. Must not be null.
* @param backingFilename Path to backing file with content in excess of
* whats in <code>buffer</code>.
- * @param encoding Encoding to use reading the passed prefix buffer and
- * backing file. For now, should be java canonical name for the
- * encoding. (If null is passed, we will default to
- * ByteReplayCharSequence).
- *
- * @throws IOException
- */
- public GenericReplayCharSequence(byte[] buffer, long size,
- long responseBodyStart, String encoding)
- throws IOException {
- super();
- this.content = decodeInMemory(buffer, size, responseBodyStart,
- encoding);
- }
-
- /**
- * Constructor for overflow-to-disk-file operation.
- *
- * @param contentReplayInputStream inputStream of content
- * @param backingFilename hint for name of temp file
- * @param characterEncoding Encoding to use reading the stream.
- * For now, should be java canonical name for the
- * encoding.
*
* @throws IOException
*/
public GenericReplayCharSequence(
- ReplayInputStream contentReplayInputStream,
- String backingFilename,
- String characterEncoding)
- throws IOException {
+ ReplayInputStream contentReplayInputStream, String backingFilename,
+ String charsetName) throws IOException {
super();
- this.content = decodeToFile(contentReplayInputStream,
- backingFilename, characterEncoding);
+ logger.info("new GenericReplayCharSequence() characterEncoding="
+ + charsetName + " backingFilename=" + backingFilename);
+
+ Charset charset = Charset.forName(charsetName);
+ if (charset.newEncoder().maxBytesPerChar() == 1.0) {
+ logger.info("charset=" + charsetName
+ + ": supports random access, using backing file directly");
+ this.bytesPerChar = 1;
+ this.backingFileIn = new FileInputStream(backingFilename);
+ this.decoder = charset.newDecoder();
+ this.prefixBuffer = this.decoder.decode(
+ ByteBuffer.wrap(contentReplayInputStream.getBuffer()));
+ } else {
+ logger.info("charset=" + charsetName
+ + ": may not support random access, decoding to separate file");
+
+ // decodes only up to Integer.MAX_VALUE characters
+ decodeToFile(contentReplayInputStream, backingFilename, charsetName);
+
+ this.bytesPerChar = 2;
+ this.backingFileIn = new FileInputStream(decodedFile);
+ this.decoder = Charset.forName(WRITE_ENCODING).newDecoder();
+ this.prefixBuffer = CharBuffer.wrap("");
+ }
+
+ this.tempBuf = ByteBuffer.wrap(new byte[(int) this.bytesPerChar]);
+ this.backingFileChannel = backingFileIn.getChannel();
+
+ // we only support the first Integer.MAX_VALUE characters
+ long wouldBeLength = prefixBuffer.limit() + backingFileChannel.size() / bytesPerChar;
+ if (wouldBeLength <= Integer.MAX_VALUE) {
+ this.length = (int) wouldBeLength;
+ } else {
+ logger.warning("input stream is longer than Integer.MAX_VALUE="
+ + NumberFormat.getInstance().format(Integer.MAX_VALUE)
+ + " characters -- only first "
+ + NumberFormat.getInstance().format(Integer.MAX_VALUE)
+ + " are accessible through this GenericReplayCharSequence");
+ this.length = Integer.MAX_VALUE;
+ }
+
+ this.mapByteOffset = 0;
+ updateMemoryMappedBuffer();
+ }
+
+ private void updateMemoryMappedBuffer() {
+ long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
+ long mapSize = Math.min(fileLength * bytesPerChar - mapByteOffset, MAP_MAX_BYTES);
+ logger.fine("updateMemoryMappedBuffer: mapOffset="
+ + NumberFormat.getInstance().format(mapByteOffset)
+ + " mapSize=" + NumberFormat.getInstance().format(mapSize));
+ try {
+ System.gc();
+ System.runFinalization();
+ // TODO: Confirm the READ_ONLY works. I recall it not working.
+ // The buffers seem to always say that the buffer is writable.
+ mappedBuffer = backingFileChannel.map(
+ FileChannel.MapMode.READ_ONLY, mapByteOffset, mapSize)
+ .asReadOnlyBuffer();
+ } catch (IOException e) {
+ // TODO convert this to a runtime error?
+ DevUtils.logger.log(Level.SEVERE,
+ " backingFileChannel.map() mapByteOffset=" + mapByteOffset
+ + " mapSize=" + mapSize + "\n" + "decodedFile="
+ + decodedFile + " length=" + length + "\n"
+ + DevUtils.extraInfo(), e);
+ throw new RuntimeException(e);
+ }
}
/**
- * Decode passed buffer and backing file into a CharBuffer.
- *
- * This method writes a new file made of the decoded concatenation of
- * the in-memory prefix buffer and the backing file. Returns a
- * charSequence view onto this new file.
- *
- * @param buffer In-memory buffer of recordings prefix. We read from
- * here first and will only go to the backing file if <code>size</code>
- * requested is greater than <code>buffer.length</code>.
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
- * @param backingFilename Path to backing file with content in excess of
- * whats in <code>buffer</code>.
- * @param encoding Encoding to use reading the passed prefix buffer and
- * backing file. For now, should be java canonical name for the
- * encoding. (If null is passed, we will default to
- * ByteReplayCharSequence).
- *
- * @return A CharBuffer view on decodings of the contents of passed
- * buffer.
+ * Converts the first <code>Integer.MAX_VALUE</code> characters from the
+ * file <code>backingFilename</code> from encoding <code>encoding</code> to
+ * encoding <code>WRITE_ENCODING</code> and saves as
+ * <code>this.decodedFile</code>, which is named <code>backingFilename
+ * + "." + WRITE_ENCODING</code>.
+ *
* @throws IOException
*/
- private CharBuffer decodeToFile(ReplayInputStream inStream,
- String backingFilename, String encoding)
- throws IOException {
+ private void decodeToFile(ReplayInputStream inStream,
+ String backingFilename, String encoding) throws IOException {
- CharBuffer charBuffer = null;
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ inStream, encoding));
+
+ this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING);
+
+ logger.info("decodeToFile: backingFilename=" + backingFilename
+ + " encoding=" + encoding + " decodedFile=" + decodedFile);
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(inStream,encoding));
-
- File backingFile = new File(backingFilename);
- this.decodedFile = File.createTempFile(
- backingFile.getName(), WRITE_ENCODING, backingFile.getParentFile());
FileOutputStream fos;
- fos = new FileOutputStream(this.decodedFile);
-
- BufferedWriter writer = new BufferedWriter(
- new OutputStreamWriter(
- fos,
- WRITE_ENCODING));
+ try {
+ fos = new FileOutputStream(this.decodedFile);
+ } catch (FileNotFoundException e) {
+ // Windows workaround attempt
+ System.gc();
+ System.runFinalization();
+ this.decodedFile = new File(decodedFile.getAbsolutePath()+".win");
+ logger.info("Windows 'file with a user-mapped section open' "
+ + "workaround gc/finalization/name-extension performed.");
+ // try again
+ fos = new FileOutputStream(this.decodedFile);
+ }
+ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,
+ WRITE_ENCODING));
int c;
- while((c = reader.read())>=0) {
+ long count = 0;
+ while ((c = reader.read()) >= 0 && count < Integer.MAX_VALUE) {
writer.write(c);
+ count++;
+ if (count % 100000000 == 0) {
+ logger.fine("wrote " + count + " characters so far...");
+ }
}
writer.close();
-
- charBuffer = getReadOnlyMemoryMappedBuffer(this.decodedFile).
- asCharBuffer();
- return charBuffer;
+ logger.info("decodeToFile: wrote " + count + " characters to "
+ + decodedFile);
}
/**
- * Decode passed buffer into a CharBuffer.
- *
- * This method decodes a memory buffer returning a memory buffer.
- *
- * @param buffer In-memory buffer of recordings prefix. We read from
- * here first and will only go to the backing file if <code>size</code>
- * requested is greater than <code>buffer.length</code>.
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
- * @param encoding Encoding to use reading the passed prefix buffer and
- * backing file. For now, should be java canonical name for the
- * encoding. (If null is passed, we will default to
- * ByteReplayCharSequence).
- *
- * @return A CharBuffer view on decodings of the contents of passed
- * buffer.
- */
- private CharBuffer decodeInMemory(byte[] buffer, long size,
- long responseBodyStart, String encoding)
- {
- ByteBuffer bb = ByteBuffer.wrap(buffer);
- // Move past the HTTP header if present.
- bb.position((int)responseBodyStart);
- // Set the end-of-buffer to be end-of-content.
- bb.limit((int)size);
- return (Charset.forName(encoding)).decode(bb).asReadOnlyBuffer();
- }
-
- /**
- * Create read-only memory-mapped buffer onto passed file.
- *
- * @param file File to get memory-mapped buffer on.
- * @return Read-only memory-mapped ByteBuffer view on to passed file.
- * @throws IOException
+ * Get character at passed absolute position.
+ * @param index Index into content
+ * @return Character at offset <code>index</code>.
*/
- private ByteBuffer getReadOnlyMemoryMappedBuffer(File file)
- throws IOException {
+ public char charAt(int index) {
+ if (index < 0 || index >= this.length()) {
+ throw new IndexOutOfBoundsException("index=" + index
+ + " - should be between 0 and length()=" + this.length());
+ }
- ByteBuffer bb = null;
- FileInputStream in = null;
- FileChannel c = null;
- assert file.exists(): "No file " + file.getAbsolutePath();
+ // is it in the buffer
+ if (index < prefixBuffer.limit()) {
+ return prefixBuffer.get(index);
+ }
- try {
- in = new FileInputStream(file);
- c = in.getChannel();
- // TODO: Confirm the READ_ONLY works. I recall it not working.
- // The buffers seem to always say that the buffer is writeable.
- bb = c.map(FileChannel.MapMode.READ_ONLY, 0, c.size()).
- asReadOnlyBuffer();
+ // otherwise we gotta get it from disk via memory map
+ long fileIndex = (long) index - (long) prefixBuffer.limit();
+ long fileLength = (long) this.length() - (long) prefixBuffer.limit(); // in characters
+ if (fileIndex * bytesPerChar < mapByteOffset
+ || fileIndex * bytesPerChar - mapByteOffset >= mappedBuffer.limit()) {
+ // fault
+ /*
+ * mapByteOffset is bounded by 0 and file size +/- size of the map,
+ * and starts as close to <code>fileIndex -
+ * MAP_TARGET_LEFT_PADDING_BYTES</code> as it can while also not
+ * being smaller than it needs to be.
+ */
+ mapByteOffset = Math.max(0, fileIndex * bytesPerChar - MAP_TARGET_LEFT_PADDING_BYTES);
+ mapByteOffset = Math.min(mapByteOffset, fileLength * bytesPerChar - MAP_MAX_BYTES);
+ updateMemoryMappedBuffer();
}
- finally {
- if (c != null && c.isOpen()) {
- c.close();
- }
- if (in != null) {
- in.close();
- }
+ // CharsetDecoder always decodes up to the end of the ByteBuffer, so we
+ // create a new ByteBuffer with only the bytes we're interested in.
+ mappedBuffer.position((int) (fileIndex * bytesPerChar - mapByteOffset));
+ mappedBuffer.get(tempBuf.array());
+ tempBuf.position(0); // decoder starts at this position
+
+ try {
+ CharBuffer cbuf = decoder.decode(tempBuf);
+ return cbuf.get();
+ } catch (CharacterCodingException e) {
+ logger.warning("unable to get character at index=" + index + " (fileIndex=" + fileIndex + "): " + e);
+ // U+FFFD REPLACEMENT CHARACTER --
+ // "used to replace an incoming character whose value is unknown or unrepresentable in Unicode"
+ return (char) 0xfffd;
}
+ }
- return bb;
+ public CharSequence subSequence(int start, int end) {
+ return new CharSubSequence(this, start, end);
}
private void deleteFile(File fileToDelete) {
- deleteFile(fileToDelete, null);
+ deleteFile(fileToDelete, null);
}
private void deleteFile(File fileToDelete, final Exception e) {
if (e != null) {
- // Log why the delete to help with debug of java.io.FileNotFoundException:
+ // Log why the delete to help with debug of
+ // java.io.FileNotFoundException:
// ....tt53http.ris.UTF-16BE.
logger.severe("Deleting " + fileToDelete + " because of "
- + e.toString());
+ + e.toString());
}
if (fileToDelete != null && fileToDelete.exists()) {
- FileUtils.deleteSoonerOrLater(fileToDelete);
+ logger.info("deleting file: " + fileToDelete);
+ fileToDelete.delete();
}
}
- public void close()
- {
- this.content = null;
+ public void close() throws IOException {
+ logger.info("closing");
+
+ if (this.backingFileChannel != null && this.backingFileChannel.isOpen()) {
+ this.backingFileChannel.close();
+ }
+ if (backingFileIn != null) {
+ backingFileIn.close();
+ }
+
deleteFile(this.decodedFile);
- // clear decodedFile -- so that double-close (as in
- // finalize()) won't delete a later instance with same name
- // see bug [ 1218961 ] "failed get of replay" in ExtractorHTML... usu: UTF-16BE
+
+ // clear decodedFile -- so that double-close (as in finalize()) won't
+ // delete a later instance with same name see bug [ 1218961 ]
+ // "failed get of replay" in ExtractorHTML... usu: UTF-16BE
this.decodedFile = null;
}
- protected void finalize() throws Throwable
- {
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#finalize()
+ */
+ protected void finalize() throws Throwable {
super.finalize();
- // Maybe TODO: eliminate close here, requiring explicit close instead
+ logger.info("finalizing");
close();
}
- public int length()
- {
- return this.content.limit();
- }
-
- public char charAt(int index)
- {
- return this.content.get(index);
+ /**
+ * Convenience method for getting a substring.
+ *
+ * @deprecated please use subSequence() and then toString() directly
+ */
+ public String substring(int offset, int len) {
+ return subSequence(offset, offset + len).toString();
}
- public CharSequence subSequence(int start, int end) {
- return new CharSubSequence(this, start, end);
- }
-
public String toString() {
- StringBuffer sb = new StringBuffer(length());
- // could use StringBuffer.append(CharSequence) if willing to do 1.5 & up
- for (int i = 0;i<length();i++) {
- sb.append(charAt(i));
- }
+ StringBuilder sb = new StringBuilder(this.length());
+ sb.append(this);
return sb.toString();
}
+
+ public int length() {
+ return length;
+ }
}
\ No newline at end of file
diff --git a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
new file mode 100644
index 000000000..fd36bb647
--- /dev/null
+++ b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
@@ -0,0 +1,117 @@
+/*
+ * This file is part of the Heritrix web crawler (crawler.archive.org).
+ *
+ * Licensed to the Internet Archive (IA) by one or more individual
+ * contributors.
+ *
+ * The IA 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.archive.io;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.util.logging.Logger;
+
+public class InMemoryReplayCharSequence implements ReplayCharSequence {
+
+ protected static Logger logger =
+ Logger.getLogger(InMemoryReplayCharSequence.class.getName());
+
+ /**
+ * CharBuffer of decoded content.
+ *
+ * Content of this buffer is unicode.
+ */
+ private CharBuffer charBuffer = null;
+
+ /**
+ * Constructor for all in-memory operation.
+ *
+ * @param buffer
+ * @param size Total size of stream to replay in bytes. Used to find
+ * EOS. This is total length of content including HTTP headers if
+ * present.
+ * @param responseBodyStart Where the response body starts in bytes.
+ * Used to skip over the HTTP headers if present.
+ * @param encoding Encoding to use reading the passed prefix buffer and
+ * backing file. For now, should be java canonical name for the
+ * encoding. Must not be null.
+ *
+ * @throws IOException
+ */
+ public InMemoryReplayCharSequence(byte[] buffer, long size,
+ long responseBodyStart, String encoding) throws IOException {
+ super();
+ this.charBuffer = decodeInMemory(buffer, size, responseBodyStart,
+ encoding);
+ }
+
+ /**
+ * Decode passed buffer into a CharBuffer.
+ *
+ * This method decodes a memory buffer returning a memory buffer.
+ *
+ * @param buffer
+ * @param size Total size of stream to replay in bytes. Used to find
+ * EOS. This is total length of content including HTTP headers if
+ * present.
+ * @param responseBodyStart Where the response body starts in bytes.
+ * Used to skip over the HTTP headers if present.
+ * @param encoding Encoding to use reading the passed prefix buffer and
+ * backing file. For now, should be java canonical name for the
+ * encoding. Must not be null.
+ *
+ * @return A CharBuffer view on decodings of the contents of passed
+ * buffer.
+ */
+ private CharBuffer decodeInMemory(byte[] buffer, long size,
+ long responseBodyStart, String encoding) {
+ ByteBuffer bb = ByteBuffer.wrap(buffer);
+ // Move past the HTTP header if present.
+ bb.position((int) responseBodyStart);
+ // Set the end-of-buffer to be end-of-content.
+ bb.limit((int) size);
+ return (Charset.forName(encoding)).decode(bb).asReadOnlyBuffer();
+ }
+
+ public void close() {
+ this.charBuffer = null;
+ }
+
+ protected void finalize() throws Throwable {
+ super.finalize();
+ // Maybe TODO: eliminate close here, requiring explicit close instead
+ close();
+ }
+
+ public int length() {
+ return this.charBuffer.limit();
+ }
+
+ public char charAt(int index) {
+ return this.charBuffer.get(index);
+ }
+
+ public CharSequence subSequence(int start, int end) {
+ return new CharSubSequence(this, start, end);
+ }
+
+ public String toString() {
+ StringBuffer sb = new StringBuffer(length());
+ sb.append(this);
+ return sb.toString();
+ }
+}
diff --git a/commons/src/main/java/org/archive/io/Latin1ByteReplayCharSequence.java b/commons/src/main/java/org/archive/io/Latin1ByteReplayCharSequence.java
deleted file mode 100644
index 4742572b2..000000000
--- a/commons/src/main/java/org/archive/io/Latin1ByteReplayCharSequence.java
+++ /dev/null
@@ -1,365 +0,0 @@
-/* ByteReplayCharSequenceFactory
- *
- * (Re)Created on Dec 21, 2006
- *
- * Copyright (C) 2006 Internet Archive.
- *
- * This file is part of the Heritrix web crawler (crawler.archive.org).
- *
- * Heritrix is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser Public License as published by
- * the Free Software Foundation; either version 2.1 of the License, or
- * any later version.
- *
- * Heritrix is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser Public License for more details.
- *
- * You should have received a copy of the GNU Lesser Public License
- * along with Heritrix; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-package org.archive.io;
-
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.archive.util.DevUtils;
-
-/**
- * Provides a (Replay)CharSequence view on recorded stream bytes (a prefix
- * buffer and overflow backing file).
- *
- * Assumes the byte stream is ISO-8859-1 text, taking advantage of the fact
- * that each byte in the stream corresponds to a single unicode character with
- * the same numerical value as the byte.
- *
- * <p>Uses a wraparound rolling buffer of the last windowSize bytes read
- * from disk in memory; as long as the 'random access' of a CharSequence
- * user stays within this window, access should remain fairly efficient.
- * (So design any regexps pointed at these CharSequences to work within
- * that range!)
- *
- * <p>When rereading of a location is necessary, the whole window is
- * recentered around the location requested. (TODO: More research
- * into whether this is the best strategy.)
- *
- * <p>An implementation of a ReplayCharSequence done with ByteBuffers -- one
- * to wrap the passed prefix buffer and the second, a memory-mapped
- * ByteBuffer view into the backing file -- was consistently slower: ~10%.
- * My tests did the following. Made a buffer filled w/ regular content.
- * This buffer was used as the prefix buffer. The buffer content was
- * written MULTIPLER times to a backing file. I then did accesses w/ the
- * following pattern: Skip forward 32 bytes, then back 16 bytes, and then
- * read forward from byte 16-32. Repeat. Though I varied the size of the
- * buffer to the size of the backing file,from 3-10, the difference of 10%
- * or so seemed to persist. Same if I tried to favor get() over get(index).
- * I used a profiler, JMP, to study times taken (St.Ack did above comment).
- *
- * <p>TODO determine in memory mapped files is better way to do this;
- * probably not -- they don't offer the level of control over
- * total memory used that this approach does.
- *
- * @author Gordon Mohr
- * @version $Revision$, $Date$
- */
-class Latin1ByteReplayCharSequence implements ReplayCharSequence {
-
- protected static Logger logger =
- Logger.getLogger(Latin1ByteReplayCharSequence.class.getName());
-
- /**
- * Buffer that holds the first bit of content.
- *
- * Once this is exhausted we go to the backing file.
- */
- private byte[] prefixBuffer;
-
- /**
- * Total length of character stream to replay minus the HTTP headers
- * if present.
- *
- * Used to find EOS.
- */
- protected int length;
-
- /**
- * Absolute length of the stream.
- *
- * Includes HTTP headers. Needed doing calc. in the below figuring
- * how much to load into buffer.
- */
- private int absoluteLength = -1;
-
- /**
- * Buffer window on to backing file.
- */
- private byte[] wraparoundBuffer;
-
- /**
- * Absolute index into underlying bytestream where wrap starts.
- */
- private int wrapOrigin;
-
- /**
- * Index in wraparoundBuffer that corresponds to wrapOrigin
- */
- private int wrapOffset;
-
- /**
- * Name of backing file we go to when we've exhausted content from the
- * prefix buffer.
- */
- private String backingFilename;
-
- /**
- * Random access to the backing file.
- */
- private RandomAccessFile raFile;
-
- /**
- * Offset into prefix buffer at which content beings.
- */
- private int contentOffset;
-
- /**
- * 8-bit encoding used reading single bytes from buffer and
- * stream.
- */
- @SuppressWarnings("unused")
- private static final String DEFAULT_SINGLE_BYTE_ENCODING =
- "ISO-8859-1";
-
-
- /**
- * Constructor.
- *
- * @param buffer In-memory buffer of recordings prefix. We read from
- * here first and will only go to the backing file if <code>size</code>
- * requested is greater than <code>buffer.length</code>.
- * @param size Total size of stream to replay in bytes. Used to find
- * EOS. This is total length of content including HTTP headers if
- * present.
- * @param responseBodyStart Where the response body starts in bytes.
- * Used to skip over the HTTP headers if present.
- * @param backingFilename Path to backing file with content in excess of
- * whats in <code>buffer</code>.
- *
- * @throws IOException
- */
- public Latin1ByteReplayCharSequence(byte[] buffer, long size,
- long responseBodyStart, String backingFilename)
- throws IOException {
-
- this.length = (int)(size - responseBodyStart);
- this.absoluteLength = (int)size;
- this.prefixBuffer = buffer;
- this.contentOffset = (int)responseBodyStart;
-
- // If amount to read is > than what is in our prefix buffer, then
- // open the backing file.
- if (size > buffer.length) {
- this.backingFilename = backingFilename;
- this.raFile = new RandomAccessFile(backingFilename, "r");
- this.wraparoundBuffer = new byte[this.prefixBuffer.length];
- this.wrapOrigin = this.prefixBuffer.length;
- this.wrapOffset = 0;
- loadBuffer();
- }
- }
-
- /**
- * @return Length of characters in stream to replay. Starts counting
- * at the HTTP header/body boundary.
- */
- public int length() {
- return this.length;
- }
-
- /**
- * Get character at passed absolute position.
- *
- * Called by {@link #charAt(int)} which has a relative index into the
- * content, one that doesn't account for HTTP header if present.
- *
- * @param index Index into content adjusted to accomodate initial offset
- * to get us past the HTTP header if present (i.e.
- * {@link #contentOffset}).
- *
- * @return Characater at offset <code>index</code>.
- */
- public char charAt(int index) {
- int c = -1;
- // Add to index start-of-content offset to get us over HTTP header
- // if present.
- index += this.contentOffset;
- if (index < this.prefixBuffer.length) {
- // If index is into our prefix buffer.
- c = this.prefixBuffer[index];
- } else if (index >= this.wrapOrigin &&
- (index - this.wrapOrigin) < this.wraparoundBuffer.length) {
- // If index is into our buffer window on underlying backing file.
- c = this.wraparoundBuffer[
- ((index - this.wrapOrigin) + this.wrapOffset) %
- this.wraparoundBuffer.length];
- } else {
- // Index is outside of both prefix buffer and our buffer window
- // onto the underlying backing file. Fix the buffer window
- // location.
- c = faultCharAt(index);
- }
- // Stream is treated as single byte. Make sure characters returned
- // are not negative.
- return (char)(c & 0xff);
- }
-
- /**
- * Get a character that's outside the current buffers.
- *
- * will cause the wraparoundBuffer to be changed to
- * cover a region including the index
- *
- * if index is higher than the highest index in the
- * wraparound buffer, buffer is moved forward such
- * that requested char is last item in buffer
- *
- * if index is lower than lowest index in the
- * wraparound buffer, buffet is reset centered around
- * index
- *
- * @param index Index of character to fetch.
- * @return A character that's outside the current buffers
- */
- private int faultCharAt(int index) {
- if(Thread.interrupted()) {
- throw new RuntimeException("thread interrupted");
- }
- if(index >= this.wrapOrigin + this.wraparoundBuffer.length) {
- // Moving forward
- while (index >= this.wrapOrigin + this.wraparoundBuffer.length)
- {
- // TODO optimize this
- advanceBuffer();
- }
- return charAt(index - this.contentOffset);
- }
- // Moving backward
- recenterBuffer(index);
- return charAt(index - this.contentOffset);
- }
-
- /**
- * Move the buffer window on backing file back centering current access
- * position in middle of window.
- *
- * @param index Index of character to access.
- */
- private void recenterBuffer(int index) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("Recentering around " + index + " in " +
- this.backingFilename);
- }
- this.wrapOrigin = index - (this.wraparoundBuffer.length / 2);
- if(this.wrapOrigin < this.prefixBuffer.length) {
- this.wrapOrigin = this.prefixBuffer.length;
- }
- this.wrapOffset = 0;
- loadBuffer();
- }
-
- /**
- * Load from backing file into the wrapper buffer.
- */
- private void loadBuffer()
- {
- long len = -1;
- try {
- len = this.raFile.length();
- this.raFile.seek(this.wrapOrigin - this.prefixBuffer.length);
- this.raFile.readFully(this.wraparoundBuffer, 0,
- Math.min(this.wraparoundBuffer.length,
- this.absoluteLength - this.wrapOrigin));
- }
-
- catch (IOException e) {
- // TODO convert this to a runtime error?
- DevUtils.logger.log (
- Level.SEVERE,
- "raFile.seek(" +
- (this.wrapOrigin - this.prefixBuffer.length) +
- ")\n" +
- "raFile.readFully(wraparoundBuffer,0," +
- (Math.min(this.wraparoundBuffer.length,
- this.length - this.wrapOrigin )) +
- ")\n"+
- "raFile.length()" + len + "\n" +
- DevUtils.extraInfo(),
- e);
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Roll the wraparound buffer forward one position
- */
- private void advanceBuffer() {
- try {
- this.wraparoundBuffer[this.wrapOffset] =
- (byte)this.raFile.read();
- this.wrapOffset++;
- this.wrapOffset %= this.wraparoundBuffer.length;
- this.wrapOrigin++;
- } catch (IOException e) {
- DevUtils.logger.log(Level.SEVERE, "advanceBuffer()" +
- DevUtils.extraInfo(), e);
- throw new RuntimeException(e);
- }
- }
-
- public CharSequence subSequence(int start, int end) {
- return new CharSubSequence(this, start, end);
- }
-
- /**
- * Cleanup resources.
- *
- * @exception IOException Failed close of random access file.
- */
- public void close() throws IOException
- {
- this.prefixBuffer = null;
- if (this.raFile != null) {
- this.raFile.close();
- this.raFile = null;
- }
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#finalize()
- */
- protected void finalize() throws Throwable
- {
- super.finalize();
- close();
- }
-
- /**
- * Convenience method for getting a substring.
- * @deprecated please use subSequence() and then toString() directly
- */
- public String substring(int offset, int len) {
- return subSequence(offset, offset+len).toString();
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuilder sb = new StringBuilder(this.length());
- sb.append(this);
- return sb.toString();
- }
-}
\ No newline at end of file
diff --git a/commons/src/main/java/org/archive/io/RecordingOutputStream.java b/commons/src/main/java/org/archive/io/RecordingOutputStream.java
index 01f64a057..edc1c5023 100644
--- a/commons/src/main/java/org/archive/io/RecordingOutputStream.java
+++ b/commons/src/main/java/org/archive/io/RecordingOutputStream.java
@@ -1,27 +1,22 @@
-/* ReplayableOutputStream
+/*
+ * This file is part of the Heritrix web crawler (crawler.archive.org).
*
- * $Id$
+ * Licensed to the Internet Archive (IA) by one or more individual
+ * contributors.
*
- * Created on Sep 23, 2003
+ * The IA 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
*
- * Copyright (C) 2003 Internet Archive.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * This file is part of the Heritrix web crawler (crawler.archive.org).
- *
- * Heritrix is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser Public License as published by
- * the Free Software Foundation; either version 2.1 of the License, or
- * any later version.
- *
- * Heritrix is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser Public License for more details.
- *
- * You should have received a copy of the GNU Lesser Public License
- * along with Heritrix; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * 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.archive.io;
import it.unimi.dsi.fastutil.io.FastBufferedOutputStream;
@@ -513,9 +508,7 @@ public ReplayCharSequence getReplayCharSequence(String characterEncoding)
throws IOException {
return getReplayCharSequence(characterEncoding, this.contentBeginMark);
}
-
- private static final String canonicalLatin1 = Charset.forName("iso8859-1").name();
-
+
/**
* @param characterEncoding Encoding of recorded stream.
* @return A ReplayCharSequence Will return null if an IOException. Call
@@ -524,39 +517,27 @@ public ReplayCharSequence getReplayCharSequence(String characterEncoding)
*/
public ReplayCharSequence getReplayCharSequence(String characterEncoding,
long startOffset) throws IOException {
- if (characterEncoding == null) {
+ if (characterEncoding == null)
characterEncoding = Charset.defaultCharset().name();
- }
- // TODO: handled transfer-encoding: chunked content-bodies properly
- if (canonicalLatin1.equals(Charset.forName(characterEncoding).name())) {
- return new Latin1ByteReplayCharSequence(
+ logger.fine("this.size=" + this.size + " this.buffer.length=" + this.buffer.length);
+ if (this.size <= this.buffer.length) {
+ logger.fine("using InMemoryReplayCharSequence");
+ // raw data is all in memory; do in memory
+ return new InMemoryReplayCharSequence(
this.buffer,
this.size,
startOffset,
- this.backingFilename);
- } else {
- // multibyte
- if(this.size <= this.buffer.length) {
- // raw data is all in memory; do in memory
- return new GenericReplayCharSequence(
- this.buffer,
- this.size,
- startOffset,
- characterEncoding);
-
- } else {
- // raw data overflows to disk; use temp file
- ReplayInputStream ris = getReplayInputStream(startOffset);
- ReplayCharSequence rcs = new GenericReplayCharSequence(
- ris,
- this.backingFilename,
- characterEncoding);
- ris.close();
- return rcs;
- }
-
+ characterEncoding);
+ }
+ else {
+ logger.fine("using GenericReplayCharSequence");
+ // raw data overflows to disk; use temp file
+ ReplayInputStream ris = getReplayInputStream(startOffset);
+ return new GenericReplayCharSequence(
+ ris,
+ this.backingFilename,
+ characterEncoding);
}
-
}
public long getResponseContentLength() {
@@ -624,3 +605,4 @@ public long getRemainingLength() {
return maxLength - position;
}
}
+
diff --git a/commons/src/main/java/org/archive/io/ReplayInputStream.java b/commons/src/main/java/org/archive/io/ReplayInputStream.java
index a590ccdb2..04656d4bd 100644
--- a/commons/src/main/java/org/archive/io/ReplayInputStream.java
+++ b/commons/src/main/java/org/archive/io/ReplayInputStream.java
@@ -1,27 +1,22 @@
-/* ReplayInputStream
+/*
+ * This file is part of the Heritrix web crawler (crawler.archive.org).
*
- * $Id$
+ * Licensed to the Internet Archive (IA) by one or more individual
+ * contributors.
*
- * Created on Sep 24, 2003
+ * The IA 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
*
- * Copyright (C) 2003 Internet Archive.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * This file is part of the Heritrix web crawler (crawler.archive.org).
- *
- * Heritrix is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser Public License as published by
- * the Free Software Foundation; either version 2.1 of the License, or
- * any later version.
- *
- * Heritrix is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser Public License for more details.
- *
- * You should have received a copy of the GNU Lesser Public License
- * along with Heritrix; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ * 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.archive.io;
import java.io.File;
@@ -279,4 +274,9 @@ public void position(long p) throws IOException {
public long position() throws IOException {
return position;
}
+
+ // package private
+ byte[] getBuffer() {
+ return buffer;
+ }
}
diff --git a/commons/src/test/java/org/archive/io/ReplayCharSequenceTest.java b/commons/src/test/java/org/archive/io/ReplayCharSequenceTest.java
index fb7d229f0..11b84f563 100644
--- a/commons/src/test/java/org/archive/io/ReplayCharSequenceTest.java
+++ b/commons/src/test/java/org/archive/io/ReplayCharSequenceTest.java
@@ -20,7 +20,9 @@
package org.archive.io;
import java.io.IOException;
+import java.text.NumberFormat;
import java.util.Date;
+import java.util.Random;
import java.util.logging.Logger;
import org.archive.util.FileUtils;
@@ -210,14 +212,24 @@ public void testSingleByteEncodings() throws IOException {
}
public void testReplayCharSequenceByteToStringOverflow() throws IOException {
- String fileContent = "Some file content. ";
+ String fileContent = "Some file content. "; // ascii
byte [] buffer = fileContent.getBytes();
RecordingOutputStream ros = writeTestStream(
buffer,1,
- "testReplayCharSequenceByteToString.txt",1);
+ "testReplayCharSequenceByteToStringOverflow.txt",1);
String expectedContent = fileContent+fileContent;
- ReplayCharSequence rcs = ros.getReplayCharSequence();
- String result = rcs.toString();
+
+ // The string is ascii which is a subset of both these encodings. Use
+ // both encodings because they exercise different code paths. UTF-8 is
+ // decoded to UTF-16 while windows-1252 is memory mapped directly. See
+ // GenericReplayCharSequence
+ ReplayCharSequence rcsUtf8 = ros.getReplayCharSequence("UTF-8");
+ ReplayCharSequence rcs1252 = ros.getReplayCharSequence("windows-1252");
+
+ String result = rcsUtf8.toString();
+ assertEquals("Strings don't match", expectedContent, result);
+
+ result = rcs1252.toString();
assertEquals("Strings don't match", expectedContent, result);
}
@@ -244,6 +256,67 @@ public void testReplayCharSequenceByteToStringMulti() throws IOException {
}
}
+ public void xestHugeReplayCharSequence() throws IOException {
+ String fileContent = "01234567890123456789";
+ String characterEncoding = "ascii";
+ byte[] buffer = fileContent.getBytes(characterEncoding);
+
+ long reps = (long) Integer.MAX_VALUE / (long) buffer.length + 1000000l;
+
+ logger.info("writing " + (reps * buffer.length)
+ + " bytes to testHugeReplayCharSequence.txt");
+ RecordingOutputStream ros = writeTestStream(buffer, 0,
+ "testHugeReplayCharSequence.txt", reps);
+ ReplayCharSequence rcs = ros.getReplayCharSequence(characterEncoding);
+
+ if (reps * fileContent.length() > (long) Integer.MAX_VALUE) {
+ assertTrue("ReplayCharSequence has wrong length (length()="
+ + rcs.length() + ") (should be " + Integer.MAX_VALUE + ")",
+ rcs.length() == Integer.MAX_VALUE);
+ } else {
+ assertEquals("ReplayCharSequence has wrong length (length()="
+ + rcs.length() + ") (should be "
+ + (reps * fileContent.length()) + ")", (long) rcs.length(),
+ reps * (long) fileContent.length());
+ }
+
+ // boundary cases or something
+ for (int index : new int[] { 0, rcs.length() / 4, rcs.length() / 2,
+ rcs.length() - 1, rcs.length() / 4 }) {
+ // logger.info("testing char at index=" +
+ // NumberFormat.getInstance().format(index));
+ assertEquals("Characters don't match (index="
+ + NumberFormat.getInstance().format(index) + ")",
+ fileContent.charAt(index % fileContent.length()), rcs
+ .charAt(index));
+ }
+
+ // check that out of bounds indices throw exception
+ for (int n : new int[] { -1, Integer.MIN_VALUE, rcs.length() + 1 }) {
+ try {
+ String message = "rcs.charAt(" + n + ")=" + rcs.charAt(n)
+ + " ?!? -- expected IndexOutOfBoundsException";
+ logger.severe(message);
+ fail(message);
+ } catch (IndexOutOfBoundsException e) {
+ logger.info("got expected exception: " + e);
+ }
+ }
+
+ // check some characters at random spots & kinda stress test the
+ // system's memory mapping facility
+ Random rand = new Random(0); // seed so we get the same ones each time
+ for (int i = 0; i < 5000; i++) {
+ int index = rand.nextInt(rcs.length());
+ // logger.info(i + ". testing char at index=" +
+ // NumberFormat.getInstance().format(index));
+ assertEquals("Characters don't match (index="
+ + NumberFormat.getInstance().format(index) + ")",
+ fileContent.charAt(index % fileContent.length()), rcs
+ .charAt(index));
+ }
+ }
+
/**
* Accessing characters test.
*
@@ -290,13 +363,14 @@ private void checkCharacter(CharSequence rcs, int i) {
* @throws IOException
*/
private RecordingOutputStream writeTestStream(byte[] content,
- int memReps, String baseName, int fileReps) throws IOException {
+ int memReps, String baseName, long fileReps) throws IOException {
String backingFilename = FileUtils.maybeRelative(getTmpDir(),baseName).getAbsolutePath();
RecordingOutputStream ros = new RecordingOutputStream(
content.length * memReps,
backingFilename);
ros.open();
- for(int i = 0; i < (memReps+fileReps); i++) {
+ ros.markContentBegin();
+ for(long i = 0; i < (memReps+fileReps); i++) {
// fill buffer (repeat MULTIPLIER times) and
// overflow to disk (also MULTIPLIER times)
ros.write(content);
|
4631ac5c89e34a3ac34568ca7faf6b4d91e9abb1
|
Vala
|
gio-unix-2.0: update to 2.22.4
Fixes bug 610074.
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-unix-2.0.vapi b/vapi/gio-unix-2.0.vapi
index 8823c7412f..818895a31b 100644
--- a/vapi/gio-unix-2.0.vapi
+++ b/vapi/gio-unix-2.0.vapi
@@ -13,6 +13,18 @@ namespace GLib {
public bool get_is_hidden ();
public static void set_desktop_env (string desktop_env);
}
+ [CCode (cheader_filename = "gio/gunixmounts.h")]
+ public class UnixConnection : GLib.SocketConnection {
+ public int receive_fd (GLib.Cancellable cancellable) throws GLib.Error;
+ public bool send_fd (int fd, GLib.Cancellable cancellable) throws GLib.Error;
+ }
+ [CCode (cheader_filename = "gio/gunixmounts.h")]
+ public class UnixFDMessage : GLib.SocketControlMessage {
+ [CCode (type = "GSocketControlMessage*", has_construct_function = false)]
+ public UnixFDMessage ();
+ public bool append_fd (int fd) throws GLib.Error;
+ public int steal_fds (int length);
+ }
[CCode (cheader_filename = "gio/gunixinputstream.h")]
public class UnixInputStream : GLib.InputStream {
[CCode (type = "GInputStream*", has_construct_function = false)]
@@ -91,8 +103,17 @@ namespace GLib {
public class UnixSocketAddress : GLib.SocketAddress, GLib.SocketConnectable {
[CCode (type = "GSocketAddress*", has_construct_function = false)]
public UnixSocketAddress (string path);
+ public static bool abstract_names_supported ();
+ [CCode (cname = "g_unix_socket_address_new_abstract", type = "GSocketAddress*", has_construct_function = false)]
+ public UnixSocketAddress.as_abstract (string path, int path_len);
+ public bool get_is_abstract ();
+ public unowned string get_path ();
+ public size_t get_path_len ();
+ [NoAccessorMethod]
+ public bool @abstract { get; construct; }
+ public string path { get; construct; }
[NoAccessorMethod]
- public string path { owned get; construct; }
+ public GLib.ByteArray path_as_array { owned get; construct; }
}
[CCode (cheader_filename = "gio/gunixmounts.h")]
public interface DesktopAppInfoLookup : GLib.Object {
diff --git a/vapi/packages/gio-unix-2.0/gio-unix-2.0.gi b/vapi/packages/gio-unix-2.0/gio-unix-2.0.gi
index 7166e2c383..f735787191 100644
--- a/vapi/packages/gio-unix-2.0/gio-unix-2.0.gi
+++ b/vapi/packages/gio-unix-2.0/gio-unix-2.0.gi
@@ -213,6 +213,45 @@
</parameters>
</method>
</object>
+ <object name="GUnixConnection" parent="GSocketConnection" type-name="GUnixConnection" get-type="g_unix_connection_get_type">
+ <method name="receive_fd" symbol="g_unix_connection_receive_fd">
+ <return-type type="gint"/>
+ <parameters>
+ <parameter name="connection" type="GUnixConnection*"/>
+ <parameter name="cancellable" type="GCancellable*"/>
+ <parameter name="error" type="GError**"/>
+ </parameters>
+ </method>
+ <method name="send_fd" symbol="g_unix_connection_send_fd">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="connection" type="GUnixConnection*"/>
+ <parameter name="fd" type="gint"/>
+ <parameter name="cancellable" type="GCancellable*"/>
+ <parameter name="error" type="GError**"/>
+ </parameters>
+ </method>
+ </object>
+ <object name="GUnixFDMessage" parent="GSocketControlMessage" type-name="GUnixFDMessage" get-type="g_unix_fd_message_get_type">
+ <method name="append_fd" symbol="g_unix_fd_message_append_fd">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="message" type="GUnixFDMessage*"/>
+ <parameter name="fd" type="gint"/>
+ <parameter name="error" type="GError**"/>
+ </parameters>
+ </method>
+ <constructor name="new" symbol="g_unix_fd_message_new">
+ <return-type type="GSocketControlMessage*"/>
+ </constructor>
+ <method name="steal_fds" symbol="g_unix_fd_message_steal_fds">
+ <return-type type="gint*"/>
+ <parameters>
+ <parameter name="message" type="GUnixFDMessage*"/>
+ <parameter name="length" type="gint*"/>
+ </parameters>
+ </method>
+ </object>
<object name="GUnixInputStream" parent="GInputStream" type-name="GUnixInputStream" get-type="g_unix_input_stream_get_type">
<method name="get_close_fd" symbol="g_unix_input_stream_get_close_fd">
<return-type type="gboolean"/>
@@ -301,13 +340,43 @@
<implements>
<interface name="GSocketConnectable"/>
</implements>
+ <method name="abstract_names_supported" symbol="g_unix_socket_address_abstract_names_supported">
+ <return-type type="gboolean"/>
+ </method>
+ <method name="get_is_abstract" symbol="g_unix_socket_address_get_is_abstract">
+ <return-type type="gboolean"/>
+ <parameters>
+ <parameter name="address" type="GUnixSocketAddress*"/>
+ </parameters>
+ </method>
+ <method name="get_path" symbol="g_unix_socket_address_get_path">
+ <return-type type="char*"/>
+ <parameters>
+ <parameter name="address" type="GUnixSocketAddress*"/>
+ </parameters>
+ </method>
+ <method name="get_path_len" symbol="g_unix_socket_address_get_path_len">
+ <return-type type="gsize"/>
+ <parameters>
+ <parameter name="address" type="GUnixSocketAddress*"/>
+ </parameters>
+ </method>
<constructor name="new" symbol="g_unix_socket_address_new">
<return-type type="GSocketAddress*"/>
<parameters>
<parameter name="path" type="gchar*"/>
</parameters>
</constructor>
+ <constructor name="new_abstract" symbol="g_unix_socket_address_new_abstract">
+ <return-type type="GSocketAddress*"/>
+ <parameters>
+ <parameter name="path" type="gchar*"/>
+ <parameter name="path_len" type="int"/>
+ </parameters>
+ </constructor>
+ <property name="abstract" type="gboolean" readable="1" writable="1" construct="0" construct-only="1"/>
<property name="path" type="char*" readable="1" writable="1" construct="0" construct-only="1"/>
+ <property name="path-as-array" type="GByteArray*" readable="1" writable="1" construct="0" construct-only="1"/>
</object>
<interface name="GDesktopAppInfoLookup" type-name="GDesktopAppInfoLookup" get-type="g_desktop_app_info_lookup_get_type">
<requires>
diff --git a/vapi/packages/gio-unix-2.0/gio-unix-2.0.metadata b/vapi/packages/gio-unix-2.0/gio-unix-2.0.metadata
index 535891e7c7..8f5048ea73 100644
--- a/vapi/packages/gio-unix-2.0/gio-unix-2.0.metadata
+++ b/vapi/packages/gio-unix-2.0/gio-unix-2.0.metadata
@@ -20,4 +20,4 @@ g_unix_mount_is_system_internal hidden="1"
g_unix_mount_points_changed_since name="mount_points_changed_since"
g_unix_mount_points_get hidden="1"
GUnixOutputStream cheader_filename="gio/gunixoutputstream.h"
-
+g_unix_socket_address_new_abstract name="as_abstract"
|
03687b80bcd2c8f8968a044f4f9b8c865af0fd61
|
hbase
|
HBASE-11813 CellScanner-advance may overflow- stack--
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java
index 8dce6ba3200f..50e42c65633b 100644
--- a/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java
+++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/CellUtil.java
@@ -201,13 +201,14 @@ public Cell current() {
@Override
public boolean advance() throws IOException {
- if (this.cellScanner == null) {
- if (!this.iterator.hasNext()) return false;
- this.cellScanner = this.iterator.next().cellScanner();
+ while (true) {
+ if (this.cellScanner == null) {
+ if (!this.iterator.hasNext()) return false;
+ this.cellScanner = this.iterator.next().cellScanner();
+ }
+ if (this.cellScanner.advance()) return true;
+ this.cellScanner = null;
}
- if (this.cellScanner.advance()) return true;
- this.cellScanner = null;
- return advance();
}
};
}
@@ -275,11 +276,9 @@ public boolean advance() {
* inside Put, etc., keeping Cells organized by family.
* @return CellScanner interface over <code>cellIterable</code>
*/
- public static CellScanner createCellScanner(final NavigableMap<byte [],
- List<Cell>> map) {
+ public static CellScanner createCellScanner(final NavigableMap<byte [], List<Cell>> map) {
return new CellScanner() {
- private final Iterator<Entry<byte[], List<Cell>>> entries =
- map.entrySet().iterator();
+ private final Iterator<Entry<byte[], List<Cell>>> entries = map.entrySet().iterator();
private Iterator<Cell> currentIterator = null;
private Cell currentCell;
@@ -290,17 +289,18 @@ public Cell current() {
@Override
public boolean advance() {
- if (this.currentIterator == null) {
- if (!this.entries.hasNext()) return false;
- this.currentIterator = this.entries.next().getValue().iterator();
+ while(true) {
+ if (this.currentIterator == null) {
+ if (!this.entries.hasNext()) return false;
+ this.currentIterator = this.entries.next().getValue().iterator();
+ }
+ if (this.currentIterator.hasNext()) {
+ this.currentCell = this.currentIterator.next();
+ return true;
+ }
+ this.currentCell = null;
+ this.currentIterator = null;
}
- if (this.currentIterator.hasNext()) {
- this.currentCell = this.currentIterator.next();
- return true;
- }
- this.currentCell = null;
- this.currentIterator = null;
- return advance();
}
};
}
diff --git a/hbase-common/src/test/java/org/apache/hadoop/hbase/TestCellUtil.java b/hbase-common/src/test/java/org/apache/hadoop/hbase/TestCellUtil.java
index 4835ccab8719..50063f4da64a 100644
--- a/hbase-common/src/test/java/org/apache/hadoop/hbase/TestCellUtil.java
+++ b/hbase-common/src/test/java/org/apache/hadoop/hbase/TestCellUtil.java
@@ -18,6 +18,12 @@
package org.apache.hadoop.hbase;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Assert;
import org.junit.Test;
@@ -25,6 +31,250 @@
@Category(SmallTests.class)
public class TestCellUtil {
+ /**
+ * CellScannable used in test. Returns a {@link TestCellScanner}
+ */
+ private class TestCellScannable implements CellScannable {
+ private final int cellsCount;
+ TestCellScannable(final int cellsCount) {
+ this.cellsCount = cellsCount;
+ }
+ @Override
+ public CellScanner cellScanner() {
+ return new TestCellScanner(this.cellsCount);
+ }
+ };
+
+ /**
+ * CellScanner used in test.
+ */
+ private class TestCellScanner implements CellScanner {
+ private int count = 0;
+ private Cell current = null;
+ private final int cellsCount;
+
+ TestCellScanner(final int cellsCount) {
+ this.cellsCount = cellsCount;
+ }
+
+ @Override
+ public Cell current() {
+ return this.current;
+ }
+
+ @Override
+ public boolean advance() throws IOException {
+ if (this.count < cellsCount) {
+ this.current = new TestCell(this.count);
+ this.count++;
+ return true;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Cell used in test. Has row only.
+ */
+ private class TestCell implements Cell {
+ private final byte [] row;
+
+ TestCell(final int i) {
+ this.row = Bytes.toBytes(i);
+ }
+
+ @Override
+ public byte[] getRowArray() {
+ return this.row;
+ }
+
+ @Override
+ public int getRowOffset() {
+ return 0;
+ }
+
+ @Override
+ public short getRowLength() {
+ return (short)this.row.length;
+ }
+
+ @Override
+ public byte[] getFamilyArray() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getFamilyOffset() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte getFamilyLength() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte[] getQualifierArray() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getQualifierOffset() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public int getQualifierLength() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getTimestamp() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte getTypeByte() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getMvccVersion() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte[] getValueArray() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getValueOffset() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public int getValueLength() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte[] getTagsArray() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public int getTagsOffset() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public byte[] getValue() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public byte[] getFamily() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public byte[] getQualifier() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public byte[] getRow() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public long getSequenceId() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public int getTagsLength() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+ };
+
+ /**
+ * Was overflowing if 100k or so lists of cellscanners to return.
+ * @throws IOException
+ */
+ @Test
+ public void testCreateCellScannerOverflow() throws IOException {
+ consume(doCreateCellScanner(1, 1), 1 * 1);
+ consume(doCreateCellScanner(3, 0), 3 * 0);
+ consume(doCreateCellScanner(3, 3), 3 * 3);
+ consume(doCreateCellScanner(0, 1), 0 * 1);
+ // Do big number. See HBASE-11813 for why.
+ final int hundredK = 100000;
+ consume(doCreateCellScanner(hundredK, 0), hundredK * 0);
+ consume(doCreateCellArray(1), 1);
+ consume(doCreateCellArray(0), 0);
+ consume(doCreateCellArray(3), 3);
+ List<CellScannable> cells = new ArrayList<CellScannable>(hundredK);
+ for (int i = 0; i < hundredK; i++) {
+ cells.add(new TestCellScannable(1));
+ }
+ consume(CellUtil.createCellScanner(cells), hundredK * 1);
+ NavigableMap<byte [], List<Cell>> m = new TreeMap<byte [], List<Cell>>(Bytes.BYTES_COMPARATOR);
+ List<Cell> cellArray = new ArrayList<Cell>(hundredK);
+ for (int i = 0; i < hundredK; i++) cellArray.add(new TestCell(i));
+ m.put(new byte [] {'f'}, cellArray);
+ consume(CellUtil.createCellScanner(m), hundredK * 1);
+ }
+
+ private CellScanner doCreateCellArray(final int itemsPerList) {
+ Cell [] cells = new Cell [itemsPerList];
+ for (int i = 0; i < itemsPerList; i++) {
+ cells[i] = new TestCell(i);
+ }
+ return CellUtil.createCellScanner(cells);
+ }
+
+ private CellScanner doCreateCellScanner(final int listsCount, final int itemsPerList)
+ throws IOException {
+ List<CellScannable> cells = new ArrayList<CellScannable>(listsCount);
+ for (int i = 0; i < listsCount; i++) {
+ CellScannable cs = new CellScannable() {
+ @Override
+ public CellScanner cellScanner() {
+ return new TestCellScanner(itemsPerList);
+ }
+ };
+ cells.add(cs);
+ }
+ return CellUtil.createCellScanner(cells);
+ }
+
+ private void consume(final CellScanner scanner, final int expected) throws IOException {
+ int count = 0;
+ while (scanner.advance()) count++;
+ Assert.assertEquals(expected, count);
+ }
@Test
public void testOverlappingKeys() {
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/CallRunner.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/CallRunner.java
index c36478621f46..05fd873e7b9e 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/CallRunner.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/CallRunner.java
@@ -139,7 +139,7 @@ public void run() {
RpcServer.LOG.warn(Thread.currentThread().getName()
+ ": caught: " + StringUtils.stringifyException(e));
} finally {
- // regardless if succesful or not we need to reset the callQueueSize
+ // regardless if successful or not we need to reset the callQueueSize
this.rpcServer.addCallSize(call.getSize() * -1);
}
}
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/SimpleRpcScheduler.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/SimpleRpcScheduler.java
index 2debe2ec8d7a..5b13b1d70542 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/SimpleRpcScheduler.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/ipc/SimpleRpcScheduler.java
@@ -126,21 +126,21 @@ public SimpleRpcScheduler(
// multiple read/write queues
if (callQueueType.equals(CALL_QUEUE_TYPE_DEADLINE_CONF_VALUE)) {
CallPriorityComparator callPriority = new CallPriorityComparator(conf, this.priority);
- callExecutor = new RWQueueRpcExecutor("default", handlerCount, numCallQueues,
+ callExecutor = new RWQueueRpcExecutor("RW.default", handlerCount, numCallQueues,
callqReadShare, callqScanShare, maxQueueLength,
BoundedPriorityBlockingQueue.class, callPriority);
} else {
- callExecutor = new RWQueueRpcExecutor("default", handlerCount, numCallQueues,
+ callExecutor = new RWQueueRpcExecutor("RW.default", handlerCount, numCallQueues,
callqReadShare, callqScanShare, maxQueueLength);
}
} else {
// multiple queues
if (callQueueType.equals(CALL_QUEUE_TYPE_DEADLINE_CONF_VALUE)) {
CallPriorityComparator callPriority = new CallPriorityComparator(conf, this.priority);
- callExecutor = new BalancedQueueRpcExecutor("default", handlerCount, numCallQueues,
+ callExecutor = new BalancedQueueRpcExecutor("B.default", handlerCount, numCallQueues,
BoundedPriorityBlockingQueue.class, maxQueueLength, callPriority);
} else {
- callExecutor = new BalancedQueueRpcExecutor("default", handlerCount,
+ callExecutor = new BalancedQueueRpcExecutor("B.default", handlerCount,
numCallQueues, maxQueueLength);
}
}
|
a8014dec501f50c4a7bb91778ed832676aa6835c
|
kotlin
|
[KT-4124] Add support for simple nested classes--
|
a
|
https://github.com/JetBrains/kotlin
|
diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/JsPlatformConfigurator.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/JsPlatformConfigurator.kt
index a5a04e94ee6ac..f0244a8377330 100644
--- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/JsPlatformConfigurator.kt
+++ b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/JsPlatformConfigurator.kt
@@ -28,7 +28,7 @@ import org.jetbrains.kotlin.types.DynamicTypesAllowed
object JsPlatformConfigurator : PlatformConfigurator(
DynamicTypesAllowed(),
- additionalDeclarationCheckers = listOf(NativeInvokeChecker(), NativeGetterChecker(), NativeSetterChecker(), ClassDeclarationChecker()),
+ additionalDeclarationCheckers = listOf(NativeInvokeChecker(), NativeGetterChecker(), NativeSetterChecker()),
additionalCallCheckers = listOf(),
additionalTypeCheckers = listOf(),
additionalSymbolUsageValidators = listOf(),
diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/unsupportedFeatureCheckers.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/unsupportedFeatureCheckers.kt
deleted file mode 100644
index 0185d5b6b6f78..0000000000000
--- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/unsupportedFeatureCheckers.kt
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2010-2015 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jetbrains.kotlin.js.resolve
-
-import org.jetbrains.kotlin.descriptors.ClassDescriptor
-import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
-import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
-import org.jetbrains.kotlin.descriptors.Visibilities
-import org.jetbrains.kotlin.diagnostics.DiagnosticSink
-import org.jetbrains.kotlin.diagnostics.rendering.renderKind
-import org.jetbrains.kotlin.diagnostics.rendering.renderKindWithName
-import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs
-import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
-import org.jetbrains.kotlin.psi.*
-import org.jetbrains.kotlin.resolve.BindingContext
-import org.jetbrains.kotlin.resolve.DeclarationChecker
-import org.jetbrains.kotlin.resolve.DescriptorUtils
-
-class ClassDeclarationChecker : DeclarationChecker {
- override fun check(
- declaration: KtDeclaration,
- descriptor: DeclarationDescriptor,
- diagnosticHolder: DiagnosticSink,
- bindingContext: BindingContext
- ) {
- if (declaration !is KtClassOrObject || declaration is KtObjectDeclaration || declaration is KtEnumEntry) return
-
- // hack to avoid to get diagnostics when compile kotlin builtins
- val fqNameUnsafe = DescriptorUtils.getFqName(descriptor)
- if (fqNameUnsafe.asString().startsWith("kotlin.")) return
-
- if (!DescriptorUtils.isTopLevelDeclaration(descriptor) && !AnnotationsUtils.isNativeObject(descriptor)) {
- diagnosticHolder.report(ErrorsJs.NON_TOPLEVEL_CLASS_DECLARATION.on(declaration, (descriptor as ClassDescriptor).renderKind()))
- }
- }
-}
diff --git a/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/NestedTypesTest.java b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/NestedTypesTest.java
new file mode 100644
index 0000000000000..278f65a6adf79
--- /dev/null
+++ b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/NestedTypesTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2010-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.jetbrains.kotlin.js.test.semantics;
+
+import org.jetbrains.kotlin.js.test.SingleFileTranslationTest;
+
+public class NestedTypesTest extends SingleFileTranslationTest {
+ public NestedTypesTest() {
+ super("nestedTypes/");
+ }
+
+ public void testNested() throws Exception {
+ checkFooBoxIsOk();
+ }
+
+ public void testInner() throws Exception {
+ checkFooBoxIsOk();
+ }
+}
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt
index ba4b41a2cf71b..209eefc5a6a13 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/callTranslator/FunctionCallCases.kt
@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.descriptors.Visibilities
import org.jetbrains.kotlin.js.PredefinedAnnotation
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.context.TranslationContext
+import org.jetbrains.kotlin.js.translate.general.Translation
import org.jetbrains.kotlin.js.translate.operation.OperatorTable
import org.jetbrains.kotlin.js.translate.reference.CallArgumentTranslator
import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils
@@ -32,6 +33,7 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
+import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.util.OperatorNameConventions
import java.util.ArrayList
@@ -209,13 +211,35 @@ object ConstructorCallCase : FunctionCallCase() {
val functionRef = if (isNative()) fqName else context.aliasOrValue(callableDescriptor) { fqName }
val constructorDescriptor = callableDescriptor as ConstructorDescriptor
- if(constructorDescriptor.isPrimary || AnnotationsUtils.isNativeObject(constructorDescriptor)) {
+ if (constructorDescriptor.isPrimary || AnnotationsUtils.isNativeObject(constructorDescriptor)) {
return JsNew(functionRef, argumentsInfo.translateArguments)
}
else {
return JsInvocation(functionRef, argumentsInfo.translateArguments)
}
}
+
+ override fun FunctionCallInfo.dispatchReceiver(): JsExpression {
+ val fqName = context.getQualifiedReference(callableDescriptor)
+ val functionRef = context.aliasOrValue(callableDescriptor) { fqName }
+
+ val constructorDescriptor = callableDescriptor as ConstructorDescriptor
+ val receiver = this.resolvedCall.dispatchReceiver
+ var allArguments = when (receiver) {
+ is ExpressionReceiver -> {
+ val jsReceiver = Translation.translateAsExpression(receiver.expression, context)
+ (sequenceOf(jsReceiver) + argumentsInfo.translateArguments).toList()
+ }
+ else -> argumentsInfo.translateArguments
+ }
+
+ if (constructorDescriptor.isPrimary || AnnotationsUtils.isNativeObject(constructorDescriptor)) {
+ return JsNew(functionRef, allArguments)
+ }
+ else {
+ return JsInvocation(functionRef, allArguments)
+ }
+ }
}
object SuperCallCase : FunctionCallCase() {
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/StaticContext.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/StaticContext.java
index 0190dea9e8fdd..71a22e1a1ae86 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/StaticContext.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/StaticContext.java
@@ -541,6 +541,27 @@ public JsExpression apply(@NotNull DeclarationDescriptor descriptor) {
return null;
}
};
+ Rule<JsExpression> nestedClassesHaveContainerQualifier = new Rule<JsExpression>() {
+ @Nullable
+ @Override
+ public JsExpression apply(@NotNull DeclarationDescriptor descriptor) {
+ if (isNativeObject(descriptor) || isBuiltin(descriptor)) {
+ return null;
+ }
+ if (!(descriptor instanceof ClassDescriptor)) {
+ return null;
+ }
+ ClassDescriptor cls = (ClassDescriptor) descriptor;
+ if (cls.getKind() == ClassKind.ENUM_ENTRY || cls.getKind() == ClassKind.OBJECT) {
+ return null;
+ }
+ DeclarationDescriptor container = descriptor.getContainingDeclaration();
+ if (container == null) {
+ return null;
+ }
+ return getQualifiedReference(container);
+ }
+ };
addRule(libraryObjectsHaveKotlinQualifier);
addRule(constructorOrCompanionObjectHasTheSameQualifierAsTheClass);
@@ -548,6 +569,7 @@ public JsExpression apply(@NotNull DeclarationDescriptor descriptor) {
addRule(packageLevelDeclarationsHaveEnclosingPackagesNamesAsQualifier);
addRule(nativeObjectsHaveNativePartOfFullQualifier);
addRule(staticMembersHaveContainerQualifier);
+ addRule(nestedClassesHaveContainerQualifier);
}
}
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/TranslationContext.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/TranslationContext.java
index 1c461208e665a..3b9dc1a9c9d20 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/TranslationContext.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/context/TranslationContext.java
@@ -21,10 +21,7 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.ReflectionTypes;
-import org.jetbrains.kotlin.descriptors.CallableDescriptor;
-import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
-import org.jetbrains.kotlin.descriptors.MemberDescriptor;
-import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor;
+import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.js.config.Config;
import org.jetbrains.kotlin.js.translate.intrinsic.Intrinsics;
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils;
@@ -32,6 +29,7 @@
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingContext;
import org.jetbrains.kotlin.resolve.BindingTrace;
+import org.jetbrains.kotlin.resolve.DescriptorUtils;
import java.util.HashMap;
import java.util.Map;
@@ -55,12 +53,16 @@ public class TranslationContext {
private final TranslationContext parent;
@Nullable
private final DefinitionPlace definitionPlace;
+ @Nullable
+ private final DeclarationDescriptor declarationDescriptor;
+ @Nullable
+ private final ClassDescriptor classDescriptor;
@NotNull
public static TranslationContext rootContext(@NotNull StaticContext staticContext, JsFunction rootFunction) {
DynamicContext rootDynamicContext = DynamicContext.rootContext(rootFunction.getScope(), rootFunction.getBody());
AliasingContext rootAliasingContext = AliasingContext.getCleanContext();
- return new TranslationContext(null, staticContext, rootDynamicContext, rootAliasingContext, null, null);
+ return new TranslationContext(null, staticContext, rootDynamicContext, rootAliasingContext, null, null, null);
}
private final Map<JsExpression, TemporaryConstVariable> expressionToTempConstVariableCache = new HashMap<JsExpression, TemporaryConstVariable>();
@@ -71,7 +73,8 @@ private TranslationContext(
@NotNull DynamicContext dynamicContext,
@NotNull AliasingContext aliasingContext,
@Nullable UsageTracker usageTracker,
- @Nullable DefinitionPlace definitionPlace
+ @Nullable DefinitionPlace definitionPlace,
+ @Nullable DeclarationDescriptor declarationDescriptor
) {
this.parent = parent;
this.dynamicContext = dynamicContext;
@@ -79,6 +82,14 @@ private TranslationContext(
this.aliasingContext = aliasingContext;
this.usageTracker = usageTracker;
this.definitionPlace = definitionPlace;
+ this.declarationDescriptor = declarationDescriptor;
+ if (declarationDescriptor instanceof ClassDescriptor
+ && !DescriptorUtils.isAnonymousObject(declarationDescriptor)
+ && !DescriptorUtils.isObject(declarationDescriptor)) {
+ this.classDescriptor = (ClassDescriptor) declarationDescriptor;
+ } else {
+ this.classDescriptor = parent != null ? parent.classDescriptor : null;
+ }
}
@Nullable
@@ -103,19 +114,22 @@ public TranslationContext newFunctionBody(@NotNull JsFunction fun, @Nullable Ali
aliasingContext = this.aliasingContext.inner();
}
- return new TranslationContext(this, this.staticContext, dynamicContext, aliasingContext, this.usageTracker, null);
+ return new TranslationContext(this, this.staticContext, dynamicContext, aliasingContext, this.usageTracker, null,
+ this.declarationDescriptor);
}
@NotNull
public TranslationContext newFunctionBodyWithUsageTracker(@NotNull JsFunction fun, @NotNull MemberDescriptor descriptor) {
DynamicContext dynamicContext = DynamicContext.newContext(fun.getScope(), fun.getBody());
UsageTracker usageTracker = new UsageTracker(this.usageTracker, descriptor, fun.getScope());
- return new TranslationContext(this, this.staticContext, dynamicContext, this.aliasingContext.inner(), usageTracker, this.definitionPlace);
+ return new TranslationContext(this, this.staticContext, dynamicContext, this.aliasingContext.inner(), usageTracker, this.definitionPlace,
+ this.declarationDescriptor);
}
@NotNull
public TranslationContext innerBlock(@NotNull JsBlock block) {
- return new TranslationContext(this, staticContext, dynamicContext.innerBlock(block), aliasingContext, usageTracker, null);
+ return new TranslationContext(this, staticContext, dynamicContext.innerBlock(block), aliasingContext, usageTracker, null,
+ this.declarationDescriptor);
}
@NotNull
@@ -126,12 +140,14 @@ public TranslationContext innerBlock() {
@NotNull
public TranslationContext newDeclaration(@NotNull DeclarationDescriptor descriptor, @Nullable DefinitionPlace place) {
DynamicContext dynamicContext = DynamicContext.newContext(getScopeForDescriptor(descriptor), getBlockForDescriptor(descriptor));
- return new TranslationContext(this, staticContext, dynamicContext, aliasingContext, usageTracker, place);
+ return new TranslationContext(this, staticContext, dynamicContext, aliasingContext, usageTracker, place,
+ descriptor);
}
@NotNull
private TranslationContext innerWithAliasingContext(AliasingContext aliasingContext) {
- return new TranslationContext(this, this.staticContext, this.dynamicContext, aliasingContext, this.usageTracker, null);
+ return new TranslationContext(this, this.staticContext, this.dynamicContext, aliasingContext, this.usageTracker, null,
+ this.declarationDescriptor);
}
@NotNull
@@ -319,7 +335,29 @@ public JsExpression getAliasForDescriptor(@NotNull DeclarationDescriptor descrip
@NotNull
public JsExpression getDispatchReceiver(@NotNull ReceiverParameterDescriptor descriptor) {
JsExpression alias = getAliasForDescriptor(descriptor);
- return alias == null ? JsLiteral.THIS : alias;
+ if (alias != null) {
+ return alias;
+ }
+ return getDispatchReceiverPath(getNearestClass(descriptor));
+ }
+
+ @NotNull
+ private JsExpression getDispatchReceiverPath(@Nullable ClassDescriptor cls) {
+ if (cls != null) {
+ JsExpression alias = getAliasForDescriptor(cls);
+ if (alias != null) {
+ return alias;
+ }
+ }
+ if (cls == classDescriptor || parent == null) {
+ return JsLiteral.THIS;
+ }
+ ClassDescriptor parentDescriptor = parent.classDescriptor;
+ if (classDescriptor != parentDescriptor) {
+ return new JsNameRef("$outer", parent.getDispatchReceiverPath(cls));
+ } else {
+ return parent.getDispatchReceiverPath(cls);
+ }
}
@NotNull
@@ -347,4 +385,17 @@ private JsNameRef captureIfNeedAndGetCapturedName(DeclarationDescriptor descript
return null;
}
+
+ private static ClassDescriptor getNearestClass(DeclarationDescriptor declaration) {
+ while (declaration != null) {
+ if (declaration instanceof ClassDescriptor) {
+ if (!DescriptorUtils.isAnonymousObject(declaration)
+ && !DescriptorUtils.isObject(declaration)) {
+ return (ClassDescriptor) declaration;
+ }
+ }
+ declaration = declaration.getContainingDeclaration();
+ }
+ return null;
+ }
}
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
index 2280cde4ac63f..02cff3705cf7d 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/DeclarationBodyVisitor.java
@@ -67,7 +67,8 @@ protected Void emptyResult(@NotNull TranslationContext context) {
}
@Override
- public Void visitClass(@NotNull KtClass expression, TranslationContext context) {
+ public Void visitClass(@NotNull KtClass declaration, TranslationContext context) {
+ staticResult.addAll(ClassTranslator.Companion.translate(declaration, context));
return null;
}
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/FileDeclaration.kt b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/FileDeclaration.kt
index 67fb980081210..9d313936e61cd 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/FileDeclaration.kt
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/declaration/FileDeclaration.kt
@@ -50,8 +50,8 @@ class FileDeclarationVisitor(
}
}
- override fun visitClass(expression: KtClass, context: TranslationContext?): Void? {
- result.addAll(ClassTranslator.translate(expression, context!!))
+ override fun visitClass(declaration: KtClass, context: TranslationContext?): Void? {
+ result.addAll(ClassTranslator.translate(declaration, context!!))
return null
}
diff --git a/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/ClassInitializerTranslator.java b/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/ClassInitializerTranslator.java
index df9c13ef6a2bb..580e38a836d98 100644
--- a/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/ClassInitializerTranslator.java
+++ b/js/js.translator/src/org/jetbrains/kotlin/js/translate/initializer/ClassInitializerTranslator.java
@@ -84,6 +84,7 @@ private static JsFunction createInitFunction(KtClassOrObject declaration, Transl
@NotNull
public JsFunction generateInitializeMethod(DelegationTranslator delegationTranslator) {
ClassDescriptor classDescriptor = getClassDescriptor(bindingContext(), classDeclaration);
+ addOuterClassReference(classDescriptor);
ConstructorDescriptor primaryConstructor = classDescriptor.getUnsubstitutedPrimaryConstructor();
if (primaryConstructor != null) {
@@ -113,6 +114,22 @@ public JsFunction generateInitializeMethod(DelegationTranslator delegationTransl
return initFunction;
}
+ private void addOuterClassReference(ClassDescriptor classDescriptor) {
+ DeclarationDescriptor container = classDescriptor.getContainingDeclaration();
+ if (!(container instanceof ClassDescriptor) || !classDescriptor.isInner()) {
+ return;
+ }
+
+ // TODO: avoid name clashing
+ JsName outerName = initFunction.getScope().declareName("$outer");
+ initFunction.getParameters().add(0, new JsParameter(outerName));
+
+ JsExpression target = new JsNameRef(outerName, JsLiteral.THIS);
+ JsExpression paramRef = new JsNameRef(outerName);
+ JsExpression assignment = new JsBinaryOperation(JsBinaryOperator.ASG, target, paramRef);
+ initFunction.getBody().getStatements().add(new JsExpressionStatement(assignment));
+ }
+
@NotNull
public JsExpression generateEnumEntryInstanceCreation(@NotNull KotlinType enumClassType) {
ResolvedCall<FunctionDescriptor> superCall = getSuperCall();
diff --git a/js/js.translator/testData/kotlin_lib_ecma5.js b/js/js.translator/testData/kotlin_lib_ecma5.js
index fd799ac5cd851..ce75f44f05197 100644
--- a/js/js.translator/testData/kotlin_lib_ecma5.js
+++ b/js/js.translator/testData/kotlin_lib_ecma5.js
@@ -91,19 +91,22 @@ var Kotlin = {};
}
}
- function computeMetadata(bases, properties) {
+ function computeMetadata(bases, properties, staticProperties) {
var metadata = {};
+ var p, property;
metadata.baseClasses = toArray(bases);
metadata.baseClass = getClass(metadata.baseClasses);
metadata.classIndex = Kotlin.newClassIndex();
metadata.functions = {};
metadata.properties = {};
+ metadata.types = {};
+ metadata.staticMembers = {};
if (!(properties == null)) {
- for (var p in properties) {
+ for (p in properties) {
if (properties.hasOwnProperty(p)) {
- var property = properties[p];
+ property = properties[p];
property.$classIndex$ = metadata.classIndex;
if (typeof property === "function") {
metadata.functions[p] = property;
@@ -114,6 +117,19 @@ var Kotlin = {};
}
}
}
+ if (typeof staticProperties !== 'undefined') {
+ for (p in staticProperties) {
+ if (!staticProperties.hasOwnProperty(p)) {
+ continue;
+ }
+ property = staticProperties[p];
+ if (typeof property === "function" && typeof property.type !== "undefined" && property.type === Kotlin.TYPE.INIT_FUN) {
+ metadata.types[p] = property;
+ } else {
+ metadata.staticMembers[p] = property;
+ }
+ }
+ }
applyExtension(metadata.functions, metadata.baseClasses, function (it) {
return it.$metadata$.functions
});
@@ -146,10 +162,10 @@ var Kotlin = {};
if (constructor == null) {
constructor = emptyFunction();
}
- copyProperties(constructor, staticProperties);
- var metadata = computeMetadata(bases, properties);
+ var metadata = computeMetadata(bases, properties, staticProperties);
metadata.type = Kotlin.TYPE.CLASS;
+ copyProperties(constructor, metadata.staticMembers);
var prototypeObj;
if (metadata.baseClass !== null) {
@@ -161,6 +177,14 @@ var Kotlin = {};
Object.defineProperties(prototypeObj, metadata.properties);
copyProperties(prototypeObj, metadata.functions);
prototypeObj.constructor = constructor;
+ for (var innerType in metadata.types) {
+ if (metadata.types.hasOwnProperty(innerType)) {
+ Object.defineProperty(constructor, innerType, {
+ get: metadata.types[innerType],
+ configurable: true
+ });
+ }
+ }
if (metadata.baseClass != null) {
constructor.baseInitializer = metadata.baseClass;
@@ -181,15 +205,25 @@ var Kotlin = {};
Kotlin.createTraitNow = function (bases, properties, staticProperties) {
var obj = function () {};
- copyProperties(obj, staticProperties);
- obj.$metadata$ = computeMetadata(bases, properties);
+ obj.$metadata$ = computeMetadata(bases, properties, staticProperties);
obj.$metadata$.type = Kotlin.TYPE.TRAIT;
+ copyProperties(obj, obj.$metadata$.staticMembers);
obj.prototype = {};
Object.defineProperties(obj.prototype, obj.$metadata$.properties);
copyProperties(obj.prototype, obj.$metadata$.functions);
Object.defineProperty(obj, "object", {get: class_object, configurable: true});
+
+ for (var innerType in obj.$metadata$.types) {
+ if (obj.$metadata$.types.hasOwnProperty(innerType)) {
+ Object.defineProperty(constructor, innerType, {
+ get: obj.$metadata$.types[innerType],
+ configurable: true
+ });
+ }
+ }
+
return obj;
};
diff --git a/js/js.translator/testData/nestedTypes/cases/inner.kt b/js/js.translator/testData/nestedTypes/cases/inner.kt
new file mode 100644
index 0000000000000..f6b40471caf0c
--- /dev/null
+++ b/js/js.translator/testData/nestedTypes/cases/inner.kt
@@ -0,0 +1,14 @@
+package foo
+
+open class A(val x: Int, val y: Int) {
+ inner class B(val z: Int) {
+ fun foo() = x + y + z
+ }
+}
+
+fun box(): String {
+ val a = A(2, 3)
+ val b = a.B(4)
+ return if (b.foo() == 9) "OK" else "failure"
+}
+
diff --git a/js/js.translator/testData/nestedTypes/cases/nested.kt b/js/js.translator/testData/nestedTypes/cases/nested.kt
new file mode 100644
index 0000000000000..62c75ccbb1364
--- /dev/null
+++ b/js/js.translator/testData/nestedTypes/cases/nested.kt
@@ -0,0 +1,10 @@
+package foo
+
+open class A(val x: Int) {
+ class B : A(5)
+}
+
+fun box(): String {
+ return if (A(7).x + A.B().x == 12) "OK" else "failed"
+}
+
|
393b67f7a03d76698375be3350ff9282661fbf21
|
intellij-community
|
tests repaired--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java
index 320c63cad8d51..49c1c33c10572 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/MethodChainsCompletionTest.java
@@ -109,7 +109,7 @@ public void testResultsForSuperClassesShowed() {
assertOneElement(doCompletion());
}
- public void testInnerClasses() {
+ public void _testInnerClasses() {
assertAdvisorLookupElementEquals("j.getEntry", 0, 8, 1, 0, assertOneElement(doCompletion()));
}
|
7d26cffb0cb21c16b335e8ae9b02523565ad3b5d
|
hadoop
|
YARN-2819. NPE in ATS Timeline Domains when- upgrading from 2.4 to 2.6. Contributed by Zhijie Shen--(cherry picked from commit 4a114dd67aae83e5bb2d65470166de954acf36a2)-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index f3c9d4e207307..bb94797db81cd 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -884,6 +884,9 @@ Release 2.6.0 - UNRELEASED
YARN-2825. Container leak on NM (Jian He via jlowe)
+ YARN-2819. NPE in ATS Timeline Domains when upgrading from 2.4 to 2.6.
+ (Zhijie Shen via xgong)
+
Release 2.5.2 - UNRELEASED
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/LeveldbTimelineStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/LeveldbTimelineStore.java
index e1f790d9da768..c4ea9960ad739 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/LeveldbTimelineStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/LeveldbTimelineStore.java
@@ -792,7 +792,8 @@ private TimelineEntities getEntityByTime(byte[] base,
* Put a single entity. If there is an error, add a TimelinePutError to the
* given response.
*/
- private void put(TimelineEntity entity, TimelinePutResponse response) {
+ private void put(TimelineEntity entity, TimelinePutResponse response,
+ boolean allowEmptyDomainId) {
LockMap.CountingReentrantLock<EntityIdentifier> lock =
writeLocks.getLock(new EntityIdentifier(entity.getEntityId(),
entity.getEntityType()));
@@ -867,10 +868,18 @@ private void put(TimelineEntity entity, TimelinePutResponse response) {
new EntityIdentifier(relatedEntityId, relatedEntityType));
continue;
} else {
+ // This is the existing entity
byte[] domainIdBytes = db.get(createDomainIdKey(
relatedEntityId, relatedEntityType, relatedEntityStartTime));
- // This is the existing entity
- String domainId = new String(domainIdBytes);
+ // The timeline data created by the server before 2.6 won't have
+ // the domain field. We assume this timeline data is in the
+ // default timeline domain.
+ String domainId = null;
+ if (domainIdBytes == null) {
+ domainId = TimelineDataManager.DEFAULT_DOMAIN_ID;
+ } else {
+ domainId = new String(domainIdBytes);
+ }
if (!domainId.equals(entity.getDomainId())) {
// in this case the entity will be put, but the relation will be
// ignored
@@ -923,12 +932,14 @@ private void put(TimelineEntity entity, TimelinePutResponse response) {
entity.getEntityType(), revStartTime);
if (entity.getDomainId() == null ||
entity.getDomainId().length() == 0) {
- TimelinePutError error = new TimelinePutError();
- error.setEntityId(entity.getEntityId());
- error.setEntityType(entity.getEntityType());
- error.setErrorCode(TimelinePutError.NO_DOMAIN);
- response.addError(error);
- return;
+ if (!allowEmptyDomainId) {
+ TimelinePutError error = new TimelinePutError();
+ error.setEntityId(entity.getEntityId());
+ error.setEntityType(entity.getEntityType());
+ error.setErrorCode(TimelinePutError.NO_DOMAIN);
+ response.addError(error);
+ return;
+ }
} else {
writeBatch.put(key, entity.getDomainId().getBytes());
writePrimaryFilterEntries(writeBatch, primaryFilters, key,
@@ -1011,7 +1022,22 @@ public TimelinePutResponse put(TimelineEntities entities) {
deleteLock.readLock().lock();
TimelinePutResponse response = new TimelinePutResponse();
for (TimelineEntity entity : entities.getEntities()) {
- put(entity, response);
+ put(entity, response, false);
+ }
+ return response;
+ } finally {
+ deleteLock.readLock().unlock();
+ }
+ }
+
+ @Private
+ @VisibleForTesting
+ public TimelinePutResponse putWithNoDomainId(TimelineEntities entities) {
+ try {
+ deleteLock.readLock().lock();
+ TimelinePutResponse response = new TimelinePutResponse();
+ for (TimelineEntity entity : entities.getEntities()) {
+ put(entity, response, true);
}
return response;
} finally {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineDataManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineDataManager.java
index 7ef0a67dac81f..888c28311579e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineDataManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/timeline/TimelineDataManager.java
@@ -124,6 +124,7 @@ public TimelineEntities getEntities(
entities.getEntities().iterator();
while (entitiesItr.hasNext()) {
TimelineEntity entity = entitiesItr.next();
+ addDefaultDomainIdIfAbsent(entity);
try {
// check ACLs
if (!timelineACLsManager.checkAccess(
@@ -161,6 +162,7 @@ public TimelineEntity getEntity(
entity =
store.getEntity(entityId, entityType, fields);
if (entity != null) {
+ addDefaultDomainIdIfAbsent(entity);
// check ACLs
if (!timelineACLsManager.checkAccess(
callerUGI, ApplicationAccessType.VIEW_APP, entity)) {
@@ -203,6 +205,7 @@ public TimelineEvents getEvents(
eventsOfOneEntity.getEntityId(),
eventsOfOneEntity.getEntityType(),
EnumSet.of(Field.PRIMARY_FILTERS));
+ addDefaultDomainIdIfAbsent(entity);
// check ACLs
if (!timelineACLsManager.checkAccess(
callerUGI, ApplicationAccessType.VIEW_APP, entity)) {
@@ -254,10 +257,12 @@ public TimelinePutResponse postEntities(
existingEntity =
store.getEntity(entityID.getId(), entityID.getType(),
EnumSet.of(Field.PRIMARY_FILTERS));
- if (existingEntity != null &&
- !existingEntity.getDomainId().equals(entity.getDomainId())) {
- throw new YarnException("The domain of the timeline entity "
- + entityID + " is not allowed to be changed.");
+ if (existingEntity != null) {
+ addDefaultDomainIdIfAbsent(existingEntity);
+ if (!existingEntity.getDomainId().equals(entity.getDomainId())) {
+ throw new YarnException("The domain of the timeline entity "
+ + entityID + " is not allowed to be changed.");
+ }
}
if (!timelineACLsManager.checkAccess(
callerUGI, ApplicationAccessType.MODIFY_APP, entity)) {
@@ -355,4 +360,11 @@ public TimelineDomains getDomains(String owner,
}
}
+ private static void addDefaultDomainIdIfAbsent(TimelineEntity entity) {
+ // be compatible with the timeline data created before 2.6
+ if (entity.getDomainId() == null) {
+ entity.setDomainId(DEFAULT_DOMAIN_ID);
+ }
+ }
+
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestLeveldbTimelineStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestLeveldbTimelineStore.java
index f315930812782..5ebc96b627b5c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestLeveldbTimelineStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestLeveldbTimelineStore.java
@@ -40,6 +40,7 @@
import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities;
import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity;
import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse;
+import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse.TimelinePutError;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.records.Version;
import org.apache.hadoop.yarn.server.timeline.LeveldbTimelineStore;
@@ -160,12 +161,13 @@ private boolean deleteNextEntity(String entityType, byte[] ts)
@Test
public void testGetEntityTypes() throws IOException {
List<String> entityTypes = ((LeveldbTimelineStore)store).getEntityTypes();
- assertEquals(5, entityTypes.size());
- assertEquals(entityType1, entityTypes.get(0));
- assertEquals(entityType2, entityTypes.get(1));
- assertEquals(entityType4, entityTypes.get(2));
- assertEquals(entityType5, entityTypes.get(3));
- assertEquals(entityType7, entityTypes.get(4));
+ assertEquals(6, entityTypes.size());
+ assertEquals("OLD_ENTITY_TYPE_1", entityTypes.get(0));
+ assertEquals(entityType1, entityTypes.get(1));
+ assertEquals(entityType2, entityTypes.get(2));
+ assertEquals(entityType4, entityTypes.get(3));
+ assertEquals(entityType5, entityTypes.get(4));
+ assertEquals(entityType7, entityTypes.get(5));
}
@Test
@@ -196,7 +198,7 @@ public void testDeleteEntities() throws IOException, InterruptedException {
((LeveldbTimelineStore)store).discardOldEntities(-123l);
assertEquals(2, getEntities("type_1").size());
assertEquals(0, getEntities("type_2").size());
- assertEquals(4, ((LeveldbTimelineStore)store).getEntityTypes().size());
+ assertEquals(5, ((LeveldbTimelineStore)store).getEntityTypes().size());
((LeveldbTimelineStore)store).discardOldEntities(123l);
assertEquals(0, getEntities("type_1").size());
@@ -327,4 +329,69 @@ public void testGetDomains() throws IOException {
super.testGetDomains();
}
+ @Test
+ public void testRelatingToNonExistingEntity() throws IOException {
+ TimelineEntity entityToStore = new TimelineEntity();
+ entityToStore.setEntityType("TEST_ENTITY_TYPE_1");
+ entityToStore.setEntityId("TEST_ENTITY_ID_1");
+ entityToStore.setDomainId(TimelineDataManager.DEFAULT_DOMAIN_ID);
+ entityToStore.addRelatedEntity("TEST_ENTITY_TYPE_2", "TEST_ENTITY_ID_2");
+ TimelineEntities entities = new TimelineEntities();
+ entities.addEntity(entityToStore);
+ store.put(entities);
+ TimelineEntity entityToGet =
+ store.getEntity("TEST_ENTITY_ID_2", "TEST_ENTITY_TYPE_2", null);
+ Assert.assertNotNull(entityToGet);
+ Assert.assertEquals("DEFAULT", entityToGet.getDomainId());
+ Assert.assertEquals("TEST_ENTITY_TYPE_1",
+ entityToGet.getRelatedEntities().keySet().iterator().next());
+ Assert.assertEquals("TEST_ENTITY_ID_1",
+ entityToGet.getRelatedEntities().values().iterator().next()
+ .iterator().next());
+ }
+
+ @Test
+ public void testRelatingToOldEntityWithoutDomainId() throws IOException {
+ // New entity is put in the default domain
+ TimelineEntity entityToStore = new TimelineEntity();
+ entityToStore.setEntityType("NEW_ENTITY_TYPE_1");
+ entityToStore.setEntityId("NEW_ENTITY_ID_1");
+ entityToStore.setDomainId(TimelineDataManager.DEFAULT_DOMAIN_ID);
+ entityToStore.addRelatedEntity("OLD_ENTITY_TYPE_1", "OLD_ENTITY_ID_1");
+ TimelineEntities entities = new TimelineEntities();
+ entities.addEntity(entityToStore);
+ store.put(entities);
+
+ TimelineEntity entityToGet =
+ store.getEntity("OLD_ENTITY_ID_1", "OLD_ENTITY_TYPE_1", null);
+ Assert.assertNotNull(entityToGet);
+ Assert.assertNull(entityToGet.getDomainId());
+ Assert.assertEquals("NEW_ENTITY_TYPE_1",
+ entityToGet.getRelatedEntities().keySet().iterator().next());
+ Assert.assertEquals("NEW_ENTITY_ID_1",
+ entityToGet.getRelatedEntities().values().iterator().next()
+ .iterator().next());
+
+ // New entity is not put in the default domain
+ entityToStore = new TimelineEntity();
+ entityToStore.setEntityType("NEW_ENTITY_TYPE_2");
+ entityToStore.setEntityId("NEW_ENTITY_ID_2");
+ entityToStore.setDomainId("NON_DEFAULT");
+ entityToStore.addRelatedEntity("OLD_ENTITY_TYPE_1", "OLD_ENTITY_ID_1");
+ entities = new TimelineEntities();
+ entities.addEntity(entityToStore);
+ TimelinePutResponse response = store.put(entities);
+ Assert.assertEquals(1, response.getErrors().size());
+ Assert.assertEquals(TimelinePutError.FORBIDDEN_RELATION,
+ response.getErrors().get(0).getErrorCode());
+ entityToGet =
+ store.getEntity("OLD_ENTITY_ID_1", "OLD_ENTITY_TYPE_1", null);
+ Assert.assertNotNull(entityToGet);
+ Assert.assertNull(entityToGet.getDomainId());
+ // Still have one related entity
+ Assert.assertEquals(1, entityToGet.getRelatedEntities().keySet().size());
+ Assert.assertEquals(1, entityToGet.getRelatedEntities().values()
+ .iterator().next().size());
+ }
+
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestTimelineDataManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestTimelineDataManager.java
new file mode 100644
index 0000000000000..f74956735a34b
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TestTimelineDataManager.java
@@ -0,0 +1,152 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.yarn.server.timeline;
+
+import java.io.File;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileContext;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities;
+import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity;
+import org.apache.hadoop.yarn.api.records.timeline.TimelinePutResponse;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.server.timeline.security.TimelineACLsManager;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+
+public class TestTimelineDataManager extends TimelineStoreTestUtils {
+
+ private FileContext fsContext;
+ private File fsPath;
+ private TimelineDataManager dataManaer;
+
+ @Before
+ public void setup() throws Exception {
+ fsPath = new File("target", this.getClass().getSimpleName() +
+ "-tmpDir").getAbsoluteFile();
+ fsContext = FileContext.getLocalFSFileContext();
+ fsContext.delete(new Path(fsPath.getAbsolutePath()), true);
+ Configuration conf = new YarnConfiguration();
+ conf.set(YarnConfiguration.TIMELINE_SERVICE_LEVELDB_PATH,
+ fsPath.getAbsolutePath());
+ conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_TTL_ENABLE, false);
+ store = new LeveldbTimelineStore();
+ store.init(conf);
+ store.start();
+ loadTestEntityData();
+ loadVerificationEntityData();
+ loadTestDomainData();
+
+ TimelineACLsManager aclsManager = new TimelineACLsManager(conf);
+ dataManaer = new TimelineDataManager(store, aclsManager);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (store != null) {
+ store.stop();
+ }
+ if (fsContext != null) {
+ fsContext.delete(new Path(fsPath.getAbsolutePath()), true);
+ }
+ }
+
+ @Test
+ public void testGetOldEntityWithOutDomainId() throws Exception {
+ TimelineEntity entity = dataManaer.getEntity(
+ "OLD_ENTITY_TYPE_1", "OLD_ENTITY_ID_1", null,
+ UserGroupInformation.getCurrentUser());
+ Assert.assertNotNull(entity);
+ Assert.assertEquals("OLD_ENTITY_ID_1", entity.getEntityId());
+ Assert.assertEquals("OLD_ENTITY_TYPE_1", entity.getEntityType());
+ Assert.assertEquals(
+ TimelineDataManager.DEFAULT_DOMAIN_ID, entity.getDomainId());
+ }
+
+ @Test
+ public void testGetOldEntitiesWithOutDomainId() throws Exception {
+ TimelineEntities entities = dataManaer.getEntities(
+ "OLD_ENTITY_TYPE_1", null, null, null, null, null, null, null, null,
+ UserGroupInformation.getCurrentUser());
+ Assert.assertEquals(2, entities.getEntities().size());
+ Assert.assertEquals("OLD_ENTITY_ID_2",
+ entities.getEntities().get(0).getEntityId());
+ Assert.assertEquals("OLD_ENTITY_TYPE_1",
+ entities.getEntities().get(0).getEntityType());
+ Assert.assertEquals(TimelineDataManager.DEFAULT_DOMAIN_ID,
+ entities.getEntities().get(0).getDomainId());
+ Assert.assertEquals("OLD_ENTITY_ID_1",
+ entities.getEntities().get(1).getEntityId());
+ Assert.assertEquals("OLD_ENTITY_TYPE_1",
+ entities.getEntities().get(1).getEntityType());
+ Assert.assertEquals(TimelineDataManager.DEFAULT_DOMAIN_ID,
+ entities.getEntities().get(1).getDomainId());
+ }
+
+ @Test
+ public void testUpdatingOldEntityWithoutDomainId() throws Exception {
+ // Set the domain to the default domain when updating
+ TimelineEntity entity = new TimelineEntity();
+ entity.setEntityType("OLD_ENTITY_TYPE_1");
+ entity.setEntityId("OLD_ENTITY_ID_1");
+ entity.setDomainId(TimelineDataManager.DEFAULT_DOMAIN_ID);
+ entity.addOtherInfo("NEW_OTHER_INFO_KEY", "NEW_OTHER_INFO_VALUE");
+ TimelineEntities entities = new TimelineEntities();
+ entities.addEntity(entity);
+ TimelinePutResponse response = dataManaer.postEntities(
+ entities, UserGroupInformation.getCurrentUser());
+ Assert.assertEquals(0, response.getErrors().size());
+ entity = store.getEntity("OLD_ENTITY_ID_1", "OLD_ENTITY_TYPE_1", null);
+ Assert.assertNotNull(entity);
+ // Even in leveldb, the domain is updated to the default domain Id
+ Assert.assertEquals(
+ TimelineDataManager.DEFAULT_DOMAIN_ID, entity.getDomainId());
+ Assert.assertEquals(1, entity.getOtherInfo().size());
+ Assert.assertEquals("NEW_OTHER_INFO_KEY",
+ entity.getOtherInfo().keySet().iterator().next());
+ Assert.assertEquals("NEW_OTHER_INFO_VALUE",
+ entity.getOtherInfo().values().iterator().next());
+
+ // Set the domain to the non-default domain when updating
+ entity = new TimelineEntity();
+ entity.setEntityType("OLD_ENTITY_TYPE_1");
+ entity.setEntityId("OLD_ENTITY_ID_2");
+ entity.setDomainId("NON_DEFAULT");
+ entity.addOtherInfo("NEW_OTHER_INFO_KEY", "NEW_OTHER_INFO_VALUE");
+ entities = new TimelineEntities();
+ entities.addEntity(entity);
+ response = dataManaer.postEntities(
+ entities, UserGroupInformation.getCurrentUser());
+ Assert.assertEquals(1, response.getErrors().size());
+ Assert.assertEquals(TimelinePutResponse.TimelinePutError.ACCESS_DENIED,
+ response.getErrors().get(0).getErrorCode());
+ entity = store.getEntity("OLD_ENTITY_ID_2", "OLD_ENTITY_TYPE_1", null);
+ Assert.assertNotNull(entity);
+ // In leveldb, the domain Id is still null
+ Assert.assertNull(entity.getDomainId());
+ // Updating is not executed
+ Assert.assertEquals(0, entity.getOtherInfo().size());
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TimelineStoreTestUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TimelineStoreTestUtils.java
index 242478cafa983..6f15b9245b8d5 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TimelineStoreTestUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/test/java/org/apache/hadoop/yarn/server/timeline/TimelineStoreTestUtils.java
@@ -210,6 +210,18 @@ protected void loadTestEntityData() throws IOException {
assertEquals(entityId7, response.getErrors().get(0).getEntityId());
assertEquals(TimelinePutError.FORBIDDEN_RELATION,
response.getErrors().get(0).getErrorCode());
+
+ if (store instanceof LeveldbTimelineStore) {
+ LeveldbTimelineStore leveldb = (LeveldbTimelineStore) store;
+ entities.setEntities(Collections.singletonList(createEntity(
+ "OLD_ENTITY_ID_1", "OLD_ENTITY_TYPE_1", 63l, null, null, null, null,
+ null)));
+ leveldb.putWithNoDomainId(entities);
+ entities.setEntities(Collections.singletonList(createEntity(
+ "OLD_ENTITY_ID_2", "OLD_ENTITY_TYPE_1", 64l, null, null, null, null,
+ null)));
+ leveldb.putWithNoDomainId(entities);
+ }
}
/**
|
dffe4faa12ef455d5eec4ee29cdec839e041914e
|
Delta Spike
|
[maven-release-plugin] prepare release deltaspike-project-0.5
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/cdictrl/api/pom.xml b/deltaspike/cdictrl/api/pom.xml
index b13157eee..f7dc8cc31 100644
--- a/deltaspike/cdictrl/api/pom.xml
+++ b/deltaspike/cdictrl/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml
index a8ab98ebf..21bbd7173 100644
--- a/deltaspike/cdictrl/impl-openejb/pom.xml
+++ b/deltaspike/cdictrl/impl-openejb/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-owb/pom.xml b/deltaspike/cdictrl/impl-owb/pom.xml
index 1aff43453..87b494209 100644
--- a/deltaspike/cdictrl/impl-owb/pom.xml
+++ b/deltaspike/cdictrl/impl-owb/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/impl-weld/pom.xml b/deltaspike/cdictrl/impl-weld/pom.xml
index f32ca1344..3a69b080b 100644
--- a/deltaspike/cdictrl/impl-weld/pom.xml
+++ b/deltaspike/cdictrl/impl-weld/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/pom.xml b/deltaspike/cdictrl/pom.xml
index eea1091e1..d305fda8f 100644
--- a/deltaspike/cdictrl/pom.xml
+++ b/deltaspike/cdictrl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
diff --git a/deltaspike/cdictrl/tck/pom.xml b/deltaspike/cdictrl/tck/pom.xml
index 623d079b9..2e286017c 100644
--- a/deltaspike/cdictrl/tck/pom.xml
+++ b/deltaspike/cdictrl/tck/pom.xml
@@ -22,7 +22,7 @@
<parent>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>cdictrl-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/checkstyle-rules/pom.xml b/deltaspike/checkstyle-rules/pom.xml
index 18da99bf7..22b30783e 100644
--- a/deltaspike/checkstyle-rules/pom.xml
+++ b/deltaspike/checkstyle-rules/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/api/pom.xml b/deltaspike/core/api/pom.xml
index 11717aa22..bf3afbc9a 100644
--- a/deltaspike/core/api/pom.xml
+++ b/deltaspike/core/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>core-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/impl/pom.xml b/deltaspike/core/impl/pom.xml
index 3db7f1249..223e53602 100644
--- a/deltaspike/core/impl/pom.xml
+++ b/deltaspike/core/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>core-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/core/pom.xml b/deltaspike/core/pom.xml
index c36bd601a..d825cde78 100644
--- a/deltaspike/core/pom.xml
+++ b/deltaspike/core/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent-code</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../parent/code/pom.xml</relativePath>
</parent>
diff --git a/deltaspike/examples/jse-examples/pom.xml b/deltaspike/examples/jse-examples/pom.xml
index c19800dc2..5adde3fbf 100644
--- a/deltaspike/examples/jse-examples/pom.xml
+++ b/deltaspike/examples/jse-examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.examples</groupId>
<artifactId>examples-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.examples</groupId>
diff --git a/deltaspike/examples/jsf-examples/pom.xml b/deltaspike/examples/jsf-examples/pom.xml
index 3e6cfa9e8..e4b94a9e7 100644
--- a/deltaspike/examples/jsf-examples/pom.xml
+++ b/deltaspike/examples/jsf-examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.examples</groupId>
<artifactId>examples-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-jsf-example</artifactId>
diff --git a/deltaspike/examples/pom.xml b/deltaspike/examples/pom.xml
index a6836acbb..35436f83e 100644
--- a/deltaspike/examples/pom.xml
+++ b/deltaspike/examples/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
diff --git a/deltaspike/modules/bean-validation/api/pom.xml b/deltaspike/modules/bean-validation/api/pom.xml
index 688a9216f..a71386bf7 100644
--- a/deltaspike/modules/bean-validation/api/pom.xml
+++ b/deltaspike/modules/bean-validation/api/pom.xml
@@ -9,14 +9,13 @@
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. -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>bean-validation-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-bean-validation-module-api</artifactId>
diff --git a/deltaspike/modules/bean-validation/impl/pom.xml b/deltaspike/modules/bean-validation/impl/pom.xml
index d54e887d4..d41c44927 100644
--- a/deltaspike/modules/bean-validation/impl/pom.xml
+++ b/deltaspike/modules/bean-validation/impl/pom.xml
@@ -9,14 +9,13 @@
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. -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>bean-validation-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-bean-validation-module-impl</artifactId>
diff --git a/deltaspike/modules/bean-validation/pom.xml b/deltaspike/modules/bean-validation/pom.xml
index 541b2616e..f95e654bb 100644
--- a/deltaspike/modules/bean-validation/pom.xml
+++ b/deltaspike/modules/bean-validation/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>bean-validation-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike BeanValidation-Module</name>
diff --git a/deltaspike/modules/data/api/pom.xml b/deltaspike/modules/data/api/pom.xml
index 1c449dd0a..f331ccfd0 100755
--- a/deltaspike/modules/data/api/pom.xml
+++ b/deltaspike/modules/data/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>data-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-data-module-api</artifactId>
diff --git a/deltaspike/modules/data/impl/pom.xml b/deltaspike/modules/data/impl/pom.xml
index 27537182b..3ca03f0b8 100755
--- a/deltaspike/modules/data/impl/pom.xml
+++ b/deltaspike/modules/data/impl/pom.xml
@@ -17,14 +17,13 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>data-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-data-module-impl</artifactId>
diff --git a/deltaspike/modules/data/pom.xml b/deltaspike/modules/data/pom.xml
index 3297c156b..2ef9788ad 100755
--- a/deltaspike/modules/data/pom.xml
+++ b/deltaspike/modules/data/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>data-module-project</artifactId>
diff --git a/deltaspike/modules/jpa/api/pom.xml b/deltaspike/modules/jpa/api/pom.xml
index b770767d9..a4d691fb9 100644
--- a/deltaspike/modules/jpa/api/pom.xml
+++ b/deltaspike/modules/jpa/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jpa/impl/pom.xml b/deltaspike/modules/jpa/impl/pom.xml
index ce39da7ec..85f09cf5b 100644
--- a/deltaspike/modules/jpa/impl/pom.xml
+++ b/deltaspike/modules/jpa/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jpa/pom.xml b/deltaspike/modules/jpa/pom.xml
index 615992947..8015e0cc9 100644
--- a/deltaspike/modules/jpa/pom.xml
+++ b/deltaspike/modules/jpa/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jpa-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike JPA-Module</name>
diff --git a/deltaspike/modules/jsf/api/pom.xml b/deltaspike/modules/jsf/api/pom.xml
index 8492a2541..22eecb295 100644
--- a/deltaspike/modules/jsf/api/pom.xml
+++ b/deltaspike/modules/jsf/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jsf/impl/pom.xml b/deltaspike/modules/jsf/impl/pom.xml
index e23fde094..67162998f 100644
--- a/deltaspike/modules/jsf/impl/pom.xml
+++ b/deltaspike/modules/jsf/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/jsf/pom.xml b/deltaspike/modules/jsf/pom.xml
index 117c2f916..77c09cdb8 100644
--- a/deltaspike/modules/jsf/pom.xml
+++ b/deltaspike/modules/jsf/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>jsf-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike JSF-Module</name>
diff --git a/deltaspike/modules/partial-bean/api/pom.xml b/deltaspike/modules/partial-bean/api/pom.xml
index abfa1b47a..02ce4174c 100644
--- a/deltaspike/modules/partial-bean/api/pom.xml
+++ b/deltaspike/modules/partial-bean/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/partial-bean/impl/pom.xml b/deltaspike/modules/partial-bean/impl/pom.xml
index 7833c3410..16dc45e51 100644
--- a/deltaspike/modules/partial-bean/impl/pom.xml
+++ b/deltaspike/modules/partial-bean/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/partial-bean/pom.xml b/deltaspike/modules/partial-bean/pom.xml
index cda936091..16d08531f 100644
--- a/deltaspike/modules/partial-bean/pom.xml
+++ b/deltaspike/modules/partial-bean/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>partial-bean-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike Partial-Bean-Module</name>
diff --git a/deltaspike/modules/pom.xml b/deltaspike/modules/pom.xml
index 7fe9ba883..793c61258 100644
--- a/deltaspike/modules/pom.xml
+++ b/deltaspike/modules/pom.xml
@@ -23,13 +23,13 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent-code</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../parent/code/pom.xml</relativePath>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike Modules</name>
diff --git a/deltaspike/modules/security/api/pom.xml b/deltaspike/modules/security/api/pom.xml
index a89bc91ec..d4459c8f0 100644
--- a/deltaspike/modules/security/api/pom.xml
+++ b/deltaspike/modules/security/api/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/security/impl/pom.xml b/deltaspike/modules/security/impl/pom.xml
index 170725256..79fa93475 100644
--- a/deltaspike/modules/security/impl/pom.xml
+++ b/deltaspike/modules/security/impl/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
diff --git a/deltaspike/modules/security/pom.xml b/deltaspike/modules/security/pom.xml
index e3749c514..2432d63cc 100644
--- a/deltaspike/modules/security/pom.xml
+++ b/deltaspike/modules/security/pom.xml
@@ -23,12 +23,12 @@
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>security-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike Security-Module</name>
diff --git a/deltaspike/modules/servlet/api/pom.xml b/deltaspike/modules/servlet/api/pom.xml
index 965806c4b..bcfbfe6c3 100644
--- a/deltaspike/modules/servlet/api/pom.xml
+++ b/deltaspike/modules/servlet/api/pom.xml
@@ -17,14 +17,13 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>servlet-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-servlet-module-api</artifactId>
diff --git a/deltaspike/modules/servlet/impl/pom.xml b/deltaspike/modules/servlet/impl/pom.xml
index 2f5c3dc0e..8b2a09cf5 100644
--- a/deltaspike/modules/servlet/impl/pom.xml
+++ b/deltaspike/modules/servlet/impl/pom.xml
@@ -17,14 +17,13 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>servlet-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<artifactId>deltaspike-servlet-module-impl</artifactId>
diff --git a/deltaspike/modules/servlet/pom.xml b/deltaspike/modules/servlet/pom.xml
index d7a18276e..496361a8a 100644
--- a/deltaspike/modules/servlet/pom.xml
+++ b/deltaspike/modules/servlet/pom.xml
@@ -17,19 +17,18 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>modules-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
</parent>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>servlet-module-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike Servlet-Module</name>
diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml
index dd60d0304..89e61cdf4 100644
--- a/deltaspike/parent/code/pom.xml
+++ b/deltaspike/parent/code/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml
index 52e2fba54..c4110e168 100644
--- a/deltaspike/parent/pom.xml
+++ b/deltaspike/parent/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../pom.xml</relativePath>
</parent>
diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml
index a8eb20b99..d75c7cf8f 100644
--- a/deltaspike/pom.xml
+++ b/deltaspike/pom.xml
@@ -36,7 +36,7 @@
-->
<groupId>org.apache.deltaspike</groupId>
<artifactId>deltaspike-project</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<packaging>pom</packaging>
<name>Apache DeltaSpike</name>
@@ -49,7 +49,7 @@
<connection>scm:git:https://git-wip-us.apache.org/repos/asf/deltaspike.git</connection>
<developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/deltaspike.git</developerConnection>
<url>https://git-wip-us.apache.org/repos/asf/deltaspike.git</url>
- <tag>HEAD</tag>
+ <tag>deltaspike-project-0.5</tag>
</scm>
<modules>
diff --git a/deltaspike/test-utils/pom.xml b/deltaspike/test-utils/pom.xml
index effe3e55f..c7fb3ae50 100644
--- a/deltaspike/test-utils/pom.xml
+++ b/deltaspike/test-utils/pom.xml
@@ -23,7 +23,7 @@
<parent>
<groupId>org.apache.deltaspike</groupId>
<artifactId>parent</artifactId>
- <version>0.5-SNAPSHOT</version>
+ <version>0.5</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
|
8e36389ff951e9c3c836561d9f58dd4bc798e049
|
arrayexpress$annotare2
|
Adding change password functionality
|
p
|
https://github.com/arrayexpress/annotare2
|
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 4dc9cae16..d61d4e0ba 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
@@ -25,7 +25,6 @@
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;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors;
import uk.ac.ebi.fg.annotare2.web.server.services.EmailSender;
import uk.ac.ebi.fg.annotare2.web.server.transaction.Transactional;
@@ -34,6 +33,9 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
+import static com.google.common.base.Strings.nullToEmpty;
+import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.*;
+
/**
* @author Olga Melnichuk
*/
@@ -41,8 +43,6 @@ public class AccountServiceImpl implements AccountService {
private static final Logger log = LoggerFactory.getLogger(AccountServiceImpl.class);
- private static final SessionAttribute USER_EMAIL_ATTRIBUTE = new SessionAttribute("email");
-
private AccountManager accountManager;
private EmailSender emailer;
@@ -53,7 +53,7 @@ public AccountServiceImpl(AccountManager accountManager, EmailSender emailer) {
}
public boolean isLoggedIn(HttpServletRequest request) {
- return USER_EMAIL_ATTRIBUTE.exists(request.getSession());
+ return LOGGED_IN_SESSION_ATTRIBUTE.exists(request.getSession());
}
@Transactional
@@ -62,7 +62,7 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
ValidationErrors errors = params.validate();
if (errors.isEmpty()) {
if (null != accountManager.getByEmail(params.getEmail())) {
- errors.append("email", "User with this email already exists");
+ errors.append(FormParams.EMAIL_PARAM, "User with this email already exists");
} else {
User u = accountManager.createUser(params.getName(), params.getEmail(), params.getPassword());
try {
@@ -75,7 +75,7 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
)
);
} catch (MessagingException x) {
- //
+ log.error("There was a problem sending an email", x);
}
}
}
@@ -84,24 +84,48 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService
@Transactional
public ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException {
- SignUpParams params = new SignUpParams(request);
+ ChangePasswordParams params = new ChangePasswordParams(request);
ValidationErrors errors = params.validate();
if (errors.isEmpty()) {
- if (null != accountManager.getByEmail(params.getEmail())) {
- errors.append("email", "User with this email already exists");
+ User u = accountManager.getByEmail(params.getEmail());
+ if (null == u) {
+ errors.append(FormParams.EMAIL_PARAM, "User with this email does not exist");
+
} 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) {
- //
+ if ("".equals(nullToEmpty(params.getToken()))) {
+ u = accountManager.requestChangePassword(u.getEmail());
+ try {
+ emailer.sendFromTemplate(
+ EmailSender.CHANGE_PASSWORD_REQUEST_TEMPLATE,
+ ImmutableMap.of(
+ "to.name", u.getName(),
+ "to.email", u.getEmail(),
+ "verification.token", u.getVerificationToken()
+ )
+ );
+ } catch (MessagingException x) {
+ log.error("There was a problem sending an email", x);
+ }
+ } else {
+ if (!u.isPasswordChangeRequested()) {
+ errors.append("Change password request is invalid; please try a new one");
+ } else if (!u.getVerificationToken().equals(params.getToken())) {
+ errors.append("Incorrect code; please try again or request a new one");
+ } else {
+ accountManager.processChangePassword(u.getEmail(), params.getPassword());
+
+ }
+ try {
+ emailer.sendFromTemplate(
+ EmailSender.CHANGE_PASSWORD_CONFIRMATION_TEMPLATE,
+ ImmutableMap.of(
+ "to.name", u.getName(),
+ "to.email", u.getEmail()
+ )
+ );
+ } catch (MessagingException x) {
+ log.error("There was a problem sending an email", x);
+ }
}
}
}
@@ -118,7 +142,8 @@ public ValidationErrors login(HttpServletRequest request) throws AccountServiceE
throw new AccountServiceException("Sorry, the email or password you entered is not valid.");
}
log.debug("User '{}' logged in", params.getEmail());
- USER_EMAIL_ATTRIBUTE.set(request.getSession(), params.getEmail());
+ EMAIL_SESSION_ATTRIBUTE.set(request.getSession(), params.getEmail());
+ LOGGED_IN_SESSION_ATTRIBUTE.set(request.getSession(), true);
}
return errors;
}
@@ -128,9 +153,12 @@ public void logout(HttpSession session) {
}
public User getCurrentUser(HttpSession session) {
- String email = (String) USER_EMAIL_ATTRIBUTE.get(session);
- User user = accountManager.getByEmail(email);
- if (user == null) {
+ User user = null;
+ if (LOGGED_IN_SESSION_ATTRIBUTE.exists(session)) {
+ String email = (String) EMAIL_SESSION_ATTRIBUTE.get(session);
+ user = accountManager.getByEmail(email);
+ }
+ if (null == user) {
throw new UnauthorizedAccessException("Sorry, you are not logged in");
}
return user;
@@ -195,4 +223,46 @@ public String getPassword() {
return getParamValue(PASSWORD_PARAM);
}
}
+
+ static class ChangePasswordParams extends FormParams {
+
+ private ChangePasswordParams(HttpServletRequest request) {
+ addParam(RequestParam.from(request, EMAIL_PARAM), false);
+ addParam(RequestParam.from(request, PASSWORD_PARAM), false);
+ addParam(RequestParam.from(request, CONFIRM_PASSWORD_PARAM), false);
+ addParam(RequestParam.from(request, TOKEN_PARAM), false);
+ }
+
+ public ValidationErrors validate() {
+ ValidationErrors errors = validateMandatory();
+
+ if ("".equals(nullToEmpty(getToken()))) {
+ if (!isEmailGoodEnough()) {
+ errors.append(EMAIL_PARAM, "Email is not valid; should at least contain @ sign");
+ }
+ } else {
+ 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 getToken() {
+ return getParamValue(TOKEN_PARAM);
+ }
+
+ public String getEmail() {
+ return getParamValue(EMAIL_PARAM);
+ }
+
+ public String getPassword() {
+ 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 75d3dca75..dc19b7225 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
@@ -20,6 +20,7 @@
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import uk.ac.ebi.fg.annotare2.web.server.login.utils.FormParams;
import uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors;
import javax.servlet.ServletException;
@@ -28,6 +29,7 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
+import static com.google.common.base.Strings.nullToEmpty;
import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.CHANGE_PASSWORD;
import static com.google.common.base.Strings.isNullOrEmpty;
@@ -45,29 +47,40 @@ public class ChangePasswordServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Change password request received; processing");
ValidationErrors errors = new ValidationErrors();
-
- try {
- errors.append(accountService.changePassword(request));
- if (errors.isEmpty()) {
- 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;
+ if (null == request.getParameter(FormParams.EMAIL_PARAM)) {
+ request.setAttribute("phase", "email");
+ } else {
+ try {
+ errors.append(accountService.changePassword(request));
+ if (errors.isEmpty()) {
+ if (null == request.getParameter("token")) {
+ log.debug("Change request email has been sent; show information");
+ INFO_SESSION_ATTRIBUTE.set(request.getSession(), "Email sent to the specified address; please check your mailbox");
+ request.setAttribute("phase", "token");
+ } else if (null == request.getParameter("password")) {
+ log.debug("Token validated; enable password inputs");
+ request.setAttribute("phase", "password");
+ } else {
+ INFO_SESSION_ATTRIBUTE.set(request.getSession(), "You have successfully changed password; please sign in now");
+ LOGIN.redirect(request, response);
+ return;
+ }
+ } else {
+ request.setAttribute("phase", request.getParameter("phase"));
}
+ } catch (AccountServiceException e) {
+ log.debug("Change password request failed", e);
+ errors.append(e.getMessage());
}
- } catch (AccountServiceException e) {
- log.debug("Change password request failed", e);
- errors.append(e.getMessage());
- }
- request.setAttribute("errors", errors);
+ request.setAttribute("errors", errors);
+ }
CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response);
+ doPost(request, response);
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
index 1e69d7e72..7eaec9bff 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SessionInformation.java
@@ -21,5 +21,6 @@
public class SessionInformation {
public static final SessionAttribute EMAIL_SESSION_ATTRIBUTE = new SessionAttribute("email");
+ public static final SessionAttribute LOGGED_IN_SESSION_ATTRIBUTE = new SessionAttribute("loggedin");
public static final SessionAttribute INFO_SESSION_ATTRIBUTE = new SessionAttribute("info");
}
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
index 34c5a6263..06dffacee 100644
--- 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
@@ -22,11 +22,11 @@
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";
+ 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";
+ public static final String TOKEN_PARAM = "token";
private Map<String,RequestParam> paramMap = new HashMap<String, RequestParam>();
private Set<RequestParam> mandatoryParamSet = new HashSet<RequestParam>();
@@ -71,6 +71,6 @@ protected boolean isPasswordGoodEnough() {
}
protected boolean hasPasswordConfirmed() {
- return getParamValue(PASSWORD_PARAM).equals(getParamValue(CONFIRM_PASSWORD_PARAM));
+ return nullToEmpty(getParamValue(PASSWORD_PARAM)).equals(getParamValue(CONFIRM_PASSWORD_PARAM));
}
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
index 23cfc7117..6cab7613f 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/AccountManager.java
@@ -63,6 +63,37 @@ public User createUser(final String name, final String email, final String passw
return user;
}
+ public User activateUser(final String email) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setEmailVerified(true);
+ user.setVerificationToken(null);
+ userDao.save(user);
+ }
+ return user;
+ }
+
+ public User requestChangePassword(final String email) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setPasswordChangeRequested(true);
+ user.setVerificationToken(generateToken());
+ userDao.save(user);
+ }
+ return user;
+ }
+
+ public User processChangePassword(final String email, final String password) {
+ User user = getByEmail(email);
+ if (null != user) {
+ user.setPasswordChangeRequested(false);
+ user.setPassword(md5Hex(password));
+ user.setVerificationToken(null);
+ userDao.save(user);
+ }
+ return user;
+ }
+
private String generateToken() {
return new BigInteger(130, random).toString(36).toLowerCase();
}
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
index 036d51116..da7ed2547 100644
--- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
+++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/services/EmailSender.java
@@ -35,6 +35,8 @@ public class EmailSender
private final AnnotareProperties properties;
public static final String NEW_USER_TEMPLATE = "new-user";
+ public static final String CHANGE_PASSWORD_REQUEST_TEMPLATE = "change-password-request";
+ public static final String CHANGE_PASSWORD_CONFIRMATION_TEMPLATE = "change-password-confirmation";
public static final String INITIAL_SUBMISSION_TEMPLATE = "initial-submission";
public static final String REJECTED_SUBMISSION_TEMPLATE = "rejected-submission";
diff --git a/app/web/src/main/webapp/change-password.jsp b/app/web/src/main/webapp/change-password.jsp
index cb01a2882..916b7ac70 100644
--- a/app/web/src/main/webapp/change-password.jsp
+++ b/app/web/src/main/webapp/change-password.jsp
@@ -16,14 +16,23 @@
<%@ 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" %>
<%
- pageContext.setAttribute("errors", request.getAttribute("errors"));
+ ValidationErrors errors = (ValidationErrors) request.getAttribute("errors");
+ if (errors != null) {
+ pageContext.setAttribute("dummyErrors", errors.getErrors());
+ pageContext.setAttribute("emailErrors", errors.getErrors("email"));
+ pageContext.setAttribute("tokenErrors", errors.getErrors("token"));
+ pageContext.setAttribute("passwordErrors", errors.getErrors("password"));
+ pageContext.setAttribute("confirmPasswordErrors", errors.getErrors("confirm-password"));
+ }
String email = request.getParameter("email");
if (null == email) {
email = (String)session.getAttribute("email");
}
pageContext.setAttribute("email", email == null ? "" : email);
+ pageContext.setAttribute("phase", request.getAttribute("phase"));
%>
<!DOCTYPE html>
@@ -52,32 +61,63 @@
</tr>
<tr class="error">
<td></td>
- <td>${errors}</td>
- </tr>
- <tr class="row right">
- <td>Email</td>
- <td>
- <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>
+ <td>${dummyErrors}</td>
</tr>
+ <c:choose>
+ <c:when test="${phase == 'email'}">
+ <tr class="error">
+ <td></td>
+ <td>${emailErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Email</td>
+ <td>
+ <input type="text" name="email" value="${email}" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ </c:when>
+ <c:when test="${phase == 'token'}">
+ <tr class="error">
+ <td></td>
+ <td>${tokenErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Token</td>
+ <td>
+ <input type="hidden" name="email" value="${email}"/>
+ <input type="text" name="token" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ </c:when>
+ <c:otherwise>
+ <tr class="row right">
+ <td>Password</td>
+ <td>
+ <input type="hidden" name="email" value="${email}"/>
+ <input type="hidden" name="token" value="${token}"/>
+ <input type="password" name="password" style="width:98%" autofocus="autofocus"/>
+ </td>
+ </tr>
+ <tr class="error">
+ <td></td>
+ <td>${passwordErrors}</td>
+ </tr>
+ <tr class="row right">
+ <td>Confirm password</td>
+ <td><input type="password" name="confirm-password" style="width:98%"/></td>
+ </tr>
+ <tr class="error">
+ <td></td>
+ <td>${confirmPasswordErrors}</td>
+ </tr>
+ </c:otherwise>
+ </c:choose>
+
<tr class="row">
<td></td>
<td>
- <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>
+ <button name="changePassword">Send</button>
+ <input type="hidden" name="phase" value="${phase}"/>
</td>
</tr>
</table>
diff --git a/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java b/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
index b4fa7e101..9e227bcdd 100644
--- a/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
+++ b/app/web/src/test/java/uk/ac/ebi/fg/annotare2/web/server/login/AuthenticationServiceImplTest.java
@@ -108,7 +108,7 @@ private EmailSender mockEmailer() {
private HttpServletRequest mockRequest(String name, String password) {
HttpSession session = createMock(HttpSession.class);
session.setAttribute(isA(String.class), isA(Object.class));
- expectLastCall();
+ expectLastCall().times(2);
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request
|
0a9ff21ce61afcf58acc7173e733c8922e79e9af
|
arquillian$arquillian-graphene
|
Created AjaxSeleniumProxy for obtaining AjaxSelenium thread local context; moved unsupported Selenium API methods from TypedSelenium to UnsupportedTypedSelenium
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java b/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
index 95cc7453d..c85c58446 100644
--- a/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
+++ b/library/src/main/java/org/jboss/test/selenium/AbstractTestCase.java
@@ -34,6 +34,7 @@
import org.jboss.test.selenium.browser.BrowserType;
import org.jboss.test.selenium.encapsulated.JavaScript;
import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumImpl;
import org.jboss.test.selenium.locator.type.LocationStrategy;
import org.jboss.test.selenium.waiting.ajax.AjaxWaiting;
import org.jboss.test.selenium.waiting.conditions.AttributeEquals;
@@ -135,7 +136,7 @@ public void initializeParameters() throws MalformedURLException {
*/
@BeforeClass(dependsOnMethods = {"initializeParameters", "isTestBrowserEnabled"}, alwaysRun = true)
public void initializeBrowser() {
- selenium = new AjaxSelenium(getSeleniumHost(), getSeleniumPort(), browser, contextPath);
+ selenium = new AjaxSeleniumImpl(getSeleniumHost(), getSeleniumPort(), browser, contextPath);
selenium.start();
loadCustomLocationStrategies();
diff --git a/library/src/main/java/org/jboss/test/selenium/actions/Drag.java b/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
index a630285f7..ef2eee12b 100644
--- a/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
+++ b/library/src/main/java/org/jboss/test/selenium/actions/Drag.java
@@ -25,11 +25,11 @@
import org.apache.commons.lang.enums.EnumUtils;
import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.geometry.Point;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.selenium.SeleniumWaiting;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.waiting.Wait.waitSelenium;
/**
@@ -61,8 +61,13 @@ public class Drag {
/** The Constant FIRST_STEP. */
private static final int FIRST_STEP = 2;
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The point. */
- Point point;
+ private Point point;
// specifies phase in which is dragging state
/** The current phase. */
@@ -97,7 +102,6 @@ public Drag(ElementLocator itemToDrag, ElementLocator dropTarget) {
this.currentPhase = Phase.START;
this.itemToDrag = itemToDrag;
this.dropTarget = dropTarget;
- AjaxSelenium selenium = getCurrentSelenium();
x = selenium.getElementPositionLeft(dropTarget) - selenium.getElementPositionLeft(itemToDrag);
y = selenium.getElementPositionTop(dropTarget) - selenium.getElementPositionTop(itemToDrag);
}
@@ -180,7 +184,6 @@ private void processUntilPhase(Phase request) {
* the phase what should be executed
*/
private void executePhase(Phase phase) {
- AjaxSelenium selenium = getCurrentSelenium();
switch (phase) {
case START:
selenium.mouseDown(itemToDrag);
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
index 1b5f415cc..553223b77 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSelenium.java
@@ -21,19 +21,13 @@
*/
package org.jboss.test.selenium.framework;
-import java.net.URL;
-
-import org.jboss.test.selenium.browser.Browser;
import org.jboss.test.selenium.framework.internal.PageExtensions;
import org.jboss.test.selenium.framework.internal.SeleniumExtensions;
import org.jboss.test.selenium.interception.InterceptionProxy;
-import com.thoughtworks.selenium.CommandProcessor;
-import com.thoughtworks.selenium.HttpCommandProcessor;
-
/**
* <p>
- * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSelenium}.
+ * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSeleniumImpl}.
* </p>
*
* <p>
@@ -43,76 +37,7 @@
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class AjaxSelenium extends ExtendedTypedSelenium {
-
- /** The reference. */
- private static final ThreadLocal<AjaxSelenium> REFERENCE = new ThreadLocal<AjaxSelenium>();
-
- /** The JavaScript Extensions to tested page */
- PageExtensions pageExtensions;
-
- /** The JavaScript Extension to Selenium */
- SeleniumExtensions seleniumExtensions;
-
- /**
- * The command interception proxy
- */
- InterceptionProxy interceptionProxy;
-
- /**
- * Instantiates a new ajax selenium.
- */
- private AjaxSelenium() {
- }
-
- /**
- * Instantiates a new ajax selenium.
- *
- * @param serverHost
- * the server host
- * @param serverPort
- * the server port
- * @param browser
- * the browser
- * @param contextPathURL
- * the context path url
- */
- public AjaxSelenium(String serverHost, int serverPort, Browser browser, URL contextPathURL) {
- CommandProcessor commandProcessor =
- new HttpCommandProcessor(serverHost, serverPort, browser.getAsString(), contextPathURL.toString());
- interceptionProxy = new InterceptionProxy(commandProcessor);
- selenium = new ExtendedSelenium(interceptionProxy.getCommandProcessorProxy());
- pageExtensions = new PageExtensions(this);
- seleniumExtensions = new SeleniumExtensions(this);
- setCurrentSelenium(this);
- }
-
- /**
- * <p>
- * Sets the current context.
- * </p>
- *
- * <p>
- * <b>FIXME</b> not safe for multi-instance environment
- * </p>
- *
- * @param selenium
- * the new current context
- */
- public static void setCurrentSelenium(AjaxSelenium selenium) {
- REFERENCE.set(selenium);
- }
-
- /**
- * Gets the current context from Contextual objects.
- *
- * @param inContext
- * the in context
- * @return the current context
- */
- public static AjaxSelenium getCurrentSelenium() {
- return REFERENCE.get();
- }
+public interface AjaxSelenium extends ExtendedTypedSelenium, Cloneable {
/**
* <p>
@@ -125,9 +50,7 @@ public static AjaxSelenium getCurrentSelenium() {
*
* @return the PageExtensions associated with this AjaxSelenium object.
*/
- public PageExtensions getPageExtensions() {
- return pageExtensions;
- }
+ PageExtensions getPageExtensions();
/**
* <p>
@@ -140,30 +63,19 @@ public PageExtensions getPageExtensions() {
*
* @return the SeleniumExtensions associated with this AjaxSelenium object.
*/
- public SeleniumExtensions getSeleniumExtensions() {
- return seleniumExtensions;
- }
+ SeleniumExtensions getSeleniumExtensions();
/**
* Returns associated command interception proxy
*
* @return associated command interception proxy
*/
- public InterceptionProxy getInterceptionProxy() {
- return interceptionProxy;
- }
+ InterceptionProxy getInterceptionProxy();
/**
- * Immutable copy for copying this object.
+ * Immutable clone of this object.
*
- * @return the AjaxSelenium copy
+ * @return immutable clone of this object
*/
- public AjaxSelenium immutableCopy() {
- AjaxSelenium copy = new AjaxSelenium();
- copy.pageExtensions = new PageExtensions(copy);
- copy.seleniumExtensions = new SeleniumExtensions(copy);
- copy.interceptionProxy = this.interceptionProxy.immutableCopy();
- copy.selenium = new ExtendedSelenium(copy.interceptionProxy.getCommandProcessorProxy());
- return copy;
- }
+ AjaxSelenium clone() throws CloneNotSupportedException;
}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java
new file mode 100644
index 000000000..bf5727318
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumImpl.java
@@ -0,0 +1,157 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import java.net.URL;
+
+import org.jboss.test.selenium.browser.Browser;
+import org.jboss.test.selenium.framework.internal.PageExtensions;
+import org.jboss.test.selenium.framework.internal.SeleniumExtensions;
+import org.jboss.test.selenium.interception.InterceptionProxy;
+
+import com.thoughtworks.selenium.CommandProcessor;
+import com.thoughtworks.selenium.HttpCommandProcessor;
+
+/**
+ * <p>
+ * Implementation of {@link TypedSelenium} extended by methods in {@link ExtendedTypedSeleniumImpl}.
+ * </p>
+ *
+ * <p>
+ * Internally using {@link AjaxAwareInterceptor} and {@link InterceptionProxy}.
+ * </p>
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public class AjaxSeleniumImpl extends ExtendedTypedSeleniumImpl implements AjaxSelenium {
+
+ /** The reference. */
+ private static final ThreadLocal<AjaxSeleniumImpl> REFERENCE = new ThreadLocal<AjaxSeleniumImpl>();
+
+ /** The JavaScript Extensions to tested page */
+ PageExtensions pageExtensions;
+
+ /** The JavaScript Extension to Selenium */
+ SeleniumExtensions seleniumExtensions;
+
+ /**
+ * The command interception proxy
+ */
+ InterceptionProxy interceptionProxy;
+
+ /**
+ * Instantiates a new ajax selenium.
+ */
+ private AjaxSeleniumImpl() {
+ }
+
+ /**
+ * Instantiates a new ajax selenium.
+ *
+ * @param serverHost
+ * the server host
+ * @param serverPort
+ * the server port
+ * @param browser
+ * the browser
+ * @param contextPathURL
+ * the context path url
+ */
+ public AjaxSeleniumImpl(String serverHost, int serverPort, Browser browser, URL contextPathURL) {
+ CommandProcessor commandProcessor =
+ new HttpCommandProcessor(serverHost, serverPort, browser.getAsString(), contextPathURL.toString());
+ interceptionProxy = new InterceptionProxy(commandProcessor);
+ selenium = new ExtendedSelenium(interceptionProxy.getCommandProcessorProxy());
+ pageExtensions = new PageExtensions(this);
+ seleniumExtensions = new SeleniumExtensions(this);
+ setCurrentSelenium(this);
+ }
+
+ /**
+ * <p>
+ * Sets the current context.
+ * </p>
+ *
+ * <p>
+ * <b>FIXME</b> not safe for multi-instance environment
+ * </p>
+ *
+ * @param selenium
+ * the new current context
+ */
+ public static void setCurrentSelenium(AjaxSeleniumImpl selenium) {
+ REFERENCE.set(selenium);
+ }
+
+ /**
+ * Gets the current context from Contextual objects.
+ *
+ * @param inContext
+ * the in context
+ * @return the current context
+ */
+ static AjaxSeleniumImpl getCurrentSelenium() {
+ return REFERENCE.get();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getPageExtensions()
+ */
+ public PageExtensions getPageExtensions() {
+ return pageExtensions;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getSeleniumExtensions()
+ */
+ public SeleniumExtensions getSeleniumExtensions() {
+ return seleniumExtensions;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.test.selenium.framework.AjaxSelenium#getInterceptionProxy()
+ */
+ public InterceptionProxy getInterceptionProxy() {
+ return interceptionProxy;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see java.lang.Object#clone()
+ */
+ @Override
+ public AjaxSelenium clone() throws CloneNotSupportedException {
+ AjaxSeleniumImpl copy = new AjaxSeleniumImpl();
+ copy.pageExtensions = new PageExtensions(copy);
+ copy.seleniumExtensions = new SeleniumExtensions(copy);
+ copy.interceptionProxy = this.interceptionProxy.immutableCopy();
+ copy.selenium = new ExtendedSelenium(copy.interceptionProxy.getCommandProcessorProxy());
+ return copy;
+ }
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java
new file mode 100644
index 000000000..996c9449f
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/AjaxSeleniumProxy.java
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+/**
+ * <p>
+ * Proxy to implementation of AjaxSelenium.
+ * </p>
+ *
+ * <p>
+ * Obtains AjaxSelenium from thread local context.
+ * </p>
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public final class AjaxSeleniumProxy implements InvocationHandler {
+
+ private AjaxSeleniumProxy() {
+ }
+
+ public static AjaxSelenium getInstance() {
+ return (AjaxSelenium) Proxy.newProxyInstance(AjaxSeleniumImpl.class.getClassLoader(), AjaxSeleniumImpl.class
+ .getInterfaces(), new AjaxSeleniumProxy());
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ Object result;
+ try {
+ result = method.invoke(AjaxSeleniumImpl.getCurrentSelenium(), args);
+ } catch (InvocationTargetException e) {
+ throw e.getCause();
+ } catch (Exception e) {
+ throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
+ }
+ return result;
+ }
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
index 7b46646e2..22056356c 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSelenium.java
@@ -25,25 +25,16 @@
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.locator.IterableLocator;
-import org.jboss.test.selenium.locator.JQueryLocator;
-import org.jboss.test.selenium.locator.LocatorUtils;
/**
- * Type-safe selenium wrapper for Selenium API with extension of some useful commands defined in
- * {@link ExtendedSelenium}
+ * <p>
+ * Extends the common Selenium API by other useful functions wrapped from {@link ExtendedSelenium}.
+ * </p>
*
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class ExtendedTypedSelenium extends DefaultTypedSelenium {
-
- ExtendedSelenium getExtendedSelenium() {
- if (selenium instanceof ExtendedSelenium) {
- return (ExtendedSelenium) selenium;
- } else {
- throw new UnsupportedOperationException("Assigned Selenium isn't instance of ExtendedSelenium");
- }
- }
+public interface ExtendedTypedSelenium extends TypedSelenium {
/**
* Get current style value of element given by locator.
@@ -62,9 +53,7 @@ ExtendedSelenium getExtendedSelenium() {
* @throws IllegalStateException
* if is caught unrecognized throwable
*/
- public String getStyle(ElementLocator elementLocator, String property) {
- return getExtendedSelenium().getStyle(elementLocator.getAsString(), property);
- }
+ String getStyle(ElementLocator elementLocator, String property);
/**
* Aligns screen to top (resp. bottom) of element given by locator.
@@ -74,9 +63,7 @@ public String getStyle(ElementLocator elementLocator, String property) {
* @param alignToTop
* should be top border of screen aligned to top border of element
*/
- public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
- getExtendedSelenium().scrollIntoView(elementLocator.getAsString(), String.valueOf(alignToTop));
- }
+ void scrollIntoView(ElementLocator elementLocator, boolean alignToTop);
/**
* Simulates a user hovering a mouse over the specified element at specific coordinates relative to element.
@@ -87,9 +74,7 @@ public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
* specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the
* locator.
*/
- public void mouseOverAt(ElementLocator elementLocator, Point point) {
- getExtendedSelenium().mouseOverAt(elementLocator.getAsString(), point.getCoords());
- }
+ void mouseOverAt(ElementLocator elementLocator, Point point);
/**
* Returns whether the element is displayed on the page.
@@ -98,9 +83,7 @@ public void mouseOverAt(ElementLocator elementLocator, Point point) {
* element locator
* @return if style contains "display: none;" returns false, else returns true
*/
- public boolean isDisplayed(ElementLocator elementLocator) {
- return getExtendedSelenium().isDisplayed(elementLocator.getAsString());
- }
+ boolean isDisplayed(ElementLocator elementLocator);
/**
* Checks if element given by locator is member of CSS class given by className.
@@ -111,9 +94,7 @@ public boolean isDisplayed(ElementLocator elementLocator) {
* element's locator
* @return true if element given by locator is member of CSS class given by className
*/
- public boolean belongsClass(ElementLocator elementLocator, String className) {
- return getExtendedSelenium().belongsClass(elementLocator.getAsString(), className);
- }
+ boolean belongsClass(ElementLocator elementLocator, String className);
/**
* Verifies that the specified attribute is defined for the element.
@@ -124,11 +105,7 @@ public boolean belongsClass(ElementLocator elementLocator, String className) {
* @throws SeleniumException
* when element isn't present
*/
- public boolean isAttributePresent(AttributeLocator attributeLocator) {
- final String elementLocator = attributeLocator.getAssociatedElement().getAsString();
- final String attributeName = attributeLocator.getAttribute().getAttributeName();
- return getExtendedSelenium().isAttributePresent(elementLocator, attributeName);
- }
+ boolean isAttributePresent(AttributeLocator attributeLocator);
/*
* (non-Javadoc)
@@ -136,17 +113,5 @@ public boolean isAttributePresent(AttributeLocator attributeLocator) {
* @see
* org.jboss.test.selenium.framework.DefaultTypedSelenium#getCount(org.jboss.test.selenium.locator.IterableLocator)
*/
- @Override
- public int getCount(IterableLocator<?> locator) {
- Object reference = (Object) locator;
- if (reference instanceof JQueryLocator) {
- return getExtendedSelenium().getJQueryCount(LocatorUtils.getRawLocator((JQueryLocator) reference))
- .intValue();
- }
- try {
- return super.getCount(locator);
- } catch (UnsupportedOperationException e) {
- throw new UnsupportedOperationException("Only JQuery and XPath locators are supported for counting");
- }
- }
+ int getCount(IterableLocator<?> locator);
}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java
new file mode 100644
index 000000000..8ff07d504
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/ExtendedTypedSeleniumImpl.java
@@ -0,0 +1,125 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework;
+
+import org.jboss.test.selenium.geometry.Point;
+import org.jboss.test.selenium.locator.AttributeLocator;
+import org.jboss.test.selenium.locator.ElementLocator;
+import org.jboss.test.selenium.locator.IterableLocator;
+import org.jboss.test.selenium.locator.JQueryLocator;
+import org.jboss.test.selenium.locator.LocatorUtils;
+
+/**
+ * Type-safe selenium wrapper for Selenium API with extension of some useful commands defined in
+ * {@link ExtendedSelenium}
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public class ExtendedTypedSeleniumImpl extends TypedSeleniumImpl implements ExtendedTypedSelenium {
+
+ protected ExtendedSelenium getExtendedSelenium() {
+ if (selenium instanceof ExtendedSelenium) {
+ return (ExtendedSelenium) selenium;
+ } else {
+ throw new UnsupportedOperationException("Assigned Selenium isn't instance of ExtendedSelenium");
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.jboss.test.selenium.framework.ExtendedTypedSelenium#getStyle(org.jboss.test.selenium.locator.ElementLocator,
+ * java.lang.String)
+ */
+ public String getStyle(ElementLocator elementLocator, String property) {
+ return getExtendedSelenium().getStyle(elementLocator.getAsString(), property);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#scrollIntoView(org.jboss.test.selenium.locator.ElementLocator , boolean)
+ */
+ public void scrollIntoView(ElementLocator elementLocator, boolean alignToTop) {
+ getExtendedSelenium().scrollIntoView(elementLocator.getAsString(), String.valueOf(alignToTop));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#mouseOverAt(org.jboss.test.selenium.locator.ElementLocator ,
+ * org.jboss.test.selenium.geometry.Point)
+ */
+ public void mouseOverAt(ElementLocator elementLocator, Point point) {
+ getExtendedSelenium().mouseOverAt(elementLocator.getAsString(), point.getCoords());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#isDisplayed(org.jboss.test.selenium.locator.ElementLocator )
+ */
+ public boolean isDisplayed(ElementLocator elementLocator) {
+ return getExtendedSelenium().isDisplayed(elementLocator.getAsString());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#belongsClass(org.jboss.test.selenium.locator.ElementLocator , java.lang.String)
+ */
+ public boolean belongsClass(ElementLocator elementLocator, String className) {
+ return getExtendedSelenium().belongsClass(elementLocator.getAsString(), className);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see ExtendedTypedSelenium#isAttributePresent(org.jboss.test.selenium.locator. AttributeLocator)
+ */
+ public boolean isAttributePresent(AttributeLocator attributeLocator) {
+ final String elementLocator = attributeLocator.getAssociatedElement().getAsString();
+ final String attributeName = attributeLocator.getAttribute().getAttributeName();
+ return getExtendedSelenium().isAttributePresent(elementLocator, attributeName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see DefaultTypedSelenium#getCount(org.jboss.test.selenium.locator.IterableLocator)
+ */
+ @Override
+ public int getCount(IterableLocator<?> locator) {
+ Object reference = (Object) locator;
+ if (reference instanceof JQueryLocator) {
+ return getExtendedSelenium().getJQueryCount(LocatorUtils.getRawLocator((JQueryLocator) reference))
+ .intValue();
+ }
+ try {
+ return super.getCount(locator);
+ } catch (UnsupportedOperationException e) {
+ throw new UnsupportedOperationException("Only JQuery and XPath locators are supported for counting");
+ }
+ }
+}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
index 713052bfd..8cb712266 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/TypedSelenium.java
@@ -21,28 +21,17 @@
*/
package org.jboss.test.selenium.framework;
-import java.awt.image.BufferedImage;
-import java.io.File;
import java.net.URL;
import java.util.List;
import org.jboss.test.selenium.dom.Event;
-import org.jboss.test.selenium.encapsulated.Cookie;
-import org.jboss.test.selenium.encapsulated.CookieParameters;
-import org.jboss.test.selenium.encapsulated.Frame;
import org.jboss.test.selenium.encapsulated.FrameLocator;
import org.jboss.test.selenium.encapsulated.JavaScript;
-import org.jboss.test.selenium.encapsulated.Kwargs;
import org.jboss.test.selenium.encapsulated.LogLevel;
-import org.jboss.test.selenium.encapsulated.NetworkTraffic;
-import org.jboss.test.selenium.encapsulated.NetworkTrafficType;
-import org.jboss.test.selenium.encapsulated.Window;
-import org.jboss.test.selenium.encapsulated.WindowId;
import org.jboss.test.selenium.encapsulated.XpathLibrary;
import org.jboss.test.selenium.geometry.Dimension;
import org.jboss.test.selenium.geometry.Offset;
import org.jboss.test.selenium.geometry.Point;
-import org.jboss.test.selenium.locator.Attribute;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.locator.IdLocator;
@@ -57,9 +46,6 @@
*/
public interface TypedSelenium {
- /** Sets the per-session extension Javascript */
- void setExtensionJs(JavaScript extensionJs);
-
/** Launches the browser with a new Selenium session */
void start();
@@ -501,101 +487,6 @@ public interface TypedSelenium {
*/
void open(URL url);
- /**
- * Opens a popup window (if a window with that ID isn't already open). After opening the window, you'll need to
- * select it using the selectWindow command.
- *
- * <p>
- * This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept
- * a call to window.open (if the call occurs during or before the "onLoad" event, for example). In those cases, you
- * can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty
- * (blank) url, like this: openWindow("", "myFunnyWindow").
- * </p>
- *
- * @param url
- * the URL to open, which can be blank
- * @param windowID
- * the JavaScript window ID of the window to select
- */
- void openWindow(URL url, WindowId windowID);
-
- /**
- * Selects a popup window using a window locator; once a popup window has been selected, all commands go to that
- * window. To select the main window again, use null as the target.
- *
- * <p>
- *
- * Window locators provide different ways of specifying the window object: by title, by internal JavaScript "name,"
- * or by JavaScript variable.
- * </p>
- * <ul>
- * <li><strong>title</strong>=<em>My Special Window</em>: Finds the window using the text that appears in the title
- * bar. Be careful; two windows can share the same title. If that happens, this locator will just pick one.</li>
- * <li><strong>name</strong>=<em>myWindow</em>: Finds the window using its internal JavaScript "name" property. This
- * is the second parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures,
- * replaceFlag) (which Selenium intercepts).</li>
- * <li><strong>var</strong>=<em>variableName</em>: Some pop-up windows are unnamed (anonymous), but are associated
- * with a JavaScript variable name in the current application window, e.g. "window.foo = window.open(url);". In
- * those cases, you can open the window using "var=foo".</li>
- * </ul>
- * <p>
- * If no window locator prefix is provided, we'll try to guess what you mean like this:
- * </p>
- * <p>
- * 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window
- * instantiated by the browser).
- * </p>
- * <p>
- * 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window,
- * then it is assumed that this variable contains the return value from a call to the JavaScript window.open()
- * method.
- * </p>
- * <p>
- * 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".
- * </p>
- * <p>
- * 4.) If <em>that</em> fails, we'll try looping over all of the known windows to try to find the appropriate
- * "title". Since "title" is not necessarily unique, this may have unexpected behavior.
- * </p>
- * <p>
- * If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log
- * messages which identify the names of windows created via window.open (and therefore intercepted by Selenium). You
- * will see messages like the following for each window as it is opened:
- * </p>
- * <p>
- * <code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is
- * "myNewWindow"</code>
- * </p>
- * <p>
- * In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before
- * the "onLoad" event, for example). (This is bug SEL-339.) In those cases, you can force Selenium to notice the
- * open window's name by using the Selenium openWindow command, using an empty (blank) url, like this:
- * openWindow("", "myFunnyWindow").
- * </p>
- *
- * @param windowID
- * the JavaScript window ID of the window to select
- */
- void selectWindow(WindowId windowID);
-
- /**
- * Simplifies the process of selecting a popup window (and does not offer functionality beyond what
- * <code>selectWindow()</code> already provides).
- * <ul>
- * <li>If <code>windowID</code> is either not specified, or specified as "null", the first non-top window is
- * selected. The top window is the one that would be selected by <code>selectWindow()</code> without providing a
- * <code>windowID</code> . This should not be used when more than one popup window is in play.</li>
- * <li>Otherwise, the window will be looked up considering <code>windowID</code> as the following in order: 1) the
- * "name" of the window, as specified to <code>window.open()</code>; 2) a javascript variable which is a reference
- * to a window; and 3) the title of the window. This is the same ordered lookup performed by
- * <code>selectWindow</code> .</li>
- * </ul>
- *
- * @param windowID
- * an identifier for the popup window, which can take on a number of different meanings
- */
- void selectPopUp(WindowId windowID);
-
/**
* Selects the main window. Functionally equivalent to using <code>selectWindow()</code> and specifying no value for
* <code>windowID</code>.
@@ -621,55 +512,6 @@ public interface TypedSelenium {
*/
void selectFrame(FrameLocator frameLocator);
- /**
- * Determine whether current/locator identify the frame containing this running code.
- *
- * <p>
- * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
- * selenium server needs to identify the "current" frame. In this case, when the test calls selectFrame, this
- * routine is called for each frame to figure out which one has been selected. The selected frame will return true,
- * while all others will return false.
- * </p>
- *
- * @param currentFrameString
- * starting frame
- * @param target
- * new frame (which might be relative to the current one)
- * @return true if the new frame is this code's window
- */
- boolean getWhetherThisFrameMatchFrameExpression(Frame currentFrame, Frame targetFrame);
-
- /**
- * Determine whether currentWindowString plus target identify the window containing this running code.
- *
- * <p>
- * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
- * selenium server needs to identify the "current" window. In this case, when the test calls selectWindow, this
- * routine is called for each window to figure out which one has been selected. The selected window will return
- * true, while all others will return false.
- * </p>
- *
- * @param currentWindowString
- * starting window
- * @param target
- * new window (which might be relative to the current one, e.g., "_parent")
- * @return true if the new window is this code's window
- */
- boolean getWhetherThisWindowMatchWindowExpression(Window currentWindowString, Window target);
-
- /**
- * Waits for a popup window to appear and load up.
- *
- * @param windowID
- * the JavaScript window "name" of the window that will appear (not the text of the title bar) If
- * unspecified, or specified as "null", this command will wait for the first non-top window to appear
- * (don't rely on this if you are working with multiple popups simultaneously).
- * @param timeout
- * a timeout in milliseconds, after which the action will return with an error. If this value is not
- * specified, the default Selenium timeout will be used. See the setTimeout() command.
- */
- void waitForPopUp(WindowId windowId, long timeoutInMilis);
-
/**
* <p>
* By default, Selenium's overridden window.confirm() function will return true, as if the user had manually clicked
@@ -874,8 +716,8 @@ public interface TypedSelenium {
*
* <p>
* Note that, by default, the snippet will run in the context of the "selenium" object itself, so <code>this</code>
- * will refer to the Selenium object. Use <code>window</code> to refer to the window of your application, e.g.
- * <code>window.document.getElementById('foo')</code>
+ * will refer to the Selenium object. Use <code>window</code> to refer to the window of your application,
+ * e.g. <code>window.document.getElementById('foo')</code>
* </p>
* <p>
* If you need to use a locator to refer to a single element in your application page, you can use
@@ -1038,48 +880,6 @@ public interface TypedSelenium {
*/
boolean isEditable(ElementLocator locator);
- /**
- * Returns the IDs of all buttons on the page.
- *
- * <p>
- * If a given button has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all buttons on the page
- */
- List<ElementLocator> getAllButtons();
-
- /**
- * Returns the IDs of all links on the page.
- *
- * <p>
- * If a given link has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all links on the page
- */
- List<ElementLocator> getAllLinks();
-
- /**
- * Returns the IDs of all input fields on the page.
- *
- * <p>
- * If a given field has no ID, it will appear as "" in this array.
- * </p>
- *
- * @return the IDs of all field on the page
- */
- List<ElementLocator> getAllFields();
-
- /**
- * Returns every instance of some attribute from all known windows.
- *
- * @param attributeName
- * name of an attribute on the windows
- * @return the set of values of this attribute from all known windows.
- */
- List<String> getAttributeFromAllWindows(Attribute attribute);
-
/**
* deprecated - use dragAndDrop instead
*
@@ -1145,27 +945,6 @@ public interface TypedSelenium {
*/
void windowMaximize();
- /**
- * Returns the IDs of all windows that the browser knows about.
- *
- * @return the IDs of all windows that the browser knows about.
- */
- List<WindowId> getAllWindowIds();
-
- /**
- * Returns the names of all windows that the browser knows about.
- *
- * @return the names of all windows that the browser knows about.
- */
- List<String> getAllWindowNames();
-
- /**
- * Returns the titles of all windows that the browser knows about.
- *
- * @return the titles of all windows that the browser knows about.
- */
- List<String> getAllWindowTitles();
-
/**
* Returns the entire HTML source between the opening and closing "html" tags.
*
@@ -1278,20 +1057,6 @@ public interface TypedSelenium {
*/
int getCursorPosition(ElementLocator locator);
- /**
- * Returns the specified expression.
- *
- * <p>
- * This is useful because of JavaScript preprocessing. It is used to generate commands like assertExpression and
- * waitForExpression.
- * </p>
- *
- * @param expression
- * the value to return
- * @return the value passed in
- */
- JavaScript getExpression(JavaScript expression);
-
/**
* Returns the number of elements that match the specified locator.
*
@@ -1402,65 +1167,6 @@ public interface TypedSelenium {
*/
void waitForFrameToLoad(URL frameAddress, long timeout);
- /**
- * Return all cookies of the current page under test.
- *
- * @return all cookies of the current page under test
- */
- List<Cookie> getCookie();
-
- /**
- * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
- *
- * @param name
- * the name of the cookie
- * @return the value of the cookie
- */
- Cookie getCookieByName(Cookie name);
-
- /**
- * Returns true if a cookie with the specified name is present, or false otherwise.
- *
- * @param name
- * the name of the cookie
- * @return true if a cookie with the specified name is present, or false otherwise.
- */
- boolean isCookiePresent(Cookie name);
-
- /**
- * Create a new cookie whose path and domain are same with those of current page under test, unless you specified a
- * path for this cookie explicitly.
- *
- * @param nameValuePair
- * name and value of the cookie in a format "name=value"
- * @param optionsString
- * options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the
- * optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are
- * irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a
- * subset of the current domain will usually fail.
- */
- void createCookie(Cookie cookie, CookieParameters parameters);
-
- /**
- * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using
- * the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong,
- * the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain
- * will usually fail.
- *
- * Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option
- * called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current
- * path. Beware; this option can be slow. In big-O notation, it operates in O(n*m) time, where n is the number of
- * dots in the domain name and m is the number of slashes in the path.
- *
- * @param name
- * the name of the cookie to be deleted
- * @param optionsString
- * options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The
- * optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are
- * irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
- */
- void deleteCookie(Cookie cookie, CookieParameters parameters);
-
/**
* Calls deleteCookie with recurse=true on all cookies visible to the current page. As noted on the documentation
* for deleteCookie, recurse=true can be much slower than simply deleting the cookies using a known domain/path.
@@ -1511,30 +1217,6 @@ public interface TypedSelenium {
*/
void addLocationStrategy(LocationStrategy strategyName, JavaScript functionDefinition);
- /**
- * Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot
- * command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the
- * monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode,
- * and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from
- * the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for
- * details.
- *
- * @param filename
- * the path to the file to persist the screenshot as. No filename extension will be appended by default.
- * Directories will not be created if they do not exist, and an exception will be thrown, possibly by
- * native code.
- * @param kwargs
- * a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" .
- * Currently valid options:
- * <dl>
- * <dt>background</dt>
- * <dd>the background CSS for the HTML document. This may be useful to set for capturing screenshots of
- * less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas
- * dimension to fail and a black background is exposed (possibly obscuring black text).</dd>
- * </dl>
- */
- void captureEntirePageScreenshot(File filename, Kwargs kwargs);
-
/**
* Loads script content into a new script tag in the Selenium document. This differs from the runScript command in
* that runScript adds the script tag to the document of the AUT, not the Selenium document. The following entities
@@ -1591,84 +1273,6 @@ public interface TypedSelenium {
*/
void logToBrowser(String context);
- /**
- * Sets a file input (upload) field to the file listed in fileLocator
- *
- * @param fieldLocator
- * an element locator
- * @param fileLocator
- * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
- * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
- * form. This is common in selenium grid configurations where the RC server driving the browser is not
- * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
- */
- void attachFile(ElementLocator fieldLocator, File fileLocator);
-
- /**
- * Sets a file input (upload) field to the file listed in fileLocator
- *
- * @param fieldLocator
- * an element locator
- * @param fileLocator
- * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
- * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
- * form. This is common in selenium grid configurations where the RC server driving the browser is not
- * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
- */
- void attachFile(ElementLocator fieldLocator, URL fileLocator);
-
- /**
- * Captures a PNG screenshot to the specified file.
- *
- * @param filename
- * the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
- */
- void captureScreenshot(File filename);
-
- /**
- * Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
- *
- * @return The BufferedImage
- */
- BufferedImage captureScreenshot();
-
- /**
- * Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings.
- * When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since
- * the last call.
- *
- * @param type
- * The type of data to return the network traffic as. Valid values are: json, xml, or plain.
- * @return A string representation in the defined type of the network traffic seen by the browser.
- */
- NetworkTraffic captureNetworkTraffic(NetworkTrafficType type);
-
- /**
- * Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only
- * works if the browser is configured to use the built in Selenium proxy.
- *
- * @param key
- * the header name.
- * @param value
- * the header value.
- */
- void addCustomRequestHeader(String key, String value);
-
- /**
- * Downloads a screenshot of the browser current window canvas to a based 64 encoded PNG file. The <em>entire</em>
- * windows canvas is captured, including parts rendered outside of the current view port.
- *
- * Currently this only works in Mozilla and when running in chrome mode.
- *
- * @param kwargs
- * A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This
- * may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute
- * positioning causes the calculation of the canvas dimension to fail and a black background is exposed
- * (possibly obscuring black text).
- * @return The BufferedImage
- */
- BufferedImage captureEntirePageScreenshot(Kwargs kwargs);
-
/**
* Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be
* able to send commands to the server; you can't remotely start the server once it has been stopped. Normally you
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
similarity index 99%
rename from library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java
rename to library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
index a47ac77a5..c0ca22b72 100644
--- a/library/src/main/java/org/jboss/test/selenium/framework/DefaultTypedSelenium.java
+++ b/library/src/main/java/org/jboss/test/selenium/framework/TypedSeleniumImpl.java
@@ -41,6 +41,7 @@
import org.jboss.test.selenium.encapsulated.Window;
import org.jboss.test.selenium.encapsulated.WindowId;
import org.jboss.test.selenium.encapsulated.XpathLibrary;
+import org.jboss.test.selenium.framework.internal.UnsupportedTypedSelenium;
import org.jboss.test.selenium.geometry.Dimension;
import org.jboss.test.selenium.geometry.Offset;
import org.jboss.test.selenium.geometry.Point;
@@ -64,7 +65,7 @@
* @author <a href="mailto:[email protected]">Lukas Fryc</a>
* @version $Revision$
*/
-public class DefaultTypedSelenium implements TypedSelenium {
+public class TypedSeleniumImpl implements TypedSelenium, UnsupportedTypedSelenium {
Selenium selenium;
@@ -455,7 +456,7 @@ public boolean isOrdered(ElementLocator elementLocator1, ElementLocator elementL
}
public boolean isPromptPresent() {
- return isPromptPresent();
+ return selenium.isPromptPresent();
}
public boolean isSomethingSelected(ElementLocator selectLocator) {
diff --git a/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java b/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java
new file mode 100644
index 000000000..ef469fa23
--- /dev/null
+++ b/library/src/main/java/org/jboss/test/selenium/framework/internal/UnsupportedTypedSelenium.java
@@ -0,0 +1,433 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.selenium.framework.internal;
+
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.net.URL;
+import java.util.List;
+
+import org.jboss.test.selenium.encapsulated.Cookie;
+import org.jboss.test.selenium.encapsulated.CookieParameters;
+import org.jboss.test.selenium.encapsulated.Frame;
+import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.encapsulated.Kwargs;
+import org.jboss.test.selenium.encapsulated.NetworkTraffic;
+import org.jboss.test.selenium.encapsulated.NetworkTrafficType;
+import org.jboss.test.selenium.encapsulated.Window;
+import org.jboss.test.selenium.encapsulated.WindowId;
+import org.jboss.test.selenium.locator.Attribute;
+import org.jboss.test.selenium.locator.ElementLocator;
+
+/**
+ * Unsupported methods from Selenium API didn't exposed to TypedSelenium
+ *
+ * @author <a href="mailto:[email protected]">Lukas Fryc</a>
+ * @version $Revision$
+ */
+public interface UnsupportedTypedSelenium {
+ /**
+ * Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only
+ * works if the browser is configured to use the built in Selenium proxy.
+ *
+ * @param key
+ * the header name.
+ * @param value
+ * the header value.
+ */
+ void addCustomRequestHeader(String key, String value);
+
+ /**
+ * Sets a file input (upload) field to the file listed in fileLocator
+ *
+ * @param fieldLocator
+ * an element locator
+ * @param fileLocator
+ * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
+ * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
+ * form. This is common in selenium grid configurations where the RC server driving the browser is not
+ * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
+ */
+ void attachFile(ElementLocator fieldLocator, File fileLocator);
+
+ /**
+ * Sets a file input (upload) field to the file listed in fileLocator
+ *
+ * @param fieldLocator
+ * an element locator
+ * @param fileLocator
+ * a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator),
+ * Selenium RC may need to transfer the file to the local machine before attaching the file in a web page
+ * form. This is common in selenium grid configurations where the RC server driving the browser is not
+ * the same machine that started the test. Supported Browsers: Firefox ("*chrome") only.
+ */
+ @Deprecated
+ void attachFile(ElementLocator fieldLocator, URL fileLocator);
+
+ /**
+ * Captures a PNG screenshot to the specified file.
+ *
+ * @param filename
+ * the absolute path to the file to be written, e.g. "c:\blah\screenshot.png"
+ */
+ void captureScreenshot(File filename);
+
+ /**
+ * Capture a PNG screenshot. It then returns the file as a base 64 encoded string.
+ *
+ * @return The BufferedImage
+ */
+ BufferedImage captureScreenshot();
+
+ /**
+ * Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings.
+ * When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since
+ * the last call.
+ *
+ * @param type
+ * The type of data to return the network traffic as. Valid values are: json, xml, or plain.
+ * @return A string representation in the defined type of the network traffic seen by the browser.
+ */
+ NetworkTraffic captureNetworkTraffic(NetworkTrafficType type);
+
+ /**
+ * Downloads a screenshot of the browser current window canvas to a based 64 encoded PNG file. The <em>entire</em>
+ * windows canvas is captured, including parts rendered outside of the current view port.
+ *
+ * Currently this only works in Mozilla and when running in chrome mode.
+ *
+ * @param kwargs
+ * A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This
+ * may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute
+ * positioning causes the calculation of the canvas dimension to fail and a black background is exposed
+ * (possibly obscuring black text).
+ * @return The BufferedImage
+ */
+ BufferedImage captureEntirePageScreenshot(Kwargs kwargs);
+
+ /**
+ * Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot
+ * command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the
+ * monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode,
+ * and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from
+ * the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for
+ * details.
+ *
+ * @param filename
+ * the path to the file to persist the screenshot as. No filename extension will be appended by default.
+ * Directories will not be created if they do not exist, and an exception will be thrown, possibly by
+ * native code.
+ * @param kwargs
+ * a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" .
+ * Currently valid options:
+ * <dl>
+ * <dt>background</dt>
+ * <dd>the background CSS for the HTML document. This may be useful to set for capturing screenshots of
+ * less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas
+ * dimension to fail and a black background is exposed (possibly obscuring black text).</dd>
+ * </dl>
+ */
+ void captureEntirePageScreenshot(File filename, Kwargs kwargs);
+
+ /**
+ * Return all cookies of the current page under test.
+ *
+ * @return all cookies of the current page under test
+ */
+ List<Cookie> getCookie();
+
+ /**
+ * Returns the value of the cookie with the specified name, or throws an error if the cookie is not present.
+ *
+ * @param name
+ * the name of the cookie
+ * @return the value of the cookie
+ */
+ Cookie getCookieByName(Cookie name);
+
+ /**
+ * Returns true if a cookie with the specified name is present, or false otherwise.
+ *
+ * @param name
+ * the name of the cookie
+ * @return true if a cookie with the specified name is present, or false otherwise.
+ */
+ boolean isCookiePresent(Cookie name);
+
+ /**
+ * Create a new cookie whose path and domain are same with those of current page under test, unless you specified a
+ * path for this cookie explicitly.
+ *
+ * @param nameValuePair
+ * name and value of the cookie in a format "name=value"
+ * @param optionsString
+ * options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the
+ * optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are
+ * irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a
+ * subset of the current domain will usually fail.
+ */
+ void createCookie(Cookie cookie, CookieParameters parameters);
+
+ /**
+ * Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using
+ * the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong,
+ * the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain
+ * will usually fail.
+ *
+ * Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option
+ * called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current
+ * path. Beware; this option can be slow. In big-O notation, it operates in O(n*m) time, where n is the number of
+ * dots in the domain name and m is the number of slashes in the path.
+ *
+ * @param name
+ * the name of the cookie to be deleted
+ * @param optionsString
+ * options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The
+ * optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are
+ * irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail.
+ */
+ void deleteCookie(Cookie cookie, CookieParameters parameters);
+
+ /**
+ * Returns the IDs of all buttons on the page.
+ *
+ * <p>
+ * If a given button has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all buttons on the page
+ */
+ List<ElementLocator> getAllButtons();
+
+ /**
+ * Returns the IDs of all links on the page.
+ *
+ * <p>
+ * If a given link has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all links on the page
+ */
+ List<ElementLocator> getAllLinks();
+
+ /**
+ * Returns the IDs of all input fields on the page.
+ *
+ * <p>
+ * If a given field has no ID, it will appear as "" in this array.
+ * </p>
+ *
+ * @return the IDs of all field on the page
+ */
+ List<ElementLocator> getAllFields();
+
+ /**
+ * Returns the IDs of all windows that the browser knows about.
+ *
+ * @return the IDs of all windows that the browser knows about.
+ */
+ List<WindowId> getAllWindowIds();
+
+ /**
+ * Returns the names of all windows that the browser knows about.
+ *
+ * @return the names of all windows that the browser knows about.
+ */
+ List<String> getAllWindowNames();
+
+ /**
+ * Returns the titles of all windows that the browser knows about.
+ *
+ * @return the titles of all windows that the browser knows about.
+ */
+ List<String> getAllWindowTitles();
+
+ /**
+ * Returns every instance of some attribute from all known windows.
+ *
+ * @param attributeName
+ * name of an attribute on the windows
+ * @return the set of values of this attribute from all known windows.
+ */
+ List<String> getAttributeFromAllWindows(Attribute attribute);
+
+ /**
+ * Returns the specified expression.
+ *
+ * <p>
+ * This is useful because of JavaScript preprocessing. It is used to generate commands like assertExpression and
+ * waitForExpression.
+ * </p>
+ *
+ * @param expression
+ * the value to return
+ * @return the value passed in
+ */
+ JavaScript getExpression(JavaScript expression);
+
+ /**
+ * Determine whether current/locator identify the frame containing this running code.
+ *
+ * <p>
+ * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
+ * selenium server needs to identify the "current" frame. In this case, when the test calls selectFrame, this
+ * routine is called for each frame to figure out which one has been selected. The selected frame will return true,
+ * while all others will return false.
+ * </p>
+ *
+ * @param currentFrameString
+ * starting frame
+ * @param target
+ * new frame (which might be relative to the current one)
+ * @return true if the new frame is this code's window
+ */
+ boolean getWhetherThisFrameMatchFrameExpression(Frame currentFrame, Frame targetFrame);
+
+ /**
+ * Determine whether currentWindowString plus target identify the window containing this running code.
+ *
+ * <p>
+ * This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the
+ * selenium server needs to identify the "current" window. In this case, when the test calls selectWindow, this
+ * routine is called for each window to figure out which one has been selected. The selected window will return
+ * true, while all others will return false.
+ * </p>
+ *
+ * @param currentWindowString
+ * starting window
+ * @param target
+ * new window (which might be relative to the current one, e.g., "_parent")
+ * @return true if the new window is this code's window
+ */
+ boolean getWhetherThisWindowMatchWindowExpression(Window currentWindowString, Window target);
+
+ /**
+ * Opens a popup window (if a window with that ID isn't already open). After opening the window, you'll need to
+ * select it using the selectWindow command.
+ *
+ * <p>
+ * This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept
+ * a call to window.open (if the call occurs during or before the "onLoad" event, for example). In those cases, you
+ * can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty
+ * (blank) url, like this: openWindow("", "myFunnyWindow").
+ * </p>
+ *
+ * @param url
+ * the URL to open, which can be blank
+ * @param windowID
+ * the JavaScript window ID of the window to select
+ */
+ void openWindow(URL url, WindowId windowID);
+
+ /**
+ * Simplifies the process of selecting a popup window (and does not offer functionality beyond what
+ * <code>selectWindow()</code> already provides).
+ * <ul>
+ * <li>If <code>windowID</code> is either not specified, or specified as "null", the first non-top window is
+ * selected. The top window is the one that would be selected by <code>selectWindow()</code> without providing a
+ * <code>windowID</code> . This should not be used when more than one popup window is in play.</li>
+ * <li>Otherwise, the window will be looked up considering <code>windowID</code> as the following in order: 1) the
+ * "name" of the window, as specified to <code>window.open()</code>; 2) a javascript variable which is a reference
+ * to a window; and 3) the title of the window. This is the same ordered lookup performed by
+ * <code>selectWindow</code> .</li>
+ * </ul>
+ *
+ * @param windowID
+ * an identifier for the popup window, which can take on a number of different meanings
+ */
+ void selectPopUp(WindowId windowID);
+
+ /**
+ * Selects a popup window using a window locator; once a popup window has been selected, all commands go to that
+ * window. To select the main window again, use null as the target.
+ *
+ * <p>
+ *
+ * Window locators provide different ways of specifying the window object: by title, by internal JavaScript "name,"
+ * or by JavaScript variable.
+ * </p>
+ * <ul>
+ * <li><strong>title</strong>=<em>My Special Window</em>: Finds the window using the text that appears in the title
+ * bar. Be careful; two windows can share the same title. If that happens, this locator will just pick one.</li>
+ * <li><strong>name</strong>=<em>myWindow</em>: Finds the window using its internal JavaScript "name" property. This
+ * is the second parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures,
+ * replaceFlag) (which Selenium intercepts).</li>
+ * <li><strong>var</strong>=<em>variableName</em>: Some pop-up windows are unnamed (anonymous), but are associated
+ * with a JavaScript variable name in the current application window, e.g. "window.foo = window.open(url);". In
+ * those cases, you can open the window using "var=foo".</li>
+ * </ul>
+ * <p>
+ * If no window locator prefix is provided, we'll try to guess what you mean like this:
+ * </p>
+ * <p>
+ * 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window
+ * instantiated by the browser).
+ * </p>
+ * <p>
+ * 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window,
+ * then it is assumed that this variable contains the return value from a call to the JavaScript window.open()
+ * method.
+ * </p>
+ * <p>
+ * 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names".
+ * </p>
+ * <p>
+ * 4.) If <em>that</em> fails, we'll try looping over all of the known windows to try to find the appropriate
+ * "title". Since "title" is not necessarily unique, this may have unexpected behavior.
+ * </p>
+ * <p>
+ * If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log
+ * messages which identify the names of windows created via window.open (and therefore intercepted by Selenium). You
+ * will see messages like the following for each window as it is opened:
+ * </p>
+ * <p>
+ * <code>debug: window.open call intercepted; window ID (which you can use with selectWindow()) is
+ * "myNewWindow"</code>
+ * </p>
+ * <p>
+ * In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before
+ * the "onLoad" event, for example). (This is bug SEL-339.) In those cases, you can force Selenium to notice the
+ * open window's name by using the Selenium openWindow command, using an empty (blank) url, like this:
+ * openWindow("", "myFunnyWindow").
+ * </p>
+ *
+ * @param windowID
+ * the JavaScript window ID of the window to select
+ */
+ void selectWindow(WindowId windowID);
+
+ /** Sets the per-session extension Javascript */
+ void setExtensionJs(JavaScript extensionJs);
+
+ /**
+ * Waits for a popup window to appear and load up.
+ *
+ * @param windowID
+ * the JavaScript window "name" of the window that will appear (not the text of the title bar) If
+ * unspecified, or specified as "null", this command will wait for the first non-top window to appear
+ * (don't rely on this if you are working with multiple popups simultaneously).
+ * @param timeout
+ * a timeout in milliseconds, after which the action will return with an error. If this value is not
+ * specified, the default Selenium timeout will be used. See the setTimeout() command.
+ */
+ void waitForPopUp(WindowId windowId, long timeoutInMilis);
+}
diff --git a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
index 7d5ab7e92..b693f6d85 100644
--- a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
+++ b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuard.java
@@ -22,6 +22,8 @@
package org.jboss.test.selenium.guard.request;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.interception.CommandContext;
import org.jboss.test.selenium.interception.CommandInterceptionException;
import org.jboss.test.selenium.interception.CommandInterceptor;
@@ -30,7 +32,6 @@
import com.thoughtworks.selenium.SeleniumException;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.guard.GuardedCommands.INTERACTIVE_COMMANDS;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
@@ -47,7 +48,12 @@ public class RequestTypeGuard implements CommandInterceptor {
private final JavaScript waitRequestChange =
js("((getRFS() === undefined) ? 'HTTP' : getRFS().getRequestDone()) != 'NONE' && "
+ "selenium.browserbot.getCurrentWindow().document.body");
-
+
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/**
* The request what is expected to be done
*/
@@ -84,8 +90,8 @@ public void intercept(CommandContext ctx) throws CommandInterceptionException {
* request type to NONE state.
*/
public void doBeforeCommand() {
- getCurrentSelenium().getPageExtensions().install();
- getCurrentSelenium().getEval(clearRequestDone);
+ selenium.getPageExtensions().install();
+ selenium.getEval(clearRequestDone);
}
/**
@@ -103,7 +109,7 @@ public void doBeforeCommand() {
public void doAfterCommand() {
try {
// FIXME replace with Wait implementation
- getCurrentSelenium().waitForCondition(waitRequestChange, Wait.DEFAULT_TIMEOUT);
+ selenium.waitForCondition(waitRequestChange, Wait.DEFAULT_TIMEOUT);
} catch (SeleniumException e) {
// ignore the timeout exception
}
@@ -122,7 +128,7 @@ public void doAfterCommand() {
* when the unknown type was obtained
*/
private RequestType getRequestDone() {
- String requestDone = getCurrentSelenium().getEval(getRequestDone);
+ String requestDone = selenium.getEval(getRequestDone);
try {
return RequestType.valueOf(requestDone);
} catch (IllegalArgumentException e) {
diff --git a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
index dc571684d..3da734f95 100644
--- a/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
+++ b/library/src/main/java/org/jboss/test/selenium/guard/request/RequestTypeGuardFactory.java
@@ -35,7 +35,12 @@ private RequestTypeGuardFactory() {
}
private static AjaxSelenium guard(AjaxSelenium selenium, RequestType requestExpected) {
- AjaxSelenium copy = selenium.immutableCopy();
+ AjaxSelenium copy;
+ try {
+ copy = selenium.clone();
+ } catch (CloneNotSupportedException e) {
+ throw new IllegalStateException(e);
+ }
copy.getInterceptionProxy().unregisterInterceptorType(RequestTypeGuard.class);
copy.getInterceptionProxy().registerInterceptor(new RequestTypeGuard(requestExpected));
return copy;
diff --git a/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java b/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
index 4e9ea5c03..511f3526b 100644
--- a/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
+++ b/library/src/main/java/org/jboss/test/selenium/listener/SeleniumLoggingTestListener.java
@@ -23,12 +23,13 @@
import static org.jboss.test.selenium.utils.testng.TestInfo.STATUSES;
import static org.jboss.test.selenium.utils.testng.TestInfo.getMethodName;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
import org.apache.commons.lang.StringUtils;
import org.jboss.test.selenium.encapsulated.FrameLocator;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
@@ -44,6 +45,11 @@
*/
public class SeleniumLoggingTestListener extends TestListenerAdapter {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
@Override
public void onTestStart(ITestResult result) {
logStatus(result);
@@ -84,11 +90,11 @@ private void logStatus(ITestResult result) {
String message = String.format("%s %s: %s %s", hashes, status.toUpperCase(), methodName, hashes);
String line = StringUtils.repeat("#", message.length());
- if (getCurrentSelenium() != null) {
+ if (selenium != null) {
JavaScript eval = js(String.format("/*\n%s\n%s\n%s\n*/", line, message, line));
try {
- getCurrentSelenium().selectFrame(new FrameLocator("relative=top"));
- getCurrentSelenium().getEval(eval);
+ selenium.selectFrame(new FrameLocator("relative=top"));
+ selenium.getEval(eval);
} catch (Exception e) {
e.printStackTrace();
}
diff --git a/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java b/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
index 8cb8a6dcb..3d4483fb7 100644
--- a/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
+++ b/library/src/main/java/org/jboss/test/selenium/locator/iteration/AbstractElementList.java
@@ -21,10 +21,11 @@
*/
package org.jboss.test.selenium.locator.iteration;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import java.util.Iterator;
import java.util.NoSuchElementException;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.IterableLocator;
/**
@@ -45,6 +46,11 @@
*/
public abstract class AbstractElementList<T extends IterableLocator<T>> implements Iterable<T> {
+ /**
+ * Proxy to local selenium instance
+ */
+ protected AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The iterable locator. */
T iterableLocator;
@@ -97,7 +103,7 @@ public ElementIterator() {
* Recounts the actual count of elements by given elementLocator.
*/
private void recount() {
- count = getCurrentSelenium().getCount(iterableLocator);
+ count = selenium.getCount(iterableLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java b/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
index e82ade5d0..e997cafa9 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/ajax/AjaxWaiting.java
@@ -1,10 +1,11 @@
package org.jboss.test.selenium.waiting.ajax;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.waiting.DefaultWaiting;
/**
@@ -22,6 +23,11 @@
*/
public class AjaxWaiting extends DefaultWaiting<AjaxWaiting> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/**
* Stars loop waiting to satisfy condition.
*
@@ -29,7 +35,7 @@ public class AjaxWaiting extends DefaultWaiting<AjaxWaiting> {
* what wait for to be satisfied
*/
public void until(JavaScriptCondition condition) {
- getCurrentSelenium().waitForCondition(condition.getJavaScriptCondition(), this.getTimeout());
+ selenium.waitForCondition(condition.getJavaScriptCondition(), this.getTimeout());
}
/**
@@ -44,7 +50,7 @@ public void until(JavaScriptCondition condition) {
*/
public <T> void waitForChange(T oldValue, JavaScriptRetriever<T> retrieve) {
JavaScript waitCondition = js(format("{0} != '{1}'", retrieve.getJavaScriptRetrieve().getAsString(), oldValue));
- getCurrentSelenium().waitForCondition(waitCondition, this.getTimeout());
+ selenium.waitForCondition(waitCondition, this.getTimeout());
}
/**
@@ -63,7 +69,7 @@ public <T> T waitForChangeAndReturn(T oldValue, JavaScriptRetriever<T> retrieve)
JavaScript waitingRetriever =
js(format("selenium.waitForCondition({0} != '{1}'); {0}", retrieve.getJavaScriptRetrieve().getAsString(),
oldValueString));
- String retrieved = getCurrentSelenium().getEval(waitingRetriever);
+ String retrieved = selenium.getEval(waitingRetriever);
return retrieve.getConvertor().backwardConversion(retrieved);
}
}
\ No newline at end of file
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
index 883f8c537..054f13934 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributeEquals.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -48,11 +49,16 @@
*/
public class AttributeEquals implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/** The value. */
- String value;
+ private String value;
/**
* Instantiates a new AttributeEquals
@@ -69,7 +75,7 @@ public boolean isTrue() {
Validate.notNull(attributeLocator);
Validate.notNull(value);
- return getCurrentSelenium().getAttribute(attributeLocator).equals(value);
+ return selenium.getAttribute(attributeLocator).equals(value);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
index fa1eb4485..18dd4d792 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/AttributePresent.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -46,8 +47,13 @@
*/
public class AttributePresent implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/**
* Instantiates a new element present.
@@ -63,7 +69,7 @@ protected AttributePresent() {
public boolean isTrue() {
Validate.notNull(attributeLocator);
- return getCurrentSelenium().isAttributePresent(attributeLocator);
+ return selenium.isAttributePresent(attributeLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
index 636899f91..2a6a631e0 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/ElementPresent.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -46,8 +47,13 @@
*/
public class ElementPresent implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/**
* Instantiates a new element present.
@@ -63,7 +69,7 @@ protected ElementPresent() {
public boolean isTrue() {
Validate.notNull(elementLocator);
- return getCurrentSelenium().isElementPresent(elementLocator);
+ return selenium.isElementPresent(elementLocator);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
index aa227bb10..c5745cb06 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/conditions/TextEquals.java
@@ -23,13 +23,14 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptCondition;
import org.jboss.test.selenium.waiting.selenium.SeleniumCondition;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
import static org.apache.commons.lang.StringEscapeUtils.escapeJavaScript;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -47,11 +48,16 @@
*/
public class TextEquals implements SeleniumCondition, JavaScriptCondition {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/** The text. */
- String text;
+ private String text;
/**
* Instantiates a new text equals.
@@ -68,7 +74,7 @@ public boolean isTrue() {
Validate.notNull(elementLocator);
Validate.notNull(text);
- return getCurrentSelenium().getText(elementLocator).equals(text);
+ return selenium.getText(elementLocator).equals(text);
}
/*
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
index 57267175c..d2cc9e5e9 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/AttributeRetriever.java
@@ -23,6 +23,8 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.AttributeLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptRetriever;
import org.jboss.test.selenium.waiting.conversion.Convertor;
@@ -30,7 +32,6 @@
import org.jboss.test.selenium.waiting.selenium.SeleniumRetriever;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -41,8 +42,13 @@
*/
public class AttributeRetriever implements SeleniumRetriever<String>, JavaScriptRetriever<String> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The attribute locator. */
- AttributeLocator attributeLocator;
+ private AttributeLocator attributeLocator;
/**
* Instantiates a new attribute retriever.
@@ -56,7 +62,7 @@ protected AttributeRetriever() {
public String retrieve() {
Validate.notNull(attributeLocator);
- return getCurrentSelenium().getAttribute(attributeLocator);
+ return selenium.getAttribute(attributeLocator);
}
/**
diff --git a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
index 523649b9e..402eff955 100644
--- a/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
+++ b/library/src/main/java/org/jboss/test/selenium/waiting/retrievers/TextRetriever.java
@@ -23,6 +23,8 @@
import org.apache.commons.lang.Validate;
import org.jboss.test.selenium.encapsulated.JavaScript;
+import org.jboss.test.selenium.framework.AjaxSelenium;
+import org.jboss.test.selenium.framework.AjaxSeleniumProxy;
import org.jboss.test.selenium.locator.ElementLocator;
import org.jboss.test.selenium.waiting.ajax.JavaScriptRetriever;
import org.jboss.test.selenium.waiting.conversion.Convertor;
@@ -30,7 +32,6 @@
import org.jboss.test.selenium.waiting.selenium.SeleniumRetriever;
import static org.jboss.test.selenium.utils.text.SimplifiedFormat.format;
-import static org.jboss.test.selenium.framework.AjaxSelenium.getCurrentSelenium;
import static org.jboss.test.selenium.encapsulated.JavaScript.js;
/**
@@ -41,8 +42,13 @@
*/
public class TextRetriever implements SeleniumRetriever<String>, JavaScriptRetriever<String> {
+ /**
+ * Proxy to local selenium instance
+ */
+ private AjaxSelenium selenium = AjaxSeleniumProxy.getInstance();
+
/** The element locator. */
- ElementLocator elementLocator;
+ private ElementLocator elementLocator;
/**
* Instantiates a new text retriever.
@@ -56,7 +62,7 @@ protected TextRetriever() {
public String retrieve() {
Validate.notNull(elementLocator);
- return getCurrentSelenium().getText(elementLocator);
+ return selenium.getText(elementLocator);
}
/**
|
8d5e90063e4adc55091d0c20cd41adc536cf438d
|
Vala
|
gio-2.0: return value of g_inet_address_to_bytes is an array
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi
index a201544104..576d5d047c 100644
--- a/vapi/gio-2.0.vapi
+++ b/vapi/gio-2.0.vapi
@@ -439,7 +439,8 @@ namespace GLib {
public size_t get_native_size ();
[CCode (has_construct_function = false)]
public InetAddress.loopback (GLib.SocketFamily family);
- public virtual uchar to_bytes ();
+ [CCode (array_length = false)]
+ public virtual unowned uint8[] to_bytes ();
public virtual string to_string ();
[NoAccessorMethod]
public void* bytes { get; construct; }
diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata
index 31b122134d..9ed848399b 100644
--- a/vapi/packages/gio-2.0/gio-2.0.metadata
+++ b/vapi/packages/gio-2.0/gio-2.0.metadata
@@ -92,6 +92,7 @@ g_file_stop_mountable async="1"
g_file_unmount_mountable async="1"
g_file_unmount_mountable_with_operation async="1"
g_inet_address_to_string transfer_ownership="1"
+g_inet_address_to_bytes type_name="uint8" is_array="1" no_array_length="1"
g_input_stream_read_all.bytes_read is_out="1"
GIOErrorEnum rename_to="IOError" errordomain="1"
g_io_extension_point_get_extensions type_arguments="IOExtension"
|
930022aaacd24376b0f17168d5b8c36ca401e626
|
kotlin
|
J2K: correct conversion of nested class- references-- -KT-5294 Fixed- -KT-5400 Fixed-
|
c
|
https://github.com/JetBrains/kotlin
|
diff --git a/j2k/src/org/jetbrains/jet/j2k/ConstructorConverter.kt b/j2k/src/org/jetbrains/jet/j2k/ConstructorConverter.kt
index 1aabd44ea4512..bd23239ff6278 100644
--- a/j2k/src/org/jetbrains/jet/j2k/ConstructorConverter.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/ConstructorConverter.kt
@@ -183,8 +183,7 @@ class ConstructorConverter(private val psiClass: PsiClass, private val converter
var body = postProcessBody(bodyConverter.convertBlock(constructor.getBody()))
val containingClass = constructor.getContainingClass()
val typeParameterList = converter.convertTypeParameterList(containingClass?.getTypeParameterList())
- val factoryFunctionType = ClassType(containingClass?.declarationIdentifier() ?: Identifier.Empty,
- typeParameterList.parameters,
+ val factoryFunctionType = ClassType(ReferenceElement(containingClass?.declarationIdentifier() ?: Identifier.Empty, typeParameterList.parameters).assignNoPrototype(),
Nullability.NotNull,
converter.settings).assignNoPrototype()
return FactoryFunction(constructor.declarationIdentifier(), annotations, correctFactoryFunctionAccess(modifiers),
@@ -201,13 +200,14 @@ class ConstructorConverter(private val psiClass: PsiClass, private val converter
val body = primaryConstructor.getBody()
val parameterUsageReplacementMap = HashMap<String, String>()
+ val correctedTypeConverter = converter.withSpecialContext(psiClass).typeConverter /* to correct nested class references */
val block = if (body != null) {
val statementsToRemove = HashSet<PsiStatement>()
for (parameter in params) {
val (field, initializationStatement) = findBackingFieldForConstructorParameter(parameter, primaryConstructor) ?: continue
- val fieldType = typeConverter.convertVariableType(field)
- val parameterType = typeConverter.convertVariableType(parameter)
+ val fieldType = correctedTypeConverter.convertVariableType(field)
+ val parameterType = correctedTypeConverter.convertVariableType(parameter)
// types can be different only in nullability
val `type` = if (fieldType == parameterType) {
fieldType
@@ -244,6 +244,7 @@ class ConstructorConverter(private val psiClass: PsiClass, private val converter
// we need to replace renamed parameter usages in base class constructor arguments and in default values
val correctedConverter = converter.withExpressionVisitor { ReplacingExpressionVisitor(this, parameterUsageReplacementMap, it) }
+ .withSpecialContext(psiClass) /* to correct nested class references */
val statement = primaryConstructor.getBody()?.getStatements()?.firstOrNull()
val methodCall = (statement as? PsiExpressionStatement)?.getExpression() as? PsiMethodCallExpression
@@ -259,7 +260,7 @@ class ConstructorConverter(private val psiClass: PsiClass, private val converter
else
null
if (!parameterToField.containsKey(parameter)) {
- converter.convertParameter(parameter, defaultValue = defaultValue)
+ correctedConverter.convertParameter(parameter, defaultValue = defaultValue)
}
else {
val (field, `type`) = parameterToField[parameter]!!
diff --git a/j2k/src/org/jetbrains/jet/j2k/Converter.kt b/j2k/src/org/jetbrains/jet/j2k/Converter.kt
index 62cfeb92ddeb8..fdab1aa2afed9 100644
--- a/j2k/src/org/jetbrains/jet/j2k/Converter.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/Converter.kt
@@ -24,6 +24,7 @@ import com.intellij.psi.CommonClassNames.*
import org.jetbrains.jet.lang.types.expressions.OperatorConventions.*
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiMethodUtil
+import com.intellij.psi.util.PsiTreeUtil
public trait ConversionScope {
public fun contains(element: PsiElement): Boolean
@@ -34,29 +35,53 @@ public class FilesConversionScope(val files: Collection<PsiJavaFile>) : Conversi
}
public class Converter private(val project: Project, val settings: ConverterSettings, val conversionScope: ConversionScope, val state: Converter.State) {
- private class State(val typeConverter: TypeConverter,
- val methodReturnType: PsiType?,
+ private class State(val methodReturnType: PsiType?,
val expressionVisitorFactory: (Converter) -> ExpressionVisitor,
- val statementVisitorFactory: (Converter) -> StatementVisitor)
- val typeConverter: TypeConverter = state.typeConverter
+ val statementVisitorFactory: (Converter) -> StatementVisitor,
+ val specialContext: PsiElement?,
+ val importList: ImportList?,
+ val importsToAdd: MutableCollection<String>?)
+
+ val typeConverter: TypeConverter = TypeConverter(this)
+
val methodReturnType: PsiType? = state.methodReturnType
+ val specialContext: PsiElement? = state.specialContext
+ val importNames: Set<String> = state.importList?.imports?.mapTo(HashSet<String>()) { it.name } ?: setOf()
+ val importsToAdd: MutableCollection<String>? = state.importsToAdd
private val expressionVisitor = state.expressionVisitorFactory(this)
private val statementVisitor = state.statementVisitorFactory(this)
class object {
- public fun create(project: Project, settings: ConverterSettings, conversionScope: ConversionScope): Converter
- = Converter(project, settings, conversionScope, State(TypeConverter(settings, conversionScope), null, { ExpressionVisitor(it) }, { StatementVisitor(it) }))
+ public fun create(project: Project, settings: ConverterSettings, conversionScope: ConversionScope): Converter {
+ val state = State(null, { ExpressionVisitor(it) }, { StatementVisitor(it) }, null, null, null)
+ return Converter(project, settings, conversionScope, state)
+ }
}
fun withMethodReturnType(methodReturnType: PsiType?): Converter
- = Converter(project, settings, conversionScope, State(typeConverter, methodReturnType, state.expressionVisitorFactory, state.statementVisitorFactory))
+ = Converter(project, settings, conversionScope,
+ State(methodReturnType, state.expressionVisitorFactory, state.statementVisitorFactory, state.specialContext, state.importList, state.importsToAdd))
fun withExpressionVisitor(factory: (Converter) -> ExpressionVisitor): Converter
- = Converter(project, settings, conversionScope, State(typeConverter, state.methodReturnType, factory, state.statementVisitorFactory))
+ = Converter(project, settings, conversionScope,
+ State(state.methodReturnType, factory, state.statementVisitorFactory, state.specialContext, state.importList, state.importsToAdd))
fun withStatementVisitor(factory: (Converter) -> StatementVisitor): Converter
- = Converter(project, settings, conversionScope, State(typeConverter, state.methodReturnType, state.expressionVisitorFactory, factory))
+ = Converter(project, settings, conversionScope,
+ State(state.methodReturnType, state.expressionVisitorFactory, factory, state.specialContext, state.importList, state.importsToAdd))
+
+ fun withSpecialContext(context: PsiElement): Converter
+ = Converter(project, settings, conversionScope,
+ State(state.methodReturnType, state.expressionVisitorFactory, state.statementVisitorFactory, context, state.importList, state.importsToAdd))
+
+ private fun withImportList(importList: ImportList): Converter
+ = Converter(project, settings, conversionScope,
+ State(state.methodReturnType, state.expressionVisitorFactory, state.statementVisitorFactory, state.specialContext, importList, state.importsToAdd))
+
+ private fun withImportsToAdd(importsToAdd: MutableCollection<String>): Converter
+ = Converter(project, settings, conversionScope,
+ State(state.methodReturnType, state.expressionVisitorFactory, state.statementVisitorFactory, state.specialContext, state.importList, importsToAdd))
public fun elementToKotlin(element: PsiElement): String {
val converted = convertTopElement(element) ?: return ""
@@ -80,21 +105,22 @@ public class Converter private(val project: Project, val settings: ConverterSett
}
private fun convertFile(javaFile: PsiJavaFile): File {
+ val importsToAdd = LinkedHashSet<String>()
+ var converter = this.withImportsToAdd(importsToAdd)
var convertedChildren = javaFile.getChildren().map {
if (it is PsiImportList) {
val importList = convertImportList(it)
- typeConverter.importList = importList
+ converter = converter.withImportList(importList)
importList
}
else {
- convertTopElement(it)
+ converter.convertTopElement(it)
}
}.filterNotNull()
- typeConverter.importList = null
- if (typeConverter.importsToAdd.isNotEmpty()) {
+ if (importsToAdd.isNotEmpty()) {
val importList = convertedChildren.filterIsInstance(javaClass<ImportList>()).first()
- val newImportList = ImportList(importList.imports + typeConverter.importsToAdd).assignPrototypesFrom(importList)
+ val newImportList = ImportList(importList.imports + importsToAdd.map { Import(it).assignNoPrototype() }).assignPrototypesFrom(importList)
convertedChildren = convertedChildren.map { if (it == importList) newImportList else it }
}
@@ -392,6 +418,7 @@ public class Converter private(val project: Project, val settings: ConverterSett
return expressionVisitor.result.assignPrototype(expression)
}
+ //TODO: drop this method - it has unclear semantics
fun convertElement(element: PsiElement?): Element {
if (element == null) return Element.Empty
@@ -400,6 +427,46 @@ public class Converter private(val project: Project, val settings: ConverterSett
return elementVisitor.result.assignPrototype(element)
}
+ fun convertCodeReferenceElement(element: PsiJavaCodeReferenceElement, hasExternalQualifier: Boolean, typeArgsConverted: List<Element>? = null): ReferenceElement {
+ val typeArgs = typeArgsConverted ?: typeConverter.convertTypes(element.getTypeParameters())
+
+ if (element.isQualified()) {
+ var result = Identifier.toKotlin(element.getReferenceName()!!)
+ var qualifier = element.getQualifier()
+ while (qualifier != null) {
+ val codeRefElement = qualifier as PsiJavaCodeReferenceElement
+ result = Identifier.toKotlin(codeRefElement.getReferenceName()!!) + "." + result
+ qualifier = codeRefElement.getQualifier()
+ }
+ return ReferenceElement(Identifier(result).assignNoPrototype(), typeArgs).assignPrototype(element)
+ }
+ else {
+ if (!hasExternalQualifier) {
+ // references to nested classes may need correction
+ val targetClass = element.resolve() as? PsiClass
+ if (targetClass != null) {
+ val identifier = constructNestedClassReferenceIdentifier(targetClass, specialContext ?: element)
+ if (identifier != null) {
+ return ReferenceElement(identifier, typeArgs).assignPrototype(element)
+ }
+ }
+ }
+
+ return ReferenceElement(Identifier(element.getReferenceName()!!).assignNoPrototype(), typeArgs).assignPrototype(element)
+ }
+ }
+
+ private fun constructNestedClassReferenceIdentifier(psiClass: PsiClass, context: PsiElement): Identifier? {
+ val outerClass = psiClass.getContainingClass()
+ if (outerClass != null
+ && !PsiTreeUtil.isAncestor(outerClass, context, true)
+ && !psiClass.isImported(context.getContainingFile() as PsiJavaFile)) {
+ val qualifier = constructNestedClassReferenceIdentifier(outerClass, context)?.name ?: outerClass.getName()!!
+ return Identifier(Identifier.toKotlin(qualifier) + "." + Identifier.toKotlin(psiClass.getName()!!)).assignNoPrototype()
+ }
+ return null
+ }
+
fun convertTypeElement(element: PsiTypeElement?): TypeElement
= TypeElement(if (element == null) ErrorType().assignNoPrototype() else typeConverter.convertType(element.getType())).assignPrototype(element)
diff --git a/j2k/src/org/jetbrains/jet/j2k/TypeConverter.kt b/j2k/src/org/jetbrains/jet/j2k/TypeConverter.kt
index 683d327f3a4d6..023bad75cdf26 100644
--- a/j2k/src/org/jetbrains/jet/j2k/TypeConverter.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/TypeConverter.kt
@@ -31,27 +31,16 @@ import org.jetbrains.jet.j2k.ast.ErrorType
import com.intellij.codeInsight.NullableNotNullManager
import org.jetbrains.jet.j2k.ast.ArrayType
import org.jetbrains.jet.j2k.ast.ClassType
+import org.jetbrains.jet.j2k.ast.ReferenceElement
import org.jetbrains.jet.j2k.ast.Identifier
-class TypeConverter(val settings: ConverterSettings, val conversionScope: ConversionScope) {
+class TypeConverter(val converter: Converter) {
private val nullabilityCache = HashMap<PsiElement, Nullability>()
- private val classesToImport = HashSet<String>()
-
- public var importList: ImportList? = null
- set(value) {
- $importList = value
- importNames = importList?.imports?.mapTo(HashSet<String>()) { it.name } ?: setOf()
-
- }
- private var importNames: Set<String> = setOf()
-
- public val importsToAdd: Collection<Import>
- get() = classesToImport.map { Import(it).assignNoPrototype() }
public fun convertType(`type`: PsiType?, nullability: Nullability = Nullability.Default): Type {
if (`type` == null) return ErrorType().assignNoPrototype()
- val result = `type`.accept<Type>(TypeVisitor(this, importNames, classesToImport))!!.assignNoPrototype()
+ val result = `type`.accept<Type>(TypeVisitor(converter))!!.assignNoPrototype()
return when (nullability) {
Nullability.NotNull -> result.toNotNullType()
Nullability.Nullable -> result.toNullableType()
@@ -64,9 +53,9 @@ class TypeConverter(val settings: ConverterSettings, val conversionScope: Conver
public fun convertVariableType(variable: PsiVariable): Type {
val result = if (variable.isMainMethodParameter()) {
- ArrayType(ClassType(Identifier("String").assignNoPrototype(), listOf(), Nullability.NotNull, settings).assignNoPrototype(),
+ ArrayType(ClassType(ReferenceElement(Identifier("String").assignNoPrototype(), listOf()).assignNoPrototype(), Nullability.NotNull, converter.settings).assignNoPrototype(),
Nullability.NotNull,
- settings)
+ converter.settings).assignNoPrototype()
}
else {
convertType(variable.getType(), variableNullability(variable))
@@ -124,7 +113,7 @@ class TypeConverter(val settings: ConverterSettings, val conversionScope: Conver
return Nullability.NotNull
}
- if (!conversionScope.contains(variable)) { // do not analyze usages out of our conversion scope
+ if (!converter.conversionScope.contains(variable)) { // do not analyze usages out of our conversion scope
if (variable is PsiParameter) {
// Object.equals corresponds to Any.equals which has nullable parameter:
val scope = variable.getDeclarationScope()
@@ -203,7 +192,7 @@ class TypeConverter(val settings: ConverterSettings, val conversionScope: Conver
return Nullability.Nullable
}
- if (!conversionScope.contains(method)) return nullability // do not analyze body and usages of methods out of our conversion scope
+ if (!converter.conversionScope.contains(method)) return nullability // do not analyze body and usages of methods out of our conversion scope
if (nullability == Nullability.Default) {
method.getBody()?.accept(object: JavaRecursiveElementVisitor() {
diff --git a/j2k/src/org/jetbrains/jet/j2k/Utils.kt b/j2k/src/org/jetbrains/jet/j2k/Utils.kt
index 4d230d79981c3..9f1cdf95918d3 100644
--- a/j2k/src/org/jetbrains/jet/j2k/Utils.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/Utils.kt
@@ -139,3 +139,20 @@ fun PsiMethod.isMainMethod(): Boolean = PsiMethodUtil.isMainMethod(this)
fun <T: Any> List<T>.singleOrNull2(): T? = if (size == 1) this[0] else null
fun <T: Any> Array<T>.singleOrNull2(): T? = if (size == 1) this[0] else null
+
+fun PsiMember.isImported(file: PsiJavaFile): Boolean {
+ if (this is PsiClass) {
+ val fqName = getQualifiedName()
+ val index = fqName?.lastIndexOf('.') ?: -1
+ val parentName = if (index >= 0) fqName!!.substring(0, index) else null
+ return file.getImportList()?.getAllImportStatements()?.any {
+ it.getImportReference()?.getQualifiedName() == (if (it.isOnDemand()) parentName else fqName)
+ } ?: false
+ }
+ else {
+ return getContainingClass() != null && file.getImportList()?.getImportStaticStatements()?.any {
+ it.resolveTargetClass() == getContainingClass() && (it.isOnDemand() || it.getReferenceName() == getName())
+ } ?: false
+ }
+}
+
diff --git a/j2k/src/org/jetbrains/jet/j2k/ast/NewClassExpression.kt b/j2k/src/org/jetbrains/jet/j2k/ast/NewClassExpression.kt
index bf4b77386c827..0633e3b466f1b 100644
--- a/j2k/src/org/jetbrains/jet/j2k/ast/NewClassExpression.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/ast/NewClassExpression.kt
@@ -19,7 +19,7 @@ package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.*
class NewClassExpression(
- val name: Element,
+ val name: ReferenceElement?,
val arguments: List<Expression>,
val qualifier: Expression = Expression.Empty,
val anonymousClass: AnonymousClassBody? = null
@@ -34,7 +34,9 @@ class NewClassExpression(
builder.append(qualifier).append(if (qualifier.isNullable) "!!." else ".")
}
- builder.append(name)
+ if (name != null) {
+ builder.append(name)
+ }
if (anonymousClass == null || !anonymousClass.extendsTrait) {
builder.append("(").append(arguments, ", ").append(")")
diff --git a/j2k/src/org/jetbrains/jet/j2k/ast/ReferenceElement.kt b/j2k/src/org/jetbrains/jet/j2k/ast/ReferenceElement.kt
index 9e03f71646f8b..ea8a8f8f8d302 100644
--- a/j2k/src/org/jetbrains/jet/j2k/ast/ReferenceElement.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/ast/ReferenceElement.kt
@@ -18,8 +18,8 @@ package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.*
-class ReferenceElement(val reference: Identifier, val types: List<Type>) : Element() {
+class ReferenceElement(val name: Identifier, val typeArgs: List<Element>) : Element() {
override fun generateCode(builder: CodeBuilder) {
- builder.append(reference).append(types, ", ", "<", ">")
+ builder.append(name).append(typeArgs, ", ", "<", ">")
}
}
diff --git a/j2k/src/org/jetbrains/jet/j2k/ast/Types.kt b/j2k/src/org/jetbrains/jet/j2k/ast/Types.kt
index 1e4e6fc71c231..cb58efc14beb9 100644
--- a/j2k/src/org/jetbrains/jet/j2k/ast/Types.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/ast/Types.kt
@@ -78,15 +78,15 @@ class ErrorType : NotNullType() {
}
}
-class ClassType(val name: Identifier, val typeArgs: List<Element>, nullability: Nullability, settings: ConverterSettings)
+class ClassType(val referenceElement: ReferenceElement, nullability: Nullability, settings: ConverterSettings)
: MayBeNullableType(nullability, settings) {
override fun generateCode(builder: CodeBuilder) {
- builder.append(name).append(typeArgs, ", ", "<", ">").append(isNullableStr)
+ builder append referenceElement append isNullableStr
}
- override fun toNotNullType(): Type = ClassType(name, typeArgs, Nullability.NotNull, settings).assignPrototypesFrom(this)
- override fun toNullableType(): Type = ClassType(name, typeArgs, Nullability.Nullable, settings).assignPrototypesFrom(this)
+ override fun toNotNullType(): Type = ClassType(referenceElement, Nullability.NotNull, settings).assignPrototypesFrom(this)
+ override fun toNullableType(): Type = ClassType(referenceElement, Nullability.Nullable, settings).assignPrototypesFrom(this)
}
class ArrayType(val elementType: Type, nullability: Nullability, settings: ConverterSettings)
diff --git a/j2k/src/org/jetbrains/jet/j2k/visitors/ElementVisitor.kt b/j2k/src/org/jetbrains/jet/j2k/visitors/ElementVisitor.kt
index 6f5d0bab88c2b..2e971a8196d2c 100644
--- a/j2k/src/org/jetbrains/jet/j2k/visitors/ElementVisitor.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/visitors/ElementVisitor.kt
@@ -42,23 +42,6 @@ class ElementVisitor(private val converter: Converter) : JavaElementVisitor() {
result = ExpressionList(converter.convertExpressions(list.getExpressions()))
}
- override fun visitReferenceElement(reference: PsiJavaCodeReferenceElement) {
- val types = typeConverter.convertTypes(reference.getTypeParameters())
- if (!reference.isQualified()) {
- result = ReferenceElement(Identifier(reference.getReferenceName()!!).assignNoPrototype(), types)
- }
- else {
- var code = Identifier.toKotlin(reference.getReferenceName()!!)
- var qualifier = reference.getQualifier()
- while (qualifier != null) {
- val p = qualifier as PsiJavaCodeReferenceElement
- code = Identifier.toKotlin(p.getReferenceName()!!) + "." + code
- qualifier = p.getQualifier()
- }
- result = ReferenceElement(Identifier(code).assignNoPrototype(), types)
- }
- }
-
override fun visitTypeElement(`type`: PsiTypeElement) {
result = TypeElement(typeConverter.convertType(`type`.getType()))
}
diff --git a/j2k/src/org/jetbrains/jet/j2k/visitors/ExpressionVisitor.kt b/j2k/src/org/jetbrains/jet/j2k/visitors/ExpressionVisitor.kt
index 22d42e06c31a8..63ccb01eadce6 100644
--- a/j2k/src/org/jetbrains/jet/j2k/visitors/ExpressionVisitor.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/visitors/ExpressionVisitor.kt
@@ -254,19 +254,17 @@ open class ExpressionVisitor(private val converter: Converter) : JavaElementVisi
converter.convertExpressions(expression.getArrayDimensions()))
}
else {
- result = createNewClassExpression(expression)
+ val anonymousClass = expression.getAnonymousClass()
+ val qualifier = expression.getQualifier()
+ val classRef = expression.getClassOrAnonymousClassReference()
+ val classRefConverted = if (classRef != null) converter.convertCodeReferenceElement(classRef, hasExternalQualifier = qualifier != null) else null
+ result = NewClassExpression(classRefConverted,
+ convertArguments(expression),
+ converter.convertExpression(qualifier),
+ if (anonymousClass != null) converter.convertAnonymousClassBody(anonymousClass) else null)
}
}
- private fun createNewClassExpression(expression: PsiNewExpression): Expression {
- val anonymousClass = expression.getAnonymousClass()
- val classReference = expression.getClassOrAnonymousClassReference()
- return NewClassExpression(converter.convertElement(classReference),
- convertArguments(expression),
- converter.convertExpression(expression.getQualifier()),
- if (anonymousClass != null) converter.convertAnonymousClassBody(anonymousClass) else null)
- }
-
override fun visitParenthesizedExpression(expression: PsiParenthesizedExpression) {
result = ParenthesizedExpression(converter.convertExpression(expression.getExpression()))
}
@@ -317,16 +315,18 @@ open class ExpressionVisitor(private val converter: Converter) : JavaElementVisi
}
// add qualification for static members from base classes and also this works for enum constants in switch
+ val context = converter.specialContext ?: expression
if (target is PsiMember
&& target.hasModifierProperty(PsiModifier.STATIC)
&& target.getContainingClass() != null
- && !PsiTreeUtil.isAncestor(target.getContainingClass(), expression, true)
- && !isStaticallyImported(target, expression)) {
+ && !PsiTreeUtil.isAncestor(target.getContainingClass(), context, true)
+ && !target.isImported(context.getContainingFile() as PsiJavaFile)) {
var member: PsiMember = target
var code = Identifier.toKotlin(referenceName)
- while (member.getContainingClass() != null) {
- code = Identifier.toKotlin(member.getContainingClass()!!.getName()!!) + "." + code
- member = member.getContainingClass()!!
+ while (true) {
+ val containingClass = member.getContainingClass() ?: break
+ code = Identifier.toKotlin(containingClass.getName()!!) + "." + code
+ member = containingClass
}
result = Identifier(code, false, false)
return
@@ -433,23 +433,4 @@ open class ExpressionVisitor(private val converter: Converter) : JavaElementVisi
}
return ""
}
-
- private fun isStaticallyImported(member: PsiMember, context: PsiElement): Boolean {
- val containingFile = context.getContainingFile()
- val targetContainingClass = member.getContainingClass()
- if (containingFile is PsiJavaFile && targetContainingClass != null) {
- val importList = containingFile.getImportList();
- if (importList != null) {
- return importList.getImportStaticStatements().any { importResolvesTo(it, member) }
- }
- }
- return false
- }
-
- private fun importResolvesTo(importStatement: PsiImportStaticStatement, member: PsiMember): Boolean {
- val targetContainingClass = member.getContainingClass()
- val importedClass = importStatement.resolveTargetClass()
- return importedClass == targetContainingClass
- && (importStatement.isOnDemand() || importStatement.getReferenceName() == member.getName())
- }
}
diff --git a/j2k/src/org/jetbrains/jet/j2k/visitors/TypeVisitor.kt b/j2k/src/org/jetbrains/jet/j2k/visitors/TypeVisitor.kt
index c11ea5193d3e7..2db88fd1b88e4 100644
--- a/j2k/src/org/jetbrains/jet/j2k/visitors/TypeVisitor.kt
+++ b/j2k/src/org/jetbrains/jet/j2k/visitors/TypeVisitor.kt
@@ -19,15 +19,19 @@ package org.jetbrains.jet.j2k.visitors
import com.intellij.psi.*
import com.intellij.psi.impl.source.PsiClassReferenceType
import org.jetbrains.jet.j2k.ast.*
-import java.util.LinkedList
import com.intellij.openapi.util.text.StringUtil
-import java.util.ArrayList
import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType
import org.jetbrains.jet.j2k.TypeConverter
+import java.util.ArrayList
+import org.jetbrains.jet.j2k.singleOrNull2
+import org.jetbrains.jet.j2k.Converter
private val PRIMITIVE_TYPES_NAMES = JvmPrimitiveType.values().map { it.getName() }
-class TypeVisitor(private val converter: TypeConverter, private val importNames: Set<String>, private val classesToImport: MutableSet<String>) : PsiTypeVisitor<Type>() {
+class TypeVisitor(private val converter: Converter) : PsiTypeVisitor<Type>() {
+
+ private val typeConverter: TypeConverter = converter.typeConverter
+
override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): Type {
val name = primitiveType.getCanonicalText()
return if (name == "void") {
@@ -45,100 +49,86 @@ class TypeVisitor(private val converter: TypeConverter, private val importNames:
}
override fun visitArrayType(arrayType: PsiArrayType): Type {
- return ArrayType(converter.convertType(arrayType.getComponentType()), Nullability.Default, converter.settings)
+ return ArrayType(typeConverter.convertType(arrayType.getComponentType()), Nullability.Default, converter.settings)
}
override fun visitClassType(classType: PsiClassType): Type {
- val identifier = constructClassTypeIdentifier(classType)
- val resolvedClassTypeParams = createRawTypesForResolvedReference(classType)
- if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) {
- val starParamList = ArrayList<Type>()
- if (resolvedClassTypeParams.size() == 1) {
- if ((resolvedClassTypeParams.single() as ClassType).name.name == "Any") {
- starParamList.add(StarProjectionType())
- return ClassType(identifier, starParamList, Nullability.Default, converter.settings)
- }
- else {
- return ClassType(identifier, resolvedClassTypeParams, Nullability.Default, converter.settings)
- }
- }
- else {
- return ClassType(identifier, resolvedClassTypeParams, Nullability.Default, converter.settings)
- }
- }
- else {
- return ClassType(identifier, converter.convertTypes(classType.getParameters()), Nullability.Default, converter.settings)
- }
+ val refElement = constructReferenceElement(classType)
+ return ClassType(refElement, Nullability.Default, converter.settings)
}
- private fun constructClassTypeIdentifier(classType: PsiClassType): Identifier {
+ private fun constructReferenceElement(classType: PsiClassType): ReferenceElement {
+ val typeArgs = convertTypeArgs(classType)
+
val psiClass = classType.resolve()
if (psiClass != null) {
val javaClassName = psiClass.getQualifiedName()
val kotlinClassName = toKotlinTypesMap[javaClassName]
if (kotlinClassName != null) {
val kotlinShortName = getShortName(kotlinClassName)
- if (kotlinShortName == getShortName(javaClassName!!) && importNames.contains(getPackageName(javaClassName) + ".*")) {
- classesToImport.add(kotlinClassName)
+ if (kotlinShortName == getShortName(javaClassName!!) && converter.importNames.contains(getPackageName(javaClassName) + ".*")) {
+ converter.importsToAdd?.add(kotlinClassName)
}
- return Identifier(kotlinShortName).assignNoPrototype()
+ return ReferenceElement(Identifier(kotlinShortName).assignNoPrototype(), typeArgs).assignNoPrototype()
}
}
if (classType is PsiClassReferenceType) {
- val reference = classType.getReference()
- if (reference.isQualified()) {
- var result = Identifier.toKotlin(reference.getReferenceName()!!)
- var qualifier = reference.getQualifier()
- while (qualifier != null) {
- val codeRefElement = qualifier as PsiJavaCodeReferenceElement
- result = Identifier.toKotlin(codeRefElement.getReferenceName()!!) + "." + result
- qualifier = codeRefElement.getQualifier()
- }
- return Identifier(result).assignNoPrototype()
- }
+ return converter.convertCodeReferenceElement(classType.getReference(), hasExternalQualifier = false, typeArgsConverted = typeArgs)
}
- return Identifier(classType.getClassName() ?: "").assignNoPrototype()
+ return ReferenceElement(Identifier(classType.getClassName() ?: "").assignNoPrototype(), typeArgs).assignNoPrototype()
}
private fun getPackageName(className: String): String = className.substring(0, className.lastIndexOf('.'))
private fun getShortName(className: String): String = className.substring(className.lastIndexOf('.') + 1)
+ private fun convertTypeArgs(classType: PsiClassType): List<Type> {
+ val resolvedClassTypeParams = createRawTypesForResolvedReference(classType)
+
+ if (classType.getParameterCount() == 0 && resolvedClassTypeParams.size() > 0) {
+ if ((resolvedClassTypeParams.singleOrNull2() as? ClassType)?.referenceElement?.name?.name == "Any") {
+ return listOf(StarProjectionType().assignNoPrototype())
+ }
+ else {
+ return resolvedClassTypeParams
+ }
+ }
+ else {
+ return typeConverter.convertTypes(classType.getParameters())
+ }
+ }
+
private fun createRawTypesForResolvedReference(classType: PsiClassType): List<Type> {
- val typeParams = LinkedList<Type>()
+ val typeArgs = ArrayList<Type>()
if (classType is PsiClassReferenceType) {
val resolve = classType.getReference().resolve()
if (resolve is PsiClass) {
for (typeParam in resolve.getTypeParameters()) {
val superTypes = typeParam.getSuperTypes()
val boundType = if (superTypes.size > 0) {
- ClassType(constructClassTypeIdentifier(superTypes[0]),
- converter.convertTypes(superTypes[0].getParameters()),
- Nullability.Default,
- converter.settings)
+ ClassType(constructReferenceElement(superTypes.first()), Nullability.Default, converter.settings)
}
else {
StarProjectionType()
}
- typeParams.add(boundType)
+ typeArgs.add(boundType)
}
}
}
-
- return typeParams
+ return typeArgs
}
override fun visitWildcardType(wildcardType: PsiWildcardType): Type {
return when {
- wildcardType.isExtends() -> OutProjectionType(converter.convertType(wildcardType.getExtendsBound()))
- wildcardType.isSuper() -> InProjectionType(converter.convertType(wildcardType.getSuperBound()))
+ wildcardType.isExtends() -> OutProjectionType(typeConverter.convertType(wildcardType.getExtendsBound()))
+ wildcardType.isSuper() -> InProjectionType(typeConverter.convertType(wildcardType.getSuperBound()))
else -> StarProjectionType()
}
}
override fun visitEllipsisType(ellipsisType: PsiEllipsisType): Type {
- return VarArgType(converter.convertType(ellipsisType.getComponentType()))
+ return VarArgType(typeConverter.convertType(ellipsisType.getComponentType()))
}
class object {
diff --git a/j2k/tests/test/org/jetbrains/jet/j2k/test/JavaToKotlinConverterTestGenerated.java b/j2k/tests/test/org/jetbrains/jet/j2k/test/JavaToKotlinConverterTestGenerated.java
index 583bce28b59c2..5c7acbdb32578 100644
--- a/j2k/tests/test/org/jetbrains/jet/j2k/test/JavaToKotlinConverterTestGenerated.java
+++ b/j2k/tests/test/org/jetbrains/jet/j2k/test/JavaToKotlinConverterTestGenerated.java
@@ -891,6 +891,31 @@ public void testMethodCallInFactoryFun() throws Exception {
doTest("j2k/tests/testData/ast/constructors/methodCallInFactoryFun.java");
}
+ @TestMetadata("nestedClassNameInParameterDefaults.java")
+ public void testNestedClassNameInParameterDefaults() throws Exception {
+ doTest("j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.java");
+ }
+
+ @TestMetadata("nestedClassNameInParameterDefaults2.java")
+ public void testNestedClassNameInParameterDefaults2() throws Exception {
+ doTest("j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.java");
+ }
+
+ @TestMetadata("nestedClassNameInParameterDefaults3.java")
+ public void testNestedClassNameInParameterDefaults3() throws Exception {
+ doTest("j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.java");
+ }
+
+ @TestMetadata("nestedClassNameInParameterDefaults4.java")
+ public void testNestedClassNameInParameterDefaults4() throws Exception {
+ doTest("j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.java");
+ }
+
+ @TestMetadata("nestedClassNameInSuperParameters.java")
+ public void testNestedClassNameInSuperParameters() throws Exception {
+ doTest("j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.java");
+ }
+
@TestMetadata("noPrimary.java")
public void testNoPrimary() throws Exception {
doTest("j2k/tests/testData/ast/constructors/noPrimary.java");
@@ -1732,6 +1757,16 @@ public void testKt_1074() throws Exception {
doTest("j2k/tests/testData/ast/issues/kt-1074.java");
}
+ @TestMetadata("kt-5294.java")
+ public void testKt_5294() throws Exception {
+ doTest("j2k/tests/testData/ast/issues/kt-5294.java");
+ }
+
+ @TestMetadata("kt-5400.java")
+ public void testKt_5400() throws Exception {
+ doTest("j2k/tests/testData/ast/issues/kt-5400.java");
+ }
+
@TestMetadata("kt-543.java")
public void testKt_543() throws Exception {
doTest("j2k/tests/testData/ast/issues/kt-543.java");
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.java b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.java
new file mode 100644
index 0000000000000..7a3c0871328f9
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.java
@@ -0,0 +1,14 @@
+class A {
+ A(Nested nested) {
+ }
+
+ A() {
+ this(new Nested(Nested.FIELD));
+ }
+
+ static class Nested {
+ Nested(int p){}
+
+ public static final int FIELD = 0;
+ }
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.kt b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.kt
new file mode 100644
index 0000000000000..2b1329fa6e2f0
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults.kt
@@ -0,0 +1,9 @@
+class A(nested: A.Nested = A.Nested(A.Nested.FIELD)) {
+
+ class Nested(p: Int) {
+ class object {
+
+ public val FIELD: Int = 0
+ }
+ }
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.java b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.java
new file mode 100644
index 0000000000000..bc5ec29ece16e
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.java
@@ -0,0 +1,20 @@
+import A.Nested;
+
+class A {
+ A(Nested nested) {
+ }
+
+ A() {
+ this(new Nested(Nested.FIELD));
+ }
+
+ static class Nested {
+ Nested(int p){}
+
+ public static final int FIELD = 0;
+ }
+}
+
+class B {
+ Nested nested;
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.kt b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.kt
new file mode 100644
index 0000000000000..9e82b2b95da77
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults2.kt
@@ -0,0 +1,15 @@
+import A.Nested
+
+class A(nested: Nested = Nested(Nested.FIELD)) {
+
+ class Nested(p: Int) {
+ class object {
+
+ public val FIELD: Int = 0
+ }
+ }
+}
+
+class B {
+ var nested: Nested
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.java b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.java
new file mode 100644
index 0000000000000..7ead1b36cbde4
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.java
@@ -0,0 +1,22 @@
+package pack;
+
+import static pack.A.Nested;
+
+class A {
+ A(Nested nested) {
+ }
+
+ A() {
+ this(new Nested(Nested.FIELD));
+ }
+
+ static class Nested {
+ Nested(int p){}
+
+ public static final int FIELD = 0;
+ }
+}
+
+class B {
+ Nested nested;
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.kt b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.kt
new file mode 100644
index 0000000000000..2cbf12aa27691
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults3.kt
@@ -0,0 +1,17 @@
+package pack
+
+import pack.A.Nested
+
+class A(nested: Nested = Nested(Nested.FIELD)) {
+
+ class Nested(p: Int) {
+ class object {
+
+ public val FIELD: Int = 0
+ }
+ }
+}
+
+class B {
+ var nested: Nested
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.java b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.java
new file mode 100644
index 0000000000000..13c194022f6b2
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.java
@@ -0,0 +1,22 @@
+package pack;
+
+import static pack.A.*;
+
+class A {
+ A(Nested nested) {
+ }
+
+ A() {
+ this(new Nested(Nested.FIELD));
+ }
+
+ static class Nested {
+ Nested(int p){}
+
+ public static final int FIELD = 0;
+ }
+}
+
+class B {
+ Nested nested;
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.kt b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.kt
new file mode 100644
index 0000000000000..9fadc53f7993f
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInParameterDefaults4.kt
@@ -0,0 +1,17 @@
+package pack
+
+import pack.A.*
+
+class A(nested: Nested = Nested(Nested.FIELD)) {
+
+ class Nested(p: Int) {
+ class object {
+
+ public val FIELD: Int = 0
+ }
+ }
+}
+
+class B {
+ var nested: Nested
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.java b/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.java
new file mode 100644
index 0000000000000..41d02ece96f5b
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.java
@@ -0,0 +1,15 @@
+class Base {
+ Base(Nested nested){}
+
+ static class Nested {
+ Nested(int p){}
+
+ public static final int FIELD = 0;
+ }
+}
+
+class Derived extends Base {
+ Derived() {
+ super(new Nested(Nested.FIELD));
+ }
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.kt b/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.kt
new file mode 100644
index 0000000000000..00bb71e559e81
--- /dev/null
+++ b/j2k/tests/testData/ast/constructors/nestedClassNameInSuperParameters.kt
@@ -0,0 +1,11 @@
+class Base(nested: Base.Nested) {
+
+ class Nested(p: Int) {
+ class object {
+
+ public val FIELD: Int = 0
+ }
+ }
+}
+
+class Derived : Base(Base.Nested(Base.Nested.FIELD))
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/issues/kt-5294.java b/j2k/tests/testData/ast/issues/kt-5294.java
new file mode 100644
index 0000000000000..cdb89eaf4c39c
--- /dev/null
+++ b/j2k/tests/testData/ast/issues/kt-5294.java
@@ -0,0 +1,11 @@
+import java.util.List;
+
+class X {
+ private final List<Y> list;
+
+ X(List<Y> list) {
+ this.list = list;
+ }
+
+ class Y{}
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/issues/kt-5294.kt b/j2k/tests/testData/ast/issues/kt-5294.kt
new file mode 100644
index 0000000000000..afbba72669bce
--- /dev/null
+++ b/j2k/tests/testData/ast/issues/kt-5294.kt
@@ -0,0 +1,4 @@
+class X(private val list: List<X.Y>) {
+
+ inner class Y
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/issues/kt-5400.java b/j2k/tests/testData/ast/issues/kt-5400.java
new file mode 100644
index 0000000000000..c4c379a5f163e
--- /dev/null
+++ b/j2k/tests/testData/ast/issues/kt-5400.java
@@ -0,0 +1,7 @@
+class Base {
+ class Nested{}
+}
+
+class Derived extends Base {
+ Nested field;
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/issues/kt-5400.kt b/j2k/tests/testData/ast/issues/kt-5400.kt
new file mode 100644
index 0000000000000..ca4e330311275
--- /dev/null
+++ b/j2k/tests/testData/ast/issues/kt-5400.kt
@@ -0,0 +1,7 @@
+class Base {
+ inner class Nested
+}
+
+class Derived : Base() {
+ var field: Base.Nested
+}
\ No newline at end of file
diff --git a/j2k/tests/testData/ast/toKotlinClasses/TypeParameterBound.kt b/j2k/tests/testData/ast/toKotlinClasses/TypeParameterBound.kt
index 89db7b8c731fc..15cd57f1d3c8d 100644
--- a/j2k/tests/testData/ast/toKotlinClasses/TypeParameterBound.kt
+++ b/j2k/tests/testData/ast/toKotlinClasses/TypeParameterBound.kt
@@ -1,6 +1,6 @@
import java.util.*
-import kotlin.List
import kotlin.Iterator
+import kotlin.List
trait I<T : List<Iterator<String>>>
|
64bed0460e0bab9157e71192a18b2285bf1ef536
|
hadoop
|
YARN-1063. Augmented Hadoop common winutils to have- the ability to create containers as domain users. Contributed by Remus- Rusanu. Committed as a YARN patch even though all the code changes are in- common.--(cherry picked from commit 5ca97f1e60b8a7848f6eadd15f6c08ed390a8cda)-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-common-project/hadoop-common/src/main/winutils/chown.c b/hadoop-common-project/hadoop-common/src/main/winutils/chown.c
index bc2aefc79eeb1..1be81216974a5 100644
--- a/hadoop-common-project/hadoop-common/src/main/winutils/chown.c
+++ b/hadoop-common-project/hadoop-common/src/main/winutils/chown.c
@@ -63,11 +63,11 @@ static DWORD ChangeFileOwnerBySid(__in LPCWSTR path,
// SID is not contained in the caller's token, and have the SE_GROUP_OWNER
// permission enabled.
//
- if (!EnablePrivilege(L"SeTakeOwnershipPrivilege"))
+ if (EnablePrivilege(L"SeTakeOwnershipPrivilege") != ERROR_SUCCESS)
{
fwprintf(stdout, L"INFO: The user does not have SeTakeOwnershipPrivilege.\n");
}
- if (!EnablePrivilege(L"SeRestorePrivilege"))
+ if (EnablePrivilege(L"SeRestorePrivilege") != ERROR_SUCCESS)
{
fwprintf(stdout, L"INFO: The user does not have SeRestorePrivilege.\n");
}
diff --git a/hadoop-common-project/hadoop-common/src/main/winutils/include/winutils.h b/hadoop-common-project/hadoop-common/src/main/winutils/include/winutils.h
index 1c0007a6da922..bae754c9b6e25 100644
--- a/hadoop-common-project/hadoop-common/src/main/winutils/include/winutils.h
+++ b/hadoop-common-project/hadoop-common/src/main/winutils/include/winutils.h
@@ -27,6 +27,8 @@
#include <accctrl.h>
#include <strsafe.h>
#include <lm.h>
+#include <ntsecapi.h>
+#include <userenv.h>
enum EXIT_CODE
{
@@ -153,6 +155,26 @@ DWORD ChangeFileModeByMask(__in LPCWSTR path, INT mode);
DWORD GetLocalGroupsForUser(__in LPCWSTR user,
__out LPLOCALGROUP_USERS_INFO_0 *groups, __out LPDWORD entries);
-BOOL EnablePrivilege(__in LPCWSTR privilegeName);
-
void GetLibraryName(__in LPCVOID lpAddress, __out LPWSTR *filename);
+
+DWORD EnablePrivilege(__in LPCWSTR privilegeName);
+
+void AssignLsaString(__inout LSA_STRING * target, __in const char *strBuf);
+
+DWORD RegisterWithLsa(__in const char *logonProcessName, __out HANDLE * lsaHandle);
+
+void UnregisterWithLsa(__in HANDLE lsaHandle);
+
+DWORD LookupKerberosAuthenticationPackageId(__in HANDLE lsaHandle, __out ULONG * packageId);
+
+DWORD CreateLogonForUser(__in HANDLE lsaHandle,
+ __in const char * tokenSourceName,
+ __in const char * tokenOriginName,
+ __in ULONG authnPkgId,
+ __in const wchar_t* principalName,
+ __out HANDLE *tokenHandle);
+
+DWORD LoadUserProfileForLogon(__in HANDLE logonHandle, __out PROFILEINFO * pi);
+
+DWORD UnloadProfileForLogon(__in HANDLE logonHandle, __in PROFILEINFO * pi);
+
diff --git a/hadoop-common-project/hadoop-common/src/main/winutils/libwinutils.c b/hadoop-common-project/hadoop-common/src/main/winutils/libwinutils.c
index 391247fccd47d..da16ff5b081c4 100644
--- a/hadoop-common-project/hadoop-common/src/main/winutils/libwinutils.c
+++ b/hadoop-common-project/hadoop-common/src/main/winutils/libwinutils.c
@@ -17,6 +17,8 @@
#pragma comment(lib, "authz.lib")
#pragma comment(lib, "netapi32.lib")
+#pragma comment(lib, "Secur32.lib")
+#pragma comment(lib, "Userenv.lib")
#include "winutils.h"
#include <authz.h>
#include <sddl.h>
@@ -797,7 +799,6 @@ DWORD FindFileOwnerAndPermission(
__out_opt PINT pMask)
{
DWORD dwRtnCode = 0;
-
PSECURITY_DESCRIPTOR pSd = NULL;
PSID psidOwner = NULL;
@@ -1638,11 +1639,12 @@ DWORD GetLocalGroupsForUser(
// to the process's access token.
//
// Returns:
-// TRUE: on success
+// ERROR_SUCCESS on success
+// GetLastError() on error
//
// Notes:
//
-BOOL EnablePrivilege(__in LPCWSTR privilegeName)
+DWORD EnablePrivilege(__in LPCWSTR privilegeName)
{
HANDLE hToken = INVALID_HANDLE_VALUE;
TOKEN_PRIVILEGES tp = { 0 };
@@ -1651,28 +1653,31 @@ BOOL EnablePrivilege(__in LPCWSTR privilegeName)
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
- ReportErrorCode(L"OpenProcessToken", GetLastError());
- return FALSE;
+ dwErrCode = GetLastError();
+ ReportErrorCode(L"OpenProcessToken", dwErrCode);
+ return dwErrCode;
}
tp.PrivilegeCount = 1;
if (!LookupPrivilegeValueW(NULL,
privilegeName, &(tp.Privileges[0].Luid)))
{
- ReportErrorCode(L"LookupPrivilegeValue", GetLastError());
+ dwErrCode = GetLastError();
+ ReportErrorCode(L"LookupPrivilegeValue", dwErrCode);
CloseHandle(hToken);
- return FALSE;
+ return dwErrCode;
}
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// As stated on MSDN, we need to use GetLastError() to check if
// AdjustTokenPrivileges() adjusted all of the specified privileges.
//
- AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
+ if( !AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL) ) {
dwErrCode = GetLastError();
+ }
CloseHandle(hToken);
- return dwErrCode == ERROR_SUCCESS;
+ return dwErrCode;
}
//----------------------------------------------------------------------------
@@ -1716,9 +1721,6 @@ void ReportErrorCode(LPCWSTR func, DWORD err)
// Description:
// Given an address, get the file name of the library from which it was loaded.
//
-// Returns:
-// None
-//
// Notes:
// - The function allocates heap memory and points the filename out parameter to
// the newly allocated memory, which will contain the name of the file.
@@ -1757,3 +1759,290 @@ void GetLibraryName(LPCVOID lpAddress, LPWSTR *filename)
*filename = NULL;
}
}
+
+// Function: AssignLsaString
+//
+// Description:
+// fills in values of LSA_STRING struct to point to a string buffer
+//
+// Returns:
+// None
+//
+// IMPORTANT*** strBuf is not copied. It must be globally immutable
+//
+void AssignLsaString(__inout LSA_STRING * target, __in const char *strBuf)
+{
+ target->Length = (USHORT)(sizeof(char)*strlen(strBuf));
+ target->MaximumLength = target->Length;
+ target->Buffer = (char *)(strBuf);
+}
+
+//----------------------------------------------------------------------------
+// Function: RegisterWithLsa
+//
+// Description:
+// Registers with local security authority and sets handle for use in later LSA
+// operations
+//
+// Returns:
+// ERROR_SUCCESS on success
+// Other error code on failure
+//
+// Notes:
+//
+DWORD RegisterWithLsa(__in const char *logonProcessName, __out HANDLE * lsaHandle)
+{
+ LSA_STRING processName;
+ LSA_OPERATIONAL_MODE o_mode; // never useful as per msdn docs
+ NTSTATUS registerStatus;
+ *lsaHandle = 0;
+
+ AssignLsaString(&processName, logonProcessName);
+ registerStatus = LsaRegisterLogonProcess(&processName, lsaHandle, &o_mode);
+
+ return LsaNtStatusToWinError( registerStatus );
+}
+
+//----------------------------------------------------------------------------
+// Function: UnregisterWithLsa
+//
+// Description:
+// Closes LSA handle allocated by RegisterWithLsa()
+//
+// Returns:
+// None
+//
+// Notes:
+//
+void UnregisterWithLsa(__in HANDLE lsaHandle)
+{
+ LsaClose(lsaHandle);
+}
+
+//----------------------------------------------------------------------------
+// Function: LookupKerberosAuthenticationPackageId
+//
+// Description:
+// Looks of the current id (integer index) of the Kerberos authentication package on the local
+// machine.
+//
+// Returns:
+// ERROR_SUCCESS on success
+// Other error code on failure
+//
+// Notes:
+//
+DWORD LookupKerberosAuthenticationPackageId(__in HANDLE lsaHandle, __out ULONG * packageId)
+{
+ NTSTATUS lookupStatus;
+ LSA_STRING pkgName;
+
+ AssignLsaString(&pkgName, MICROSOFT_KERBEROS_NAME_A);
+ lookupStatus = LsaLookupAuthenticationPackage(lsaHandle, &pkgName, packageId);
+ return LsaNtStatusToWinError( lookupStatus );
+}
+
+//----------------------------------------------------------------------------
+// Function: CreateLogonForUser
+//
+// Description:
+// Contacts the local LSA and performs a logon without credential for the
+// given principal. This logon token will be local machine only and have no
+// network credentials attached.
+//
+// Returns:
+// ERROR_SUCCESS on success
+// Other error code on failure
+//
+// Notes:
+// This call assumes that all required privileges have already been enabled (TCB etc).
+// IMPORTANT **** tokenOriginName must be immutable!
+//
+DWORD CreateLogonForUser(__in HANDLE lsaHandle,
+ __in const char * tokenSourceName,
+ __in const char * tokenOriginName, // must be immutable, will not be copied!
+ __in ULONG authnPkgId,
+ __in const wchar_t* principalName,
+ __out HANDLE *tokenHandle)
+{
+ DWORD logonStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
+ TOKEN_SOURCE tokenSource;
+ LSA_STRING originName;
+ void * profile = NULL;
+
+ // from MSDN:
+ // The ClientUpn and ClientRealm members of the KERB_S4U_LOGON
+ // structure must point to buffers in memory that are contiguous
+ // to the structure itself. The value of the
+ // AuthenticationInformationLength parameter must take into
+ // account the length of these buffers.
+ const int principalNameBufLen = lstrlen(principalName)*sizeof(*principalName);
+ const int totalAuthInfoLen = sizeof(KERB_S4U_LOGON) + principalNameBufLen;
+ KERB_S4U_LOGON* s4uLogonAuthInfo = (KERB_S4U_LOGON*)calloc(totalAuthInfoLen, 1);
+ if (s4uLogonAuthInfo == NULL ) {
+ logonStatus = ERROR_NOT_ENOUGH_MEMORY;
+ goto done;
+ }
+ s4uLogonAuthInfo->MessageType = KerbS4ULogon;
+ s4uLogonAuthInfo->ClientUpn.Buffer = (wchar_t*)((char*)s4uLogonAuthInfo + sizeof *s4uLogonAuthInfo);
+ CopyMemory(s4uLogonAuthInfo->ClientUpn.Buffer, principalName, principalNameBufLen);
+ s4uLogonAuthInfo->ClientUpn.Length = (USHORT)principalNameBufLen;
+ s4uLogonAuthInfo->ClientUpn.MaximumLength = (USHORT)principalNameBufLen;
+
+ AllocateLocallyUniqueId(&tokenSource.SourceIdentifier);
+ StringCchCopyA(tokenSource.SourceName, TOKEN_SOURCE_LENGTH, tokenSourceName );
+ AssignLsaString(&originName, tokenOriginName);
+
+ {
+ DWORD cbProfile = 0;
+ LUID logonId;
+ QUOTA_LIMITS quotaLimits;
+ NTSTATUS subStatus;
+
+ NTSTATUS logonNtStatus = LsaLogonUser(lsaHandle,
+ &originName,
+ Batch, // SECURITY_LOGON_TYPE
+ authnPkgId,
+ s4uLogonAuthInfo,
+ totalAuthInfoLen,
+ 0,
+ &tokenSource,
+ &profile,
+ &cbProfile,
+ &logonId,
+ tokenHandle,
+ "aLimits,
+ &subStatus);
+ logonStatus = LsaNtStatusToWinError( logonNtStatus );
+ }
+done:
+ // clean up
+ if (s4uLogonAuthInfo != NULL) {
+ free(s4uLogonAuthInfo);
+ }
+ if (profile != NULL) {
+ LsaFreeReturnBuffer(profile);
+ }
+ return logonStatus;
+}
+
+// NOTE: must free allocatedName
+DWORD GetNameFromLogonToken(__in HANDLE logonToken, __out wchar_t **allocatedName)
+{
+ DWORD userInfoSize = 0;
+ PTOKEN_USER user = NULL;
+ DWORD userNameSize = 0;
+ wchar_t * userName = NULL;
+ DWORD domainNameSize = 0;
+ wchar_t * domainName = NULL;
+ SID_NAME_USE sidUse = SidTypeUnknown;
+ DWORD getNameStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
+ BOOL tokenInformation = FALSE;
+
+ // call for sid size then alloc and call for sid
+ tokenInformation = GetTokenInformation(logonToken, TokenUser, NULL, 0, &userInfoSize);
+ assert (FALSE == tokenInformation);
+
+ // last call should have failed and filled in allocation size
+ if ((getNameStatus = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
+ {
+ goto done;
+ }
+ user = (PTOKEN_USER)calloc(userInfoSize,1);
+ if (user == NULL)
+ {
+ getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
+ goto done;
+ }
+ if (!GetTokenInformation(logonToken, TokenUser, user, userInfoSize, &userInfoSize)) {
+ getNameStatus = GetLastError();
+ goto done;
+ }
+ LookupAccountSid( NULL, user->User.Sid, NULL, &userNameSize, NULL, &domainNameSize, &sidUse );
+ // last call should have failed and filled in allocation size
+ if ((getNameStatus = GetLastError()) != ERROR_INSUFFICIENT_BUFFER)
+ {
+ goto done;
+ }
+ userName = (wchar_t *)calloc(userNameSize, sizeof(wchar_t));
+ if (userName == NULL) {
+ getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
+ goto done;
+ }
+ domainName = (wchar_t *)calloc(domainNameSize, sizeof(wchar_t));
+ if (domainName == NULL) {
+ getNameStatus = ERROR_NOT_ENOUGH_MEMORY;
+ goto done;
+ }
+ if (!LookupAccountSid( NULL, user->User.Sid, userName, &userNameSize, domainName, &domainNameSize, &sidUse )) {
+ getNameStatus = GetLastError();
+ goto done;
+ }
+
+ getNameStatus = ERROR_SUCCESS;
+ *allocatedName = userName;
+ userName = NULL;
+done:
+ if (user != NULL) {
+ free( user );
+ user = NULL;
+ }
+ if (userName != NULL) {
+ free( userName );
+ userName = NULL;
+ }
+ if (domainName != NULL) {
+ free( domainName );
+ domainName = NULL;
+ }
+ return getNameStatus;
+}
+
+DWORD LoadUserProfileForLogon(__in HANDLE logonHandle, __out PROFILEINFO * pi)
+{
+ wchar_t *userName = NULL;
+ DWORD loadProfileStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
+
+ loadProfileStatus = GetNameFromLogonToken( logonHandle, &userName );
+ if (loadProfileStatus != ERROR_SUCCESS) {
+ goto done;
+ }
+
+ assert(pi);
+
+ ZeroMemory( pi, sizeof(*pi) );
+ pi->dwSize = sizeof(*pi);
+ pi->lpUserName = userName;
+ pi->dwFlags = PI_NOUI;
+
+ // if the profile does not exist it will be created
+ if ( !LoadUserProfile( logonHandle, pi ) ) {
+ loadProfileStatus = GetLastError();
+ goto done;
+ }
+
+ loadProfileStatus = ERROR_SUCCESS;
+done:
+ return loadProfileStatus;
+}
+
+DWORD UnloadProfileForLogon(__in HANDLE logonHandle, __in PROFILEINFO * pi)
+{
+ DWORD touchProfileStatus = ERROR_ASSERTION_FAILURE; // Failure to set status should trigger error
+
+ assert(pi);
+
+ if ( !UnloadUserProfile(logonHandle, pi->hProfile ) ) {
+ touchProfileStatus = GetLastError();
+ goto done;
+ }
+ if (pi->lpUserName != NULL) {
+ free(pi->lpUserName);
+ pi->lpUserName = NULL;
+ }
+ ZeroMemory( pi, sizeof(*pi) );
+
+ touchProfileStatus = ERROR_SUCCESS;
+done:
+ return touchProfileStatus;
+}
diff --git a/hadoop-common-project/hadoop-common/src/main/winutils/symlink.c b/hadoop-common-project/hadoop-common/src/main/winutils/symlink.c
index ea372cc06dc53..02acd4d2a40e8 100644
--- a/hadoop-common-project/hadoop-common/src/main/winutils/symlink.c
+++ b/hadoop-common-project/hadoop-common/src/main/winutils/symlink.c
@@ -77,7 +77,7 @@ int Symlink(__in int argc, __in_ecount(argc) wchar_t *argv[])
// This is just an additional step to do the privilege check by not using
// error code from CreateSymbolicLink() method.
//
- if (!EnablePrivilege(L"SeCreateSymbolicLinkPrivilege"))
+ if (EnablePrivilege(L"SeCreateSymbolicLinkPrivilege") != ERROR_SUCCESS)
{
fwprintf(stderr,
L"No privilege to create symbolic links.\n");
diff --git a/hadoop-common-project/hadoop-common/src/main/winutils/task.c b/hadoop-common-project/hadoop-common/src/main/winutils/task.c
index 19bda96a1e6ed..783f162322bd7 100644
--- a/hadoop-common-project/hadoop-common/src/main/winutils/task.c
+++ b/hadoop-common-project/hadoop-common/src/main/winutils/task.c
@@ -18,6 +18,7 @@
#include "winutils.h"
#include <errno.h>
#include <psapi.h>
+#include <malloc.h>
#define PSAPI_VERSION 1
#pragma comment(lib, "psapi.lib")
@@ -28,12 +29,18 @@
// process exits with 128 + signal. For SIGKILL, this would be 128 + 9 = 137.
#define KILLED_PROCESS_EXIT_CODE 137
+// Name for tracking this logon process when registering with LSA
+static const char *LOGON_PROCESS_NAME="Hadoop Container Executor";
+// Name for token source, must be less or eq to TOKEN_SOURCE_LENGTH (currently 8) chars
+static const char *TOKEN_SOURCE_NAME = "HadoopEx";
+
// List of different task related command line options supported by
// winutils.
typedef enum TaskCommandOptionType
{
TaskInvalid,
TaskCreate,
+ TaskCreateAsUser,
TaskIsAlive,
TaskKill,
TaskProcessList
@@ -86,37 +93,53 @@ static BOOL ParseCommandLine(__in int argc,
}
}
+ if (argc >= 6) {
+ if (wcscmp(argv[1], L"createAsUser") == 0)
+ {
+ *command = TaskCreateAsUser;
+ return TRUE;
+ }
+ }
+
return FALSE;
}
//----------------------------------------------------------------------------
-// Function: createTask
+// Function: CreateTaskImpl
//
// Description:
// Creates a task via a jobobject. Outputs the
// appropriate information to stdout on success, or stderr on failure.
+// logonHandle may be NULL, in this case the current logon will be utilized for the
+// created process
//
// Returns:
// ERROR_SUCCESS: On success
// GetLastError: otherwise
-DWORD createTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
+DWORD CreateTaskImpl(__in_opt HANDLE logonHandle, __in PCWSTR jobObjName,__in PWSTR cmdLine)
{
- DWORD err = ERROR_SUCCESS;
+ DWORD dwErrorCode = ERROR_SUCCESS;
DWORD exitCode = EXIT_FAILURE;
+ DWORD currDirCnt = 0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
HANDLE jobObject = NULL;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
+ void * envBlock = NULL;
+ BOOL createProcessResult = FALSE;
+
+ wchar_t* curr_dir = NULL;
+ FILE *stream = NULL;
// Create un-inheritable job object handle and set job object to terminate
// when last handle is closed. So winutils.exe invocation has the only open
// job object handle. Exit of winutils.exe ensures termination of job object.
// Either a clean exit of winutils or crash or external termination.
jobObject = CreateJobObject(NULL, jobObjName);
- err = GetLastError();
- if(jobObject == NULL || err == ERROR_ALREADY_EXISTS)
+ dwErrorCode = GetLastError();
+ if(jobObject == NULL || dwErrorCode == ERROR_ALREADY_EXISTS)
{
- return err;
+ return dwErrorCode;
}
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(SetInformationJobObject(jobObject,
@@ -124,36 +147,102 @@ DWORD createTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
&jeli,
sizeof(jeli)) == 0)
{
- err = GetLastError();
+ dwErrorCode = GetLastError();
CloseHandle(jobObject);
- return err;
+ return dwErrorCode;
}
if(AssignProcessToJobObject(jobObject, GetCurrentProcess()) == 0)
{
- err = GetLastError();
+ dwErrorCode = GetLastError();
CloseHandle(jobObject);
- return err;
+ return dwErrorCode;
}
// the child JVM uses this env var to send the task OS process identifier
// to the TaskTracker. We pass the job object name.
if(SetEnvironmentVariable(L"JVM_PID", jobObjName) == 0)
{
- err = GetLastError();
- CloseHandle(jobObject);
- return err;
+ dwErrorCode = GetLastError();
+ // We have to explictly Terminate, passing in the error code
+ // simply closing the job would kill our own process with success exit status
+ TerminateJobObject(jobObject, dwErrorCode);
+ return dwErrorCode;
}
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
- if (CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) == 0)
- {
- err = GetLastError();
- CloseHandle(jobObject);
- return err;
+ if( logonHandle != NULL ) {
+ // create user environment for this logon
+ if(!CreateEnvironmentBlock(&envBlock,
+ logonHandle,
+ TRUE )) {
+ dwErrorCode = GetLastError();
+ // We have to explictly Terminate, passing in the error code
+ // simply closing the job would kill our own process with success exit status
+ TerminateJobObject(jobObject, dwErrorCode);
+ return dwErrorCode;
+ }
+ }
+
+ // Get the required buffer size first
+ currDirCnt = GetCurrentDirectory(0, NULL);
+ if (0 < currDirCnt) {
+ curr_dir = (wchar_t*) alloca(currDirCnt * sizeof(wchar_t));
+ assert(curr_dir);
+ currDirCnt = GetCurrentDirectory(currDirCnt, curr_dir);
+ }
+
+ if (0 == currDirCnt) {
+ dwErrorCode = GetLastError();
+ // We have to explictly Terminate, passing in the error code
+ // simply closing the job would kill our own process with success exit status
+ TerminateJobObject(jobObject, dwErrorCode);
+ return dwErrorCode;
+ }
+
+ if (logonHandle == NULL) {
+ createProcessResult = CreateProcess(
+ NULL, // ApplicationName
+ cmdLine, // command line
+ NULL, // process security attributes
+ NULL, // thread security attributes
+ TRUE, // inherit handles
+ 0, // creation flags
+ NULL, // environment
+ curr_dir, // current directory
+ &si, // startup info
+ &pi); // process info
+ }
+ else {
+ createProcessResult = CreateProcessAsUser(
+ logonHandle, // logon token handle
+ NULL, // Application handle
+ cmdLine, // command line
+ NULL, // process security attributes
+ NULL, // thread security attributes
+ FALSE, // inherit handles
+ CREATE_UNICODE_ENVIRONMENT, // creation flags
+ envBlock, // environment
+ curr_dir, // current directory
+ &si, // startup info
+ &pi); // process info
+ }
+
+ if (FALSE == createProcessResult) {
+ dwErrorCode = GetLastError();
+ if( envBlock != NULL ) {
+ DestroyEnvironmentBlock( envBlock );
+ envBlock = NULL;
+ }
+ // We have to explictly Terminate, passing in the error code
+ // simply closing the job would kill our own process with success exit status
+ TerminateJobObject(jobObject, dwErrorCode);
+
+ // This is tehnically dead code, we cannot reach this condition
+ return dwErrorCode;
}
CloseHandle(pi.hThread);
@@ -162,10 +251,15 @@ DWORD createTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
WaitForSingleObject( pi.hProcess, INFINITE );
if(GetExitCodeProcess(pi.hProcess, &exitCode) == 0)
{
- err = GetLastError();
+ dwErrorCode = GetLastError();
}
CloseHandle( pi.hProcess );
+ if( envBlock != NULL ) {
+ DestroyEnvironmentBlock( envBlock );
+ envBlock = NULL;
+ }
+
// Terminate job object so that all spawned processes are also killed.
// This is needed because once this process closes the handle to the job
// object and none of the spawned objects have the handle open (via
@@ -173,21 +267,134 @@ DWORD createTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
// program (say winutils task kill) to terminate this job object via its name.
if(TerminateJobObject(jobObject, exitCode) == 0)
{
- err = GetLastError();
+ dwErrorCode = GetLastError();
}
- // comes here only on failure or TerminateJobObject
+ // comes here only on failure of TerminateJobObject
CloseHandle(jobObject);
- if(err != ERROR_SUCCESS)
+ if(dwErrorCode != ERROR_SUCCESS)
{
- return err;
+ return dwErrorCode;
}
return exitCode;
}
//----------------------------------------------------------------------------
-// Function: isTaskAlive
+// Function: CreateTask
+//
+// Description:
+// Creates a task via a jobobject. Outputs the
+// appropriate information to stdout on success, or stderr on failure.
+//
+// Returns:
+// ERROR_SUCCESS: On success
+// GetLastError: otherwise
+DWORD CreateTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
+{
+ // call with null logon in order to create tasks utilizing the current logon
+ return CreateTaskImpl( NULL, jobObjName, cmdLine );
+}
+//----------------------------------------------------------------------------
+// Function: CreateTask
+//
+// Description:
+// Creates a task via a jobobject. Outputs the
+// appropriate information to stdout on success, or stderr on failure.
+//
+// Returns:
+// ERROR_SUCCESS: On success
+// GetLastError: otherwise
+DWORD CreateTaskAsUser(__in PCWSTR jobObjName,__in PWSTR user, __in PWSTR pidFilePath, __in PWSTR cmdLine)
+{
+ DWORD err = ERROR_SUCCESS;
+ DWORD exitCode = EXIT_FAILURE;
+ ULONG authnPkgId;
+ HANDLE lsaHandle = INVALID_HANDLE_VALUE;
+ PROFILEINFO pi;
+ BOOL profileIsLoaded = FALSE;
+ FILE* pidFile = NULL;
+
+ DWORD retLen = 0;
+ HANDLE logonHandle = NULL;
+
+ err = EnablePrivilege(SE_TCB_NAME);
+ if( err != ERROR_SUCCESS ) {
+ fwprintf(stdout, L"INFO: The user does not have SE_TCB_NAME.\n");
+ goto done;
+ }
+ err = EnablePrivilege(SE_ASSIGNPRIMARYTOKEN_NAME);
+ if( err != ERROR_SUCCESS ) {
+ fwprintf(stdout, L"INFO: The user does not have SE_ASSIGNPRIMARYTOKEN_NAME.\n");
+ goto done;
+ }
+ err = EnablePrivilege(SE_INCREASE_QUOTA_NAME);
+ if( err != ERROR_SUCCESS ) {
+ fwprintf(stdout, L"INFO: The user does not have SE_INCREASE_QUOTA_NAME.\n");
+ goto done;
+ }
+ err = EnablePrivilege(SE_RESTORE_NAME);
+ if( err != ERROR_SUCCESS ) {
+ fwprintf(stdout, L"INFO: The user does not have SE_RESTORE_NAME.\n");
+ goto done;
+ }
+
+ err = RegisterWithLsa(LOGON_PROCESS_NAME ,&lsaHandle);
+ if( err != ERROR_SUCCESS ) goto done;
+
+ err = LookupKerberosAuthenticationPackageId( lsaHandle, &authnPkgId );
+ if( err != ERROR_SUCCESS ) goto done;
+
+ err = CreateLogonForUser(lsaHandle,
+ LOGON_PROCESS_NAME,
+ TOKEN_SOURCE_NAME,
+ authnPkgId,
+ user,
+ &logonHandle);
+ if( err != ERROR_SUCCESS ) goto done;
+
+ err = LoadUserProfileForLogon(logonHandle, &pi);
+ if( err != ERROR_SUCCESS ) goto done;
+ profileIsLoaded = TRUE;
+
+ // Create the PID file
+
+ if (!(pidFile = _wfopen(pidFilePath, "w"))) {
+ err = GetLastError();
+ goto done;
+ }
+
+ if (0 > fprintf_s(pidFile, "%ls", jobObjName)) {
+ err = GetLastError();
+ }
+
+ fclose(pidFile);
+
+ if (err != ERROR_SUCCESS) {
+ goto done;
+ }
+
+ err = CreateTaskImpl(logonHandle, jobObjName, cmdLine);
+
+done:
+ if( profileIsLoaded ) {
+ UnloadProfileForLogon( logonHandle, &pi );
+ profileIsLoaded = FALSE;
+ }
+ if( logonHandle != NULL ) {
+ CloseHandle(logonHandle);
+ }
+
+ if (INVALID_HANDLE_VALUE != lsaHandle) {
+ UnregisterWithLsa(lsaHandle);
+ }
+
+ return err;
+}
+
+
+//----------------------------------------------------------------------------
+// Function: IsTaskAlive
//
// Description:
// Checks if a task is alive via a jobobject. Outputs the
@@ -196,7 +403,7 @@ DWORD createTask(__in PCWSTR jobObjName,__in PWSTR cmdLine)
// Returns:
// ERROR_SUCCESS: On success
// GetLastError: otherwise
-DWORD isTaskAlive(const WCHAR* jobObjName, int* isAlive, int* procsInJob)
+DWORD IsTaskAlive(const WCHAR* jobObjName, int* isAlive, int* procsInJob)
{
PJOBOBJECT_BASIC_PROCESS_ID_LIST procList;
HANDLE jobObject = NULL;
@@ -247,7 +454,7 @@ DWORD isTaskAlive(const WCHAR* jobObjName, int* isAlive, int* procsInJob)
}
//----------------------------------------------------------------------------
-// Function: killTask
+// Function: KillTask
//
// Description:
// Kills a task via a jobobject. Outputs the
@@ -256,7 +463,7 @@ DWORD isTaskAlive(const WCHAR* jobObjName, int* isAlive, int* procsInJob)
// Returns:
// ERROR_SUCCESS: On success
// GetLastError: otherwise
-DWORD killTask(PCWSTR jobObjName)
+DWORD KillTask(PCWSTR jobObjName)
{
HANDLE jobObject = OpenJobObject(JOB_OBJECT_TERMINATE, FALSE, jobObjName);
if(jobObject == NULL)
@@ -280,7 +487,7 @@ DWORD killTask(PCWSTR jobObjName)
}
//----------------------------------------------------------------------------
-// Function: printTaskProcessList
+// Function: PrintTaskProcessList
//
// Description:
// Prints resource usage of all processes in the task jobobject
@@ -288,7 +495,7 @@ DWORD killTask(PCWSTR jobObjName)
// Returns:
// ERROR_SUCCESS: On success
// GetLastError: otherwise
-DWORD printTaskProcessList(const WCHAR* jobObjName)
+DWORD PrintTaskProcessList(const WCHAR* jobObjName)
{
DWORD i;
PJOBOBJECT_BASIC_PROCESS_ID_LIST procList;
@@ -372,6 +579,21 @@ int Task(__in int argc, __in_ecount(argc) wchar_t *argv[])
{
DWORD dwErrorCode = ERROR_SUCCESS;
TaskCommandOption command = TaskInvalid;
+ wchar_t* cmdLine = NULL;
+ wchar_t buffer[16*1024] = L""; // 32K max command line
+ size_t charCountBufferLeft = sizeof
(buffer)/sizeof(wchar_t);
+ int crtArgIndex = 0;
+ size_t argLen = 0;
+ size_t wscatErr = 0;
+ wchar_t* insertHere = NULL;
+
+ enum {
+ ARGC_JOBOBJECTNAME = 2,
+ ARGC_USERNAME,
+ ARGC_PIDFILE,
+ ARGC_COMMAND,
+ ARGC_COMMAND_ARGS
+ };
if (!ParseCommandLine(argc, argv, &command)) {
dwErrorCode = ERROR_INVALID_COMMAND_LINE;
@@ -385,10 +607,57 @@ int Task(__in int argc, __in_ecount(argc) wchar_t *argv[])
{
// Create the task jobobject
//
- dwErrorCode = createTask(argv[2], argv[3]);
+ dwErrorCode = CreateTask(argv[2], argv[3]);
+ if (dwErrorCode != ERROR_SUCCESS)
+ {
+ ReportErrorCode(L"CreateTask", dwErrorCode);
+ goto TaskExit;
+ }
+ } else if (command == TaskCreateAsUser)
+ {
+ // Create the task jobobject as a domain user
+ // createAsUser accepts an open list of arguments. All arguments after the command are
+ // to be passed as argumrnts to the command itself.Here we're concatenating all
+ // arguments after the command into a single arg entry.
+ //
+ cmdLine = argv[ARGC_COMMAND];
+ if (argc > ARGC_COMMAND_ARGS) {
+ crtArgIndex = ARGC_COMMAND;
+ insertHere = buffer;
+ while (crtArgIndex < argc) {
+ argLen = wcslen(argv[crtArgIndex]);
+ wscatErr = wcscat_s(insertHere, charCountBufferLeft, argv[crtArgIndex]);
+ switch (wscatErr) {
+ case 0:
+ // 0 means success;
+ break;
+ case EINVAL:
+ dwErrorCode = ERROR_INVALID_PARAMETER;
+ goto TaskExit;
+ case ERANGE:
+ dwErrorCode = ERROR_INSUFFICIENT_BUFFER;
+ goto TaskExit;
+ default:
+ // This case is not MSDN documented.
+ dwErrorCode = ERROR_GEN_FAILURE;
+ goto TaskExit;
+ }
+ insertHere += argLen;
+ charCountBufferLeft -= argLen;
+ insertHere[0] = L' ';
+ insertHere += 1;
+ charCountBufferLeft -= 1;
+ insertHere[0] = 0;
+ ++crtArgIndex;
+ }
+ cmdLine = buffer;
+ }
+
+ dwErrorCode = CreateTaskAsUser(
+ argv[ARGC_JOBOBJECTNAME], argv[ARGC_USERNAME], argv[ARGC_PIDFILE], cmdLine);
if (dwErrorCode != ERROR_SUCCESS)
{
- ReportErrorCode(L"createTask", dwErrorCode);
+ ReportErrorCode(L"CreateTaskAsUser", dwErrorCode);
goto TaskExit;
}
} else if (command == TaskIsAlive)
@@ -397,10 +666,10 @@ int Task(__in int argc, __in_ecount(argc) wchar_t *argv[])
//
int isAlive;
int numProcs;
- dwErrorCode = isTaskAlive(argv[2], &isAlive, &numProcs);
+ dwErrorCode = IsTaskAlive(argv[2], &isAlive, &numProcs);
if (dwErrorCode != ERROR_SUCCESS)
{
- ReportErrorCode(L"isTaskAlive", dwErrorCode);
+ ReportErrorCode(L"IsTaskAlive", dwErrorCode);
goto TaskExit;
}
@@ -412,27 +681,27 @@ int Task(__in int argc, __in_ecount(argc) wchar_t *argv[])
else
{
dwErrorCode = ERROR_TASK_NOT_ALIVE;
- ReportErrorCode(L"isTaskAlive returned false", dwErrorCode);
+ ReportErrorCode(L"IsTaskAlive returned false", dwErrorCode);
goto TaskExit;
}
} else if (command == TaskKill)
{
// Check if task jobobject
//
- dwErrorCode = killTask(argv[2]);
+ dwErrorCode = KillTask(argv[2]);
if (dwErrorCode != ERROR_SUCCESS)
{
- ReportErrorCode(L"killTask", dwErrorCode);
+ ReportErrorCode(L"KillTask", dwErrorCode);
goto TaskExit;
}
} else if (command == TaskProcessList)
{
// Check if task jobobject
//
- dwErrorCode = printTaskProcessList(argv[2]);
+ dwErrorCode = PrintTaskProcessList(argv[2]);
if (dwErrorCode != ERROR_SUCCESS)
{
- ReportErrorCode(L"printTaskProcessList", dwErrorCode);
+ ReportErrorCode(L"PrintTaskProcessList", dwErrorCode);
goto TaskExit;
}
} else
@@ -453,10 +722,12 @@ void TaskUsage()
// ProcessTree.isSetsidSupported()
fwprintf(stdout, L"\
Usage: task create [TASKNAME] [COMMAND_LINE] |\n\
+ task createAsUser [TASKNAME] [USERNAME] [PIDFILE] [COMMAND_LINE] |\n\
task isAlive [TASKNAME] |\n\
task kill [TASKNAME]\n\
task processList [TASKNAME]\n\
Creates a new task jobobject with taskname\n\
+ Creates a new task jobobject with taskname as the user provided\n\
Checks if task jobobject is alive\n\
Kills task jobobject\n\
Prints to stdout a list of processes in the task\n\
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java
index 588b21761ca81..953039d937a07 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestWinUtils.java
@@ -20,10 +20,12 @@
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
+import static org.junit.matchers.JUnitMatchers.containsString;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
@@ -33,7 +35,7 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assume.*;
+
import static org.hamcrest.CoreMatchers.*;
/**
@@ -521,4 +523,26 @@ public void testReadLink() throws IOException {
assertThat(ece.getExitCode(), is(1));
}
}
+
+ @SuppressWarnings("deprecation")
+ @Test(timeout=10000)
+ public void testTaskCreate() throws IOException {
+ File batch = new File(TEST_DIR, "testTaskCreate.cmd");
+ File proof = new File(TEST_DIR, "testTaskCreate.out");
+ FileWriter fw = new FileWriter(batch);
+ String testNumber = String.format("%f", Math.random());
+ fw.write(String.format("echo %s > \"%s\"", testNumber, proof.getAbsolutePath()));
+ fw.close();
+
+ assertFalse(proof.exists());
+
+ Shell.execCommand(Shell.WINUTILS, "task", "create", "testTaskCreate" + testNumber,
+ batch.getAbsolutePath());
+
+ assertTrue(proof.exists());
+
+ String outNumber = FileUtils.readFileToString(proof);
+
+ assertThat(outNumber, containsString(testNumber));
+ }
}
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 47a7e2cb45b17..e8db12ddc5e57 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -88,6 +88,9 @@ Release 2.6.0 - UNRELEASED
YARN-2581. Passed LogAggregationContext to NM via ContainerTokenIdentifier.
(Xuan Gong via zjshen)
+ YARN-1063. Augmented Hadoop common winutils to have the ability to create
+ containers as domain users. (Remus Rusanu via vinodkv)
+
IMPROVEMENTS
YARN-2242. Improve exception information on AM launch crashes. (Li Lu
|
d7d4a1410bffb969850bb17ba0d48b02ad542136
|
camel
|
CAMEL-1370 caching the StreamSource by caching- the inputStream or reader--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@746872 13f79535-47bb-0310-9956-ffa450edef68-
|
p
|
https://github.com/apache/camel
|
diff --git a/camel-core/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java b/camel-core/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
index a78903e66b890..c081193c4489d 100644
--- a/camel-core/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
+++ b/camel-core/src/main/java/org/apache/camel/converter/stream/StreamCacheConverter.java
@@ -45,18 +45,18 @@ public class StreamCacheConverter {
private XmlConverter converter = new XmlConverter();
@Converter
- public StreamCache convertToStreamCache(StreamSource source) throws TransformerException {
- return new SourceCache(converter.toString(source));
+ public StreamCache convertToStreamCache(StreamSource source) throws IOException {
+ return new StreamSourceCache(source);
}
@Converter
- public StreamCache convertToStreamCache(StringSource source) throws TransformerException {
+ public StreamCache convertToStreamCache(StringSource source) {
//no need to do stream caching for a StringSource
return null;
}
@Converter
- public StreamCache convertToStreamCache(BytesSource source) throws TransformerException {
+ public StreamCache convertToStreamCache(BytesSource source) {
//no need to do stream caching for a BytesSource
return null;
}
@@ -95,6 +95,35 @@ public void reset() {
}
}
+
+ /*
+ * {@link StreamCache} implementation for Cache the StreamSource {@link StreamSource}s
+ */
+ private class StreamSourceCache extends StreamSource implements StreamCache {
+ InputStreamCache inputStreamCache;
+ ReaderCache readCache;
+
+ public StreamSourceCache(StreamSource source) throws IOException {
+ if (source.getInputStream() != null) {
+ inputStreamCache = new InputStreamCache(IOConverter.toBytes(source.getInputStream()));
+ setInputStream(inputStreamCache);
+ setSystemId(source.getSystemId());
+ }
+ if (source.getReader() != null) {
+ readCache = new ReaderCache(IOConverter.toString(source.getReader()));
+ setReader(readCache);
+ }
+ }
+ public void reset() {
+ if (inputStreamCache != null) {
+ inputStreamCache.reset();
+ }
+ if (readCache != null) {
+ readCache.reset();
+ }
+ }
+
+ }
private class InputStreamCache extends ByteArrayInputStream implements StreamCache {
diff --git a/camel-core/src/main/java/org/apache/camel/processor/interceptor/StreamCaching.java b/camel-core/src/main/java/org/apache/camel/processor/interceptor/StreamCaching.java
index a98caa3e9c490..dc15a9ea9f748 100644
--- a/camel-core/src/main/java/org/apache/camel/processor/interceptor/StreamCaching.java
+++ b/camel-core/src/main/java/org/apache/camel/processor/interceptor/StreamCaching.java
@@ -54,4 +54,18 @@ public static void enable(RouteContext context) {
}
context.addInterceptStrategy(new StreamCaching());
}
+
+ /**
+ * Enable stream caching for a RouteContext
+ *
+ * @param context the route context
+ */
+ public static void disable(RouteContext context) {
+ for (InterceptStrategy strategy : context.getInterceptStrategies()) {
+ if (strategy instanceof StreamCaching) {
+ context.getInterceptStrategies().remove(strategy);
+ return;
+ }
+ }
+ }
}
diff --git a/camel-core/src/test/java/org/apache/camel/converter/stream/StreamCacheConverterTest.java b/camel-core/src/test/java/org/apache/camel/converter/stream/StreamCacheConverterTest.java
index 54dca0b1cabb4..364238d06e95b 100644
--- a/camel-core/src/test/java/org/apache/camel/converter/stream/StreamCacheConverterTest.java
+++ b/camel-core/src/test/java/org/apache/camel/converter/stream/StreamCacheConverterTest.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.io.InputStream;
+import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;
@@ -42,13 +43,14 @@ protected void setUp() throws Exception {
this.converter = new StreamCacheConverter();
}
- public void testConvertToStreamCacheStreamSource() throws TransformerException, FileNotFoundException {
+ public void testConvertToStreamCacheStreamSource() throws IOException, FileNotFoundException, TransformerException {
StreamSource source = new StreamSource(getTestFileStream());
- StreamSource cache = (StreamSource) converter.convertToStreamCache(source);
+ StreamCache cache = converter.convertToStreamCache(source);
//assert re-readability of the cached StreamSource
XmlConverter converter = new XmlConverter();
- assertNotNull(converter.toString(cache));
- assertNotNull(converter.toString(cache));
+ assertNotNull(converter.toString((Source)cache));
+ cache.reset();
+ assertNotNull(converter.toString((Source)cache));
}
public void testConvertToStreamCacheInputStream() throws IOException {
diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/StreamCachingInterceptorTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/StreamCachingInterceptorTest.java
index b610804121470..e6bc30b3b3446 100644
--- a/camel-core/src/test/java/org/apache/camel/processor/interceptor/StreamCachingInterceptorTest.java
+++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/StreamCachingInterceptorTest.java
@@ -81,7 +81,7 @@ public void testConvertStreamSourceWithRouteOnlyStreamCaching() throws Exception
template.sendBody("direct:b", message);
assertMockEndpointsSatisfied();
- assertTrue(b.assertExchangeReceived(0).getIn().getBody() instanceof StreamCache);
+ assertTrue(b.assertExchangeReceived(0).getIn().getBody() instanceof StreamCache);
assertEquals(b.assertExchangeReceived(0).getIn().getBody(String.class), MESSAGE);
}
|
b923c291b474c246afa9f37ae5d9f6bdbbfef9d2
|
hadoop
|
YARN-2608. FairScheduler: Potential deadlocks in- loading alloc files and clock access. (Wei Yan via kasha)--(cherry picked from commit c9811af09a3d3f9f2f1b86fc9d6f2763d3225e44)-
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 421fac6cd831d..2022204d9fc9a 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -420,6 +420,9 @@ Release 2.6.0 - UNRELEASED
YARN-2523. ResourceManager UI showing negative value for "Decommissioned
Nodes" field (Rohith via jlowe)
+ YARN-2608. FairScheduler: Potential deadlocks in loading alloc files and
+ clock access. (Wei Yan via kasha)
+
Release 2.5.1 - 2014-09-05
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
index 296d8844373d5..d6339813487ed 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
@@ -117,7 +117,7 @@ public class FairScheduler extends
private Resource incrAllocation;
private QueueManager queueMgr;
- private Clock clock;
+ private volatile Clock clock;
private boolean usePortForNodeName;
private static final Log LOG = LogFactory.getLog(FairScheduler.class);
@@ -555,11 +555,12 @@ public synchronized int getContinuousSchedulingSleepMs() {
return continuousSchedulingSleepMs;
}
- public synchronized Clock getClock() {
+ public Clock getClock() {
return clock;
}
- protected synchronized void setClock(Clock clock) {
+ @VisibleForTesting
+ void setClock(Clock clock) {
this.clock = clock;
}
@@ -1204,64 +1205,65 @@ public synchronized void setRMContext(RMContext rmContext) {
this.rmContext = rmContext;
}
- private synchronized void initScheduler(Configuration conf)
- throws IOException {
- this.conf = new FairSchedulerConfiguration(conf);
- validateConf(this.conf);
- minimumAllocation = this.conf.getMinimumAllocation();
- maximumAllocation = this.conf.getMaximumAllocation();
- incrAllocation = this.conf.getIncrementAllocation();
- continuousSchedulingEnabled = this.conf.isContinuousSchedulingEnabled();
- continuousSchedulingSleepMs =
- this.conf.getContinuousSchedulingSleepMs();
- nodeLocalityThreshold = this.conf.getLocalityThresholdNode();
- rackLocalityThreshold = this.conf.getLocalityThresholdRack();
- nodeLocalityDelayMs = this.conf.getLocalityDelayNodeMs();
- rackLocalityDelayMs = this.conf.getLocalityDelayRackMs();
- preemptionEnabled = this.conf.getPreemptionEnabled();
- preemptionUtilizationThreshold =
- this.conf.getPreemptionUtilizationThreshold();
- assignMultiple = this.conf.getAssignMultiple();
- maxAssign = this.conf.getMaxAssign();
- sizeBasedWeight = this.conf.getSizeBasedWeight();
- preemptionInterval = this.conf.getPreemptionInterval();
- waitTimeBeforeKill = this.conf.getWaitTimeBeforeKill();
- usePortForNodeName = this.conf.getUsePortForNodeName();
-
- updateInterval = this.conf.getUpdateInterval();
- if (updateInterval < 0) {
- updateInterval = FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS;
- LOG.warn(FairSchedulerConfiguration.UPDATE_INTERVAL_MS
- + " is invalid, so using default value " +
- + FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS
- + " ms instead");
- }
-
- rootMetrics = FSQueueMetrics.forQueue("root", null, true, conf);
- fsOpDurations = FSOpDurations.getInstance(true);
-
- // This stores per-application scheduling information
- this.applications = new ConcurrentHashMap<
- ApplicationId, SchedulerApplication<FSAppAttempt>>();
- this.eventLog = new FairSchedulerEventLog();
- eventLog.init(this.conf);
-
- allocConf = new AllocationConfiguration(conf);
- try {
- queueMgr.initialize(conf);
- } catch (Exception e) {
- throw new IOException("Failed to start FairScheduler", e);
- }
+ private void initScheduler(Configuration conf) throws IOException {
+ synchronized (this) {
+ this.conf = new FairSchedulerConfiguration(conf);
+ validateConf(this.conf);
+ minimumAllocation = this.conf.getMinimumAllocation();
+ maximumAllocation = this.conf.getMaximumAllocation();
+ incrAllocation = this.conf.getIncrementAllocation();
+ continuousSchedulingEnabled = this.conf.isContinuousSchedulingEnabled();
+ continuousSchedulingSleepMs =
+ this.conf.getContinuousSchedulingSleepMs();
+ nodeLocalityThreshold = this.conf.getLocalityThresholdNode();
+ rackLocalityThreshold = this.conf.getLocalityThresholdRack();
+ nodeLocalityDelayMs = this.conf.getLocalityDelayNodeMs();
+ rackLocalityDelayMs = this.conf.getLocalityDelayRackMs();
+ preemptionEnabled = this.conf.getPreemptionEnabled();
+ preemptionUtilizationThreshold =
+ this.conf.getPreemptionUtilizationThreshold();
+ assignMultiple = this.conf.getAssignMultiple();
+ maxAssign = this.conf.getMaxAssign();
+ sizeBasedWeight = this.conf.getSizeBasedWeight();
+ preemptionInterval = this.conf.getPreemptionInterval();
+ waitTimeBeforeKill = this.conf.getWaitTimeBeforeKill();
+ usePortForNodeName = this.conf.getUsePortForNodeName();
+
+ updateInterval = this.conf.getUpdateInterval();
+ if (updateInterval < 0) {
+ updateInterval = FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS;
+ LOG.warn(FairSchedulerConfiguration.UPDATE_INTERVAL_MS
+ + " is invalid, so using default value " +
+ +FairSchedulerConfiguration.DEFAULT_UPDATE_INTERVAL_MS
+ + " ms instead");
+ }
- updateThread = new UpdateThread();
- updateThread.setName("FairSchedulerUpdateThread");
- updateThread.setDaemon(true);
+ rootMetrics = FSQueueMetrics.forQueue("root", null, true, conf);
+ fsOpDurations = FSOpDurations.getInstance(true);
- if (continuousSchedulingEnabled) {
- // start continuous scheduling thread
- schedulingThread = new ContinuousSchedulingThread();
- schedulingThread.setName("FairSchedulerContinuousScheduling");
- schedulingThread.setDaemon(true);
+ // This stores per-application scheduling information
+ this.applications = new ConcurrentHashMap<
+ ApplicationId, SchedulerApplication<FSAppAttempt>>();
+ this.eventLog = new FairSchedulerEventLog();
+ eventLog.init(this.conf);
+
+ allocConf = new AllocationConfiguration(conf);
+ try {
+ queueMgr.initialize(conf);
+ } catch (Exception e) {
+ throw new IOException("Failed to start FairScheduler", e);
+ }
+
+ updateThread = new UpdateThread();
+ updateThread.setName("FairSchedulerUpdateThread");
+ updateThread.setDaemon(true);
+
+ if (continuousSchedulingEnabled) {
+ // start continuous scheduling thread
+ schedulingThread = new ContinuousSchedulingThread();
+ schedulingThread.setName("FairSchedulerContinuousScheduling");
+ schedulingThread.setDaemon(true);
+ }
}
allocsLoader.init(conf);
@@ -1321,7 +1323,7 @@ public void serviceStop() throws Exception {
}
@Override
- public synchronized void reinitialize(Configuration conf, RMContext rmContext)
+ public void reinitialize(Configuration conf, RMContext rmContext)
throws IOException {
try {
allocsLoader.reloadAllocations();
|
fa34669d5ad46f7fedab76c0092a8a3491a9982e
|
Vala
|
libsoup-2.4: Make Soup.Session.queue_message callback nullable
Fixes bug 612050.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/libsoup-2.4.vapi b/vapi/libsoup-2.4.vapi
index ed282cad9a..55ef7e543d 100644
--- a/vapi/libsoup-2.4.vapi
+++ b/vapi/libsoup-2.4.vapi
@@ -375,7 +375,7 @@ namespace Soup {
public virtual void cancel_message (Soup.Message msg, uint status_code);
public unowned GLib.MainContext get_async_context ();
public void pause_message (Soup.Message msg);
- public virtual void queue_message (owned Soup.Message msg, Soup.SessionCallback callback);
+ public virtual void queue_message (owned Soup.Message msg, Soup.SessionCallback? callback);
public void remove_feature (Soup.SessionFeature feature);
public virtual void requeue_message (Soup.Message msg);
public virtual uint send_message (Soup.Message msg);
diff --git a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
index a9fc405c6c..8bc6707f0b 100644
--- a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
+++ b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata
@@ -30,6 +30,7 @@ SoupSession::add_feature has_emitter="1"
SoupSession::add_feature_by_type has_emitter="1"
SoupSession::remove_feature_by_type has_emitter="1"
soup_session_queue_message.msg transfer_ownership="1"
+soup_session_queue_message.callback nullable="1"
soup_session_async_new_with_options ellipsis="1"
soup_session_sync_new_with_options ellipsis="1"
soup_uri_decode transfer_ownership="1"
|
0c6b38b0b5749057d6e9dcb5f7917f27e6542fc3
|
spring-framework
|
DataSourceUtils lets timeout exceptions through- even for setReadOnly calls (revised; SPR-7226)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java
index 07c6efaf3494..89ecf0bc66e3 100644
--- a/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java
+++ b/org.springframework.jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
-
import javax.sql.DataSource;
import junit.framework.TestCase;
@@ -463,6 +462,8 @@ public void testParticipatingTransactionWithIncompatibleReadOnly() throws Except
conControl.setReturnValue(false, 1);
con.rollback();
conControl.setVoidCallable(1);
+ con.setReadOnly(true);
+ conControl.setThrowable(new SQLException("read-only not supported"), 1);
con.isReadOnly();
conControl.setReturnValue(false, 1);
con.close();
|
9d8ae0a8feb951f799df29fc9f10ba07f4b0b255
|
intellij-community
|
additional null check--
|
c
|
https://github.com/JetBrains/intellij-community
|
diff --git a/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java b/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
index 56c4f69599974..762ba6c554002 100644
--- a/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
+++ b/platform/platform-api/src/com/intellij/execution/configurations/ParametersList.java
@@ -335,7 +335,10 @@ private Map<String, String> getMacroMap() {
if (application != null) {
final PathMacros pathMacros = PathMacros.getInstance();
for (String name : pathMacros.getUserMacroNames()) {
- myMacroMap.put("${" + name + "}", pathMacros.getValue(name));
+ final String value = pathMacros.getValue(name);
+ if (value != null) {
+ myMacroMap.put("${" + name + "}", value);
+ }
}
final Map<String, String> env = EnvironmentUtil.getEnviromentProperties();
for (String name : env.keySet()) {
|
1eee950ac167c1bc02918819c84e6cccb9eebb5f
|
orientdb
|
OPLA: supported invocation of Java static methods--
|
a
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java
index 7b9f1d127d6..817898076d4 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/processor/block/OFunctionBlock.java
@@ -15,6 +15,7 @@
*/
package com.orientechnologies.orient.core.processor.block;
+import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
@@ -51,12 +52,44 @@ public Object processBlock(OComposableProcessor iManager, final OCommandContext
args = null;
final OFunction f = ODatabaseRecordThreadLocal.INSTANCE.get().getMetadata().getFunctionLibrary().getFunction(function);
- if (f == null)
- throw new OProcessException("Function '" + function + "' was not found");
+ if (f != null) {
+ debug(iContext, "Calling: " + function + "(" + Arrays.toString(args) + ")...");
+ return f.executeInContext(iContext, args);
+ }
- debug(iContext, "Calling: " + function + "(" + Arrays.toString(args) + ")...");
+ int lastDot = function.lastIndexOf('.');
+ if (lastDot > -1) {
+ final String clsName = function.substring(0, lastDot);
+ final String methodName = function.substring(lastDot + 1);
+ Class<?> cls = null;
+ try {
+ cls = Class.forName(clsName);
- return f.executeInContext(iContext, args);
+ Class<?>[] argTypes = new Class<?>[args.length];
+ for (int i = 0; i < args.length; ++i)
+ argTypes[i] = args[i].getClass();
+
+ Method m = cls.getMethod(methodName, argTypes);
+ return m.invoke(null, args);
+ } catch (NoSuchMethodException e) {
+
+ for (Method m : cls.getMethods()) {
+ if (m.getName().equals(methodName) && m.getParameterTypes().length == args.length) {
+ try {
+ return m.invoke(null, args);
+ } catch (Exception e1) {
+ e1.printStackTrace();
+ throw new OProcessException("Error on call function '" + function + "'", e);
+ }
+ }
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ throw new OProcessException("Function '" + function + "' was not found");
}
@Override
|
7ff073ed301e732ae2805481d63854fa0be93180
|
arquillian$arquillian-graphene
|
Add support for multiple @InitialPage with parallel browsers
Fixes ARQGRA-478
|
a
|
https://github.com/arquillian/arquillian-graphene
|
diff --git a/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java b/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
index b5b857c8f..95985288f 100644
--- a/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
+++ b/ftest/src/test/java/org/jboss/arquillian/graphene/ftest/enricher/TestPageObjectsLocation.java
@@ -42,6 +42,7 @@
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
+import qualifier.Browser2;
import qualifier.Browser3;
@RunWith(Arquillian.class)
@@ -51,6 +52,10 @@ public class TestPageObjectsLocation {
@Drone
private WebDriver browser;
+ @Drone
+ @Browser2
+ private WebDriver browser2;
+
@Drone
@Browser3
private WebDriver browser3;
@@ -111,6 +116,21 @@ public void testInitialPageCustomBrowser(@Browser3 @InitialPage MyPageObject2 ob
checkMyPageObject2(obj);
}
+ @Test
+ public void testMultipleInitialPagesWithCustomBrowsers(
+ @Browser2 @InitialPage MyPageObject2 page1,
+ @Browser3 @InitialPage MyPageObject2 page2) {
+ browser.get(contextRoot.toExternalForm());
+ checkMyPageObject2(page1);
+ checkMyPageObject2(page2);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testMultipleInitialPagesGoingToSameBrowser(
+ @Browser2 @InitialPage MyPageObject2 page1,
+ @Browser2 @InitialPage MyPageObject2 page2) {
+ }
+
@Test
public void testGotoPageCustomBrowser() {
MyPageObject2 page2 = Graphene.goTo(MyPageObject2.class, Browser3.class);
diff --git a/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java b/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
index dbc6b30f9..3ae86930b 100644
--- a/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
+++ b/impl/src/main/java/org/jboss/arquillian/graphene/location/LocationEnricher.java
@@ -23,7 +23,11 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
+import java.util.ArrayList;
import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
import org.jboss.arquillian.core.api.Injector;
import org.jboss.arquillian.core.api.Instance;
@@ -60,17 +64,24 @@ public void enrich(Object testCase) {
@Override
public Object[] resolve(Method method) {
- int indexOfInitialPage = getIndexOfParameterWithAnnotation(InitialPage.class, method);
- if (indexOfInitialPage == -1) {
+ List<Integer> indicesOfInitialPage = getIndexOfParameterWithAnnotation(InitialPage.class, method);
+ if (indicesOfInitialPage.isEmpty()) {
return new Object[method.getParameterTypes().length];
}
- Class<?> qualifier = ReflectionHelper.getQualifier(method.getParameterAnnotations()[indexOfInitialPage]);
- Class<?>[] parameterTypes = method.getParameterTypes();
- Object[] result = new Object[method.getParameterTypes().length];
- result[indexOfInitialPage] = goTo(parameterTypes[indexOfInitialPage], qualifier);
+ Object[] results = new Object[method.getParameterTypes().length];
+ Set<Class<?>> usedQualifiers = new HashSet<Class<?>>();
+ for (Integer indexOfInitialPage : indicesOfInitialPage) {
+ Class<?> qualifier = ReflectionHelper.getQualifier(method.getParameterAnnotations()[indexOfInitialPage]);
+ if (usedQualifiers.contains(qualifier)) {
+ throw new IllegalArgumentException("There are multiple @InitialPage parameters using the same qualifier");
+ }
+ usedQualifiers.add(qualifier);
+ Class<?>[] parameterTypes = method.getParameterTypes();
+ results[indexOfInitialPage] = goTo(parameterTypes[indexOfInitialPage], qualifier);
+ }
- return result;
+ return results;
}
public <T> T goTo(Class<T> pageObject, Class<?> browserQualifier) {
@@ -132,28 +143,18 @@ private void handleLocationOf(Class<?> pageObjectClass, WebDriver browser) {
* @param method
* @return
*/
- private int getIndexOfParameterWithAnnotation(Class<? extends Annotation> annotation, Method method) {
+ private List<Integer> getIndexOfParameterWithAnnotation(Class<? extends Annotation> annotation, Method method) {
Annotation[][] annotationsOfAllParameters = method.getParameterAnnotations();
- int result = 0;
- boolean founded = false;
- for (; result < annotationsOfAllParameters.length; result++) {
- for (int j = 0; j < annotationsOfAllParameters[result].length; j++) {
- if (annotationsOfAllParameters[result][j].annotationType().equals(annotation)) {
- founded = true;
- break;
+ List<Integer> results = new ArrayList<Integer>();
+ for (int i = 0; i < annotationsOfAllParameters.length; i++) {
+ for (int j = 0; j < annotationsOfAllParameters[i].length; j++) {
+ if (annotationsOfAllParameters[i][j].annotationType().equals(annotation)) {
+ results.add(i);
}
}
- if (founded) {
- break;
- }
}
- if (!founded) {
- // the method has no parameters with Location annotation
- return -1;
- }
-
- return result;
+ return results;
}
private LocationDecider resolveDecider(Collection<LocationDecider> deciders, Class<?> scheme) {
|
7d6c8991403107e6cf9d967466ead87ef58f3fbf
|
drools
|
JBRULES-3170 Compiler erroneously resolves the- package of declared classes with the same name as basic classes--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
index 5a11f46abc0..12461d4c24b 100644
--- a/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
+++ b/drools-compiler/src/main/java/org/drools/compiler/PackageBuilder.java
@@ -1467,7 +1467,22 @@ private void processTypeDeclarations(final PackageDescr packageDescr) {
PackageRegistry pkgRegistry = null;
for ( TypeDeclarationDescr typeDescr : packageDescr.getTypeDeclarations() ) {
- int dotPos = typeDescr.getTypeName().lastIndexOf( '.' );
+
+ if ( isEmpty( typeDescr.getNamespace() ) ) {
+ for ( ImportDescr id : packageDescr.getImports() ) {
+ String imp = id.getTarget();
+ if ( imp.endsWith( typeDescr.getTypeName() ) ) {
+ typeDescr.setNamespace( imp.substring( 0,
+ imp.lastIndexOf( '.' ) ) );
+ }
+ }
+ }
+ String qName = typeDescr.getTypeName();
+ if ( typeDescr.getNamespace() != null ) {
+ qName = typeDescr.getNamespace() + "." + qName;
+ }
+
+ int dotPos = qName.lastIndexOf( '.' );
if ( dotPos >= 0 ) {
// see if this overwrites an existing bean, which also could be a nested class.
Class cls = null;
@@ -1478,7 +1493,7 @@ private void processTypeDeclarations(final PackageDescr packageDescr) {
} catch ( ClassNotFoundException e ) {
}
- String qualifiedClass = typeDescr.getTypeName();
+ String qualifiedClass = qName;
int lastIndex;
while ( cls == null && (lastIndex = qualifiedClass.lastIndexOf( '.' )) != -1 ) {
try {
@@ -1499,34 +1514,15 @@ private void processTypeDeclarations(final PackageDescr packageDescr) {
dotPos = cls.getName().lastIndexOf( '.' ); // reget dotPos, incase there were nested classes
typeDescr.setTypeName( cls.getName().substring( dotPos + 1 ) );
} else {
- typeDescr.setNamespace( typeDescr.getTypeName().substring( 0,
+ typeDescr.setNamespace( qName.substring( 0,
dotPos ) );
- typeDescr.setTypeName( typeDescr.getTypeName().substring( dotPos + 1 ) );
+ typeDescr.setTypeName( qName.substring( dotPos + 1 ) );
}
}
- if ( isEmpty( typeDescr.getNamespace() ) ) {
- // check imports
- try {
- Class< ? > cls = defaultRegistry.getTypeResolver().resolveType( typeDescr.getTypeName() );
- typeDescr.setNamespace( ClassUtils.getPackage( cls ) );
- String name = cls.getName();
- dotPos = name.lastIndexOf( '.' );
- typeDescr.setTypeName( name.substring( dotPos + 1 ) );
- } catch ( ClassNotFoundException e ) {
- // swallow, as this isn't a mistake, it just means the type declaration is intended for the default namespace
- typeDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace
- }
- }
if ( isEmpty( typeDescr.getNamespace() ) ) {
- for ( ImportDescr id : packageDescr.getImports() ) {
- String imp = id.getTarget();
- if ( imp.endsWith( typeDescr.getTypeName() ) ) {
- typeDescr.setNamespace( imp.substring( 0,
- imp.lastIndexOf( '.' ) ) );
- }
- }
+ typeDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace
}
//identify superclass type and namespace
@@ -1708,7 +1704,10 @@ private boolean isNovelClass(TypeDeclarationDescr typeDescr) {
try {
PackageRegistry reg = this.pkgRegistryMap.get( typeDescr.getNamespace() );
if ( reg != null ) {
- Class< ? > resolvedType = reg.getTypeResolver().resolveType( typeDescr.getTypeName() );
+ String availableName = typeDescr.getNamespace() != null
+ ? typeDescr.getNamespace() + "." + typeDescr.getTypeName()
+ : typeDescr.getTypeName();
+ Class< ? > resolvedType = reg.getTypeResolver().resolveType( availableName );
if ( resolvedType != null && typeDescr.getFields().size() > 1 ) {
this.results.add( new TypeDeclarationError( "Duplicate type definition. A class with the name '" + resolvedType.getName() + "' was found in the classpath while trying to " +
"redefine the fields in the declare statement. Fields can only be defined for non-existing classes.",
diff --git a/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java b/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java
new file mode 100644
index 00000000000..7791953334d
--- /dev/null
+++ b/drools-compiler/src/test/java/org/drools/compiler/TypeDeclarationTest.java
@@ -0,0 +1,31 @@
+package org.drools.compiler;
+
+import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;
+
+import org.drools.builder.KnowledgeBuilder;
+import org.drools.builder.KnowledgeBuilderFactory;
+import org.drools.builder.ResourceType;
+import org.drools.io.ResourceFactory;
+import org.junit.Test;
+
+public class TypeDeclarationTest {
+
+ @Test
+ public void testClassNameClashing() {
+ String str = "";
+ str += "package org.drools \n" +
+ "declare Character \n" +
+ " name : String \n" +
+ "end \n";
+
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+
+ kbuilder.add( ResourceFactory.newByteArrayResource( str.getBytes() ),
+ ResourceType.DRL );
+
+ if ( kbuilder.hasErrors() ) {
+ fail( kbuilder.getErrors().toString() );
+ }
+ }
+}
|
cd519e56eee4a0503bf696318dc09f6a745e7c37
|
Valadoc
|
driver: Add support for vala-0.20
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/configure.ac b/configure.ac
index a8fc5543a0..c3153d790a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -51,10 +51,6 @@ PKG_CHECK_MODULES(LIBGEE, gee-0.8 >= $LIBGEE_REQUIRED)
AC_SUBST(LIBGEE_CFLAGS)
AC_SUBST(LIBGEE_LIBS)
-PKG_CHECK_MODULES(LIBGDKPIXBUF, gdk-pixbuf-2.0 >= $LIBGDKPIXBUF_REQUIRED)
-AC_SUBST(LIBGDKPIXBUF_CFLAGS)
-AC_SUBST(LIBGDKPIXBUF_LIBS)
-
@@ -62,6 +58,13 @@ AC_SUBST(LIBGDKPIXBUF_LIBS)
## Drivers:
##
+PKG_CHECK_MODULES(LIBVALA_0_20_X, libvala-0.20 >= 0.17.4, have_libvala_0_20_x="yes", have_libvala_0_20_x="no")
+AM_CONDITIONAL(HAVE_LIBVALA_0_20_X, test "$have_libvala_0_20_x" = "yes")
+AC_SUBST(LIBVALA_0_20_X_CFLAGS)
+AC_SUBST(LIBVALA_0_20_X_LIBS)
+
+
+
PKG_CHECK_MODULES(LIBVALA_0_18_X, libvala-0.18 >= 0.17.4, have_libvala_0_18_x="yes", have_libvala_0_18_x="no")
AM_CONDITIONAL(HAVE_LIBVALA_0_18_X, test "$have_libvala_0_18_x" = "yes")
AC_SUBST(LIBVALA_0_18_X_CFLAGS)
@@ -155,6 +158,7 @@ AC_CONFIG_FILES([Makefile
src/driver/0.14.x/Makefile
src/driver/0.16.x/Makefile
src/driver/0.18.x/Makefile
+ src/driver/0.20.x/Makefile
src/doclets/Makefile
src/doclets/htm/Makefile
src/doclets/devhelp/Makefile
diff --git a/src/driver/0.20.x/Makefile.am b/src/driver/0.20.x/Makefile.am
new file mode 100644
index 0000000000..a1e7416589
--- /dev/null
+++ b/src/driver/0.20.x/Makefile.am
@@ -0,0 +1,65 @@
+NULL =
+
+
+VERSIONED_VAPI_DIR=`pkg-config libvala-0.20 --variable vapidir`
+
+
+AM_CFLAGS = -g \
+ -DPACKAGE_ICONDIR=\"$(datadir)/valadoc/icons/\" \
+ -I ../../libvaladoc/ \
+ $(GLIB_CFLAGS) \
+ $(LIBGEE_CFLAGS) \
+ $(LIBVALA_0_20_X_CFLAGS) \
+ $(NULL)
+
+
+BUILT_SOURCES = libdriver.vala.stamp
+
+
+driverdir = $(libdir)/valadoc/drivers/0.20.x
+
+
+libdriver_la_LDFLAGS = -module -avoid-version -no-undefined
+
+
+driver_LTLIBRARIES = \
+ libdriver.la \
+ $(NULL)
+
+
+libdriver_la_VALASOURCES = \
+ initializerbuilder.vala \
+ symbolresolver.vala \
+ treebuilder.vala \
+ girwriter.vala \
+ driver.vala \
+ $(NULL)
+
+
+libdriver_la_SOURCES = \
+ libdriver.vala.stamp \
+ $(libdriver_la_VALASOURCES:.vala=.c) \
+ $(NULL)
+
+
+libdriver.vala.stamp: $(libdriver_la_VALASOURCES)
+ $(VALAC) $(VALA_FLAGS) -C --vapidir $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.20 --pkg gee-0.8 --pkg valadoc-1.0 --basedir . $^
+ touch $@
+
+
+libdriver_la_LIBADD = \
+ ../../libvaladoc/libvaladoc.la \
+ $(GLIB_LIBS) \
+ $(LIBVALA_0_20_X_LIBS) \
+ $(LIBGEE_LIBS) \
+ $(NULL)
+
+
+EXTRA_DIST = $(libdriver_la_VALASOURCES) libdriver.vala.stamp
+
+
+MAINTAINERCLEANFILES = \
+ $(libdriver_la_VALASOURCES:.vala=.c) \
+ $(NULL)
+
+
diff --git a/src/driver/0.20.x/driver.vala b/src/driver/0.20.x/driver.vala
new file mode 100644
index 0000000000..35d43d1381
--- /dev/null
+++ b/src/driver/0.20.x/driver.vala
@@ -0,0 +1,65 @@
+/* driver.vala
+ *
+ * Copyright (C) 2011 Florian Brosch
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Author:
+ * Florian Brosch <[email protected]>
+ */
+
+using Valadoc.Api;
+using Gee;
+
+
+
+/**
+ * Creates an simpler, minimized, more abstract AST for valacs AST.
+ */
+public class Valadoc.Drivers.Driver : Object, Valadoc.Driver {
+ private SymbolResolver resolver;
+ private Api.Tree? tree;
+
+ public void write_gir (Settings settings, ErrorReporter reporter) {
+ var gir_writer = new Drivers.GirWriter (resolver);
+
+ // put .gir file in current directory unless -d has been explicitly specified
+ string gir_directory = ".";
+ if (settings.gir_directory != null) {
+ gir_directory = settings.gir_directory;
+ }
+
+ gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name);
+ }
+
+ public Api.Tree? build (Settings settings, ErrorReporter reporter) {
+ TreeBuilder builder = new TreeBuilder ();
+ tree = builder.build (settings, reporter);
+ if (reporter.errors > 0) {
+ return null;
+ }
+
+ resolver = new SymbolResolver (builder);
+ tree.accept (resolver);
+
+ return tree;
+ }
+}
+
+
+public Type register_plugin (Valadoc.ModuleLoader module_loader) {
+ return typeof (Valadoc.Drivers.Driver);
+}
+
diff --git a/src/driver/0.20.x/girwriter.vala b/src/driver/0.20.x/girwriter.vala
new file mode 100644
index 0000000000..c250854d64
--- /dev/null
+++ b/src/driver/0.20.x/girwriter.vala
@@ -0,0 +1,204 @@
+/* girwriter.vala
+ *
+ * Copyright (C) 2011 Florian Brosch
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Author:
+ * Florian Brosch <[email protected]>
+ */
+
+
+using Valadoc.Api;
+
+
+/**
+ * Code visitor generating .gir file for the public interface.
+ */
+public class Valadoc.Drivers.GirWriter : Vala.GIRWriter {
+ private GtkdocRenderer renderer;
+ private SymbolResolver resolver;
+
+ public GirWriter (SymbolResolver resolver) {
+ this.renderer = new GtkdocRenderer ();
+ this.resolver = resolver;
+ }
+
+ private string? translate (Content.Comment? documentation) {
+ if (documentation == null) {
+ return null;
+ }
+
+ renderer.render_symbol (documentation);
+
+ return MarkupWriter.escape (renderer.content);
+ }
+
+ private string? translate_taglet (Content.Taglet? taglet) {
+ if (taglet == null) {
+ return null;
+ }
+
+ renderer.render_children (taglet);
+
+ return MarkupWriter.escape (renderer.content);
+ }
+
+ protected override string? get_interface_comment (Vala.Interface viface) {
+ Interface iface = resolver.resolve (viface) as Interface;
+ return translate (iface.documentation);
+ }
+
+ protected override string? get_struct_comment (Vala.Struct vst) {
+ Struct st = resolver.resolve (vst) as Struct;
+ return translate (st.documentation);
+ }
+
+ protected override string? get_enum_comment (Vala.Enum ven) {
+ Enum en = resolver.resolve (ven) as Enum;
+ return translate (en.documentation);
+ }
+
+ protected override string? get_class_comment (Vala.Class vc) {
+ Class c = resolver.resolve (vc) as Class;
+ return translate (c.documentation);
+ }
+
+ protected override string? get_error_code_comment (Vala.ErrorCode vecode) {
+ ErrorCode ecode = resolver.resolve (vecode) as ErrorCode;
+ return translate (ecode.documentation);
+ }
+
+ protected override string? get_enum_value_comment (Vala.EnumValue vev) {
+ Api.EnumValue ev = resolver.resolve (vev) as Api.EnumValue;
+ return translate (ev.documentation);
+ }
+
+ protected override string? get_constant_comment (Vala.Constant vc) {
+ Constant c = resolver.resolve (vc) as Constant;
+ return translate (c.documentation);
+ }
+
+ protected override string? get_error_domain_comment (Vala.ErrorDomain vedomain) {
+ ErrorDomain edomain = resolver.resolve (vedomain) as ErrorDomain;
+ return translate (edomain.documentation);
+ }
+
+ protected override string? get_field_comment (Vala.Field vf) {
+ Field f = resolver.resolve (vf) as Field;
+ return translate (f.documentation);
+ }
+
+ protected override string? get_delegate_comment (Vala.Delegate vcb) {
+ Delegate cb = resolver.resolve (vcb) as Delegate;
+ return translate (cb.documentation);
+ }
+
+ protected override string? get_method_comment (Vala.Method vm) {
+ Method m = resolver.resolve (vm) as Method;
+ return translate (m.documentation);
+ }
+
+ protected override string? get_property_comment (Vala.Property vprop) {
+ Property prop = resolver.resolve (vprop) as Property;
+ return translate (prop.documentation);
+ }
+
+ protected override string? get_delegate_return_comment (Vala.Delegate vcb) {
+ Delegate cb = resolver.resolve (vcb) as Delegate;
+ if (cb.documentation == null) {
+ return null;
+ }
+
+ Content.Comment? documentation = cb.documentation;
+ if (documentation == null) {
+ return null;
+ }
+
+ Gee.List<Content.Taglet> taglets = documentation.find_taglets (cb, typeof(Taglets.Return));
+ foreach (Content.Taglet taglet in taglets) {
+ return translate_taglet (taglet);
+ }
+
+ return null;
+ }
+
+ protected override string? get_signal_return_comment (Vala.Signal vsig) {
+ Api.Signal sig = resolver.resolve (vsig) as Api.Signal;
+ if (sig.documentation == null) {
+ return null;
+ }
+
+ Content.Comment? documentation = sig.documentation;
+ if (documentation == null) {
+ return null;
+ }
+
+ Gee.List<Content.Taglet> taglets = documentation.find_taglets (sig, typeof(Taglets.Return));
+ foreach (Content.Taglet taglet in taglets) {
+ return translate_taglet (taglet);
+ }
+
+ return null;
+ }
+
+ protected override string? get_method_return_comment (Vala.Method vm) {
+ Method m = resolver.resolve (vm) as Method;
+ if (m.documentation == null) {
+ return null;
+ }
+
+ Content.Comment? documentation = m.documentation;
+ if (documentation == null) {
+ return null;
+ }
+
+ Gee.List<Content.Taglet> taglets = documentation.find_taglets (m, typeof(Taglets.Return));
+ foreach (Content.Taglet taglet in taglets) {
+ return translate_taglet (taglet);
+ }
+
+ return null;
+ }
+
+ protected override string? get_signal_comment (Vala.Signal vsig) {
+ Api.Signal sig = resolver.resolve (vsig) as Api.Signal;
+ return translate (sig.documentation);
+ }
+
+ protected override string? get_parameter_comment (Vala.Parameter param) {
+ Api.Symbol symbol = resolver.resolve (((Vala.Symbol) param.parent_symbol));
+ if (symbol == null) {
+ return null;
+ }
+
+ Content.Comment? documentation = symbol.documentation;
+ if (documentation == null) {
+ return null;
+ }
+
+ Gee.List<Content.Taglet> taglets = documentation.find_taglets (symbol, typeof(Taglets.Param));
+ foreach (Content.Taglet _taglet in taglets) {
+ Taglets.Param taglet = (Taglets.Param) _taglet;
+ if (taglet.parameter_name == param.name) {
+ return translate_taglet (taglet);
+ }
+ }
+
+ return null;
+ }
+}
+
+
diff --git a/src/driver/0.20.x/initializerbuilder.vala b/src/driver/0.20.x/initializerbuilder.vala
new file mode 100644
index 0000000000..7b26ab51f5
--- /dev/null
+++ b/src/driver/0.20.x/initializerbuilder.vala
@@ -0,0 +1,669 @@
+/* initializerbuilder.vala
+ *
+ * Copyright (C) 2011 Florian Brosch
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Author:
+ * Florian Brosch <[email protected]>
+ */
+
+
+using Valadoc.Content;
+using Gee;
+
+
+private class Valadoc.Api.InitializerBuilder : Vala.CodeVisitor {
+ private HashMap<Vala.Symbol, Symbol> symbol_map;
+ private SignatureBuilder signature;
+
+ private Symbol? resolve (Vala.Symbol symbol) {
+ return symbol_map.get (symbol);
+ }
+
+ private void write_node (Vala.Symbol vsymbol) {
+ signature.append_symbol (resolve (vsymbol));
+ }
+
+ private void write_type (Vala.DataType vsymbol) {
+ if (vsymbol.data_type != null) {
+ write_node (vsymbol.data_type);
+ } else {
+ signature.append_literal ("null");
+ }
+
+ var type_args = vsymbol.get_type_arguments ();
+ if (type_args.size > 0) {
+ signature.append ("<");
+ bool first = true;
+ foreach (Vala.DataType type_arg in type_args) {
+ if (!first) {
+ signature.append (",");
+ } else {
+ first = false;
+ }
+ if (!type_arg.value_owned) {
+ signature.append_keyword ("weak");
+ }
+ signature.append (type_arg.to_qualified_string (null));
+ }
+ signature.append (">");
+ }
+
+ if (vsymbol.nullable) {
+ signature.append ("?");
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_array_creation_expression (Vala.ArrayCreationExpression expr) {
+ signature.append_keyword ("new");
+ write_type (expr.element_type);
+ signature.append ("[", false);
+
+ bool first = true;
+ foreach (Vala.Expression size in expr.get_sizes ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+ size.accept (this);
+ first = false;
+ }
+
+ signature.append ("]", false);
+
+ if (expr.initializer_list != null) {
+ signature.append (" ", false);
+ expr.initializer_list.accept (this);
+ }
+ }
+
+ public InitializerBuilder (SignatureBuilder signature, HashMap<Vala.Symbol, Symbol> symbol_map) {
+ this.symbol_map = symbol_map;
+ this.signature = signature;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_binary_expression (Vala.BinaryExpression expr) {
+ expr.left.accept (this);
+
+ switch (expr.operator) {
+ case Vala.BinaryOperator.PLUS:
+ signature.append ("+ ");
+ break;
+
+ case Vala.BinaryOperator.MINUS:
+ signature.append ("- ");
+ break;
+
+ case Vala.BinaryOperator.MUL:
+ signature.append ("* ");
+ break;
+
+ case Vala.BinaryOperator.DIV:
+ signature.append ("/ ");
+ break;
+
+ case Vala.BinaryOperator.MOD:
+ signature.append ("% ");
+ break;
+
+ case Vala.BinaryOperator.SHIFT_LEFT:
+ signature.append ("<< ");
+ break;
+
+ case Vala.BinaryOperator.SHIFT_RIGHT:
+ signature.append (">> ");
+ break;
+
+ case Vala.BinaryOperator.LESS_THAN:
+ signature.append ("< ");
+ break;
+
+ case Vala.BinaryOperator.GREATER_THAN:
+ signature.append ("> ");
+ break;
+
+ case Vala.BinaryOperator.LESS_THAN_OR_EQUAL:
+ signature.append ("<= ");
+ break;
+
+ case Vala.BinaryOperator.GREATER_THAN_OR_EQUAL:
+ signature.append (">= ");
+ break;
+
+ case Vala.BinaryOperator.EQUALITY:
+ signature.append ("== ");
+ break;
+
+ case Vala.BinaryOperator.INEQUALITY:
+ signature.append ("!= ");
+ break;
+
+ case Vala.BinaryOperator.BITWISE_AND:
+ signature.append ("& ");
+ break;
+
+ case Vala.BinaryOperator.BITWISE_OR:
+ signature.append ("| ");
+ break;
+
+ case Vala.BinaryOperator.BITWISE_XOR:
+ signature.append ("^ ");
+ break;
+
+ case Vala.BinaryOperator.AND:
+ signature.append ("&& ");
+ break;
+
+ case Vala.BinaryOperator.OR:
+ signature.append ("|| ");
+ break;
+
+ case Vala.BinaryOperator.IN:
+ signature.append_keyword ("in");
+ signature.append (" ");
+ break;
+
+ case Vala.BinaryOperator.COALESCE:
+ signature.append ("?? ");
+ break;
+
+ default:
+ assert_not_reached ();
+ }
+
+ expr.right.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_unary_expression (Vala.UnaryExpression expr) {
+ switch (expr.operator) {
+ case Vala.UnaryOperator.PLUS:
+ signature.append ("+");
+ break;
+
+ case Vala.UnaryOperator.MINUS:
+ signature.append ("-");
+ break;
+
+ case Vala.UnaryOperator.LOGICAL_NEGATION:
+ signature.append ("!");
+ break;
+
+ case Vala.UnaryOperator.BITWISE_COMPLEMENT:
+ signature.append ("~");
+ break;
+
+ case Vala.UnaryOperator.INCREMENT:
+ signature.append ("++");
+ break;
+
+ case Vala.UnaryOperator.DECREMENT:
+ signature.append ("--");
+ break;
+
+ case Vala.UnaryOperator.REF:
+ signature.append_keyword ("ref");
+ break;
+
+ case Vala.UnaryOperator.OUT:
+ signature.append_keyword ("out");
+ break;
+
+ default:
+ assert_not_reached ();
+ }
+ expr.inner.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_assignment (Vala.Assignment a) {
+ a.left.accept (this);
+
+ switch (a.operator) {
+ case Vala.AssignmentOperator.SIMPLE:
+ signature.append ("=");
+ break;
+
+ case Vala.AssignmentOperator.BITWISE_OR:
+ signature.append ("|");
+ break;
+
+ case Vala.AssignmentOperator.BITWISE_AND:
+ signature.append ("&");
+ break;
+
+ case Vala.AssignmentOperator.BITWISE_XOR:
+ signature.append ("^");
+ break;
+
+ case Vala.AssignmentOperator.ADD:
+ signature.append ("+");
+ break;
+
+ case Vala.AssignmentOperator.SUB:
+ signature.append ("-");
+ break;
+
+ case Vala.AssignmentOperator.MUL:
+ signature.append ("*");
+ break;
+
+ case Vala.AssignmentOperator.DIV:
+ signature.append ("/");
+ break;
+
+ case Vala.AssignmentOperator.PERCENT:
+ signature.append ("%");
+ break;
+
+ case Vala.AssignmentOperator.SHIFT_LEFT:
+ signature.append ("<<");
+ break;
+
+ case Vala.AssignmentOperator.SHIFT_RIGHT:
+ signature.append (">>");
+ break;
+
+ default:
+ assert_not_reached ();
+ }
+
+ a.right.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_cast_expression (Vala.CastExpression expr) {
+ if (expr.is_non_null_cast) {
+ signature.append ("(!)");
+ expr.inner.accept (this);
+ return;
+ }
+
+ if (!expr.is_silent_cast) {
+ signature.append ("(", false);
+ write_type (expr.type_reference);
+ signature.append (")", false);
+ }
+
+ expr.inner.accept (this);
+
+ if (expr.is_silent_cast) {
+ signature.append_keyword ("as");
+ write_type (expr.type_reference);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_initializer_list (Vala.InitializerList list) {
+ signature.append ("{", false);
+
+ bool first = true;
+ foreach (Vala.Expression initializer in list.get_initializers ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+ first = false;
+ initializer.accept (this);
+ }
+
+ signature.append ("}", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_member_access (Vala.MemberAccess expr) {
+ if (expr.symbol_reference != null) {
+ expr.symbol_reference.accept (this);
+ } else {
+ signature.append (expr.member_name);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_element_access (Vala.ElementAccess expr) {
+ expr.container.accept (this);
+ signature.append ("[", false);
+
+ bool first = true;
+ foreach (Vala.Expression index in expr.get_indices ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+ first = false;
+
+ index.accept (this);
+ }
+
+ signature.append ("]", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_pointer_indirection (Vala.PointerIndirection expr) {
+ signature.append ("*", false);
+ expr.inner.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_addressof_expression (Vala.AddressofExpression expr) {
+ signature.append ("&", false);
+ expr.inner.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_reference_transfer_expression (Vala.ReferenceTransferExpression expr) {
+ signature.append ("(", false).append_keyword ("owned", false).append (")", false);
+ expr.inner.accept (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_type_check (Vala.TypeCheck expr) {
+ expr.expression.accept (this);
+ signature.append_keyword ("is");
+ write_type (expr.type_reference);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_method_call (Vala.MethodCall expr) {
+ // symbol-name:
+ expr.call.symbol_reference.accept (this);
+
+ // parameters:
+ signature.append (" (", false);
+ bool first = true;
+ foreach (Vala.Expression literal in expr.get_argument_list ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+
+ literal.accept (this);
+ first = false;
+ }
+ signature.append (")", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_slice_expression (Vala.SliceExpression expr) {
+ expr.container.accept (this);
+ signature.append ("[", false);
+ expr.start.accept (this);
+ signature.append (":", false);
+ expr.stop.accept (this);
+ signature.append ("]", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_base_access (Vala.BaseAccess expr) {
+ signature.append_keyword ("base", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_postfix_expression (Vala.PostfixExpression expr) {
+ expr.inner.accept (this);
+ if (expr.increment) {
+ signature.append ("++", false);
+ } else {
+ signature.append ("--", false);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_object_creation_expression (Vala.ObjectCreationExpression expr) {
+ if (!expr.struct_creation) {
+ signature.append_keyword ("new");
+ }
+
+ signature.append_symbol (resolve (expr.symbol_reference));
+
+ signature.append (" (", false);
+
+ //TODO: rm conditional space
+ bool first = true;
+ foreach (Vala.Expression arg in expr.get_argument_list ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+ arg.accept (this);
+ first = false;
+ }
+
+ signature.append (")", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_sizeof_expression (Vala.SizeofExpression expr) {
+ signature.append_keyword ("sizeof", false).append (" (", false);
+ write_type (expr.type_reference);
+ signature.append (")", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_typeof_expression (Vala.TypeofExpression expr) {
+ signature.append_keyword ("typeof", false).append (" (", false);
+ write_type (expr.type_reference);
+ signature.append (")", false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_lambda_expression (Vala.LambdaExpression expr) {
+ signature.append ("(", false);
+
+ bool first = true;
+ foreach (Vala.Parameter param in expr.get_parameters ()) {
+ if (!first) {
+ signature.append (", ", false);
+ }
+ signature.append (param.name, false);
+ first = false;
+ }
+
+
+ signature.append (") => {", false);
+ signature.append_highlighted (" [...] ", false);
+ signature.append ("}", false);
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_boolean_literal (Vala.BooleanLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_character_literal (Vala.CharacterLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_integer_literal (Vala.IntegerLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_real_literal (Vala.RealLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_regex_literal (Vala.RegexLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_string_literal (Vala.StringLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_null_literal (Vala.NullLiteral lit) {
+ signature.append_literal (lit.to_string (), false);
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_field (Vala.Field field) {
+ write_node (field);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_constant (Vala.Constant constant) {
+ write_node (constant);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum_value (Vala.EnumValue ev) {
+ write_node (ev);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_code (Vala.ErrorCode ec) {
+ write_node (ec);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_delegate (Vala.Delegate d) {
+ write_node (d);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_method (Vala.Method m) {
+ write_node (m);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_creation_method (Vala.CreationMethod m) {
+ write_node (m);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_signal (Vala.Signal sig) {
+ write_node (sig);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_class (Vala.Class c) {
+ write_node (c);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_struct (Vala.Struct s) {
+ write_node (s);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_interface (Vala.Interface i) {
+ write_node (i);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum (Vala.Enum en) {
+ write_node (en);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_domain (Vala.ErrorDomain ed) {
+ write_node (ed);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_property (Vala.Property prop) {
+ write_node (prop);
+ }
+}
+
diff --git a/src/driver/0.20.x/symbolresolver.vala b/src/driver/0.20.x/symbolresolver.vala
new file mode 100644
index 0000000000..f548f735d8
--- /dev/null
+++ b/src/driver/0.20.x/symbolresolver.vala
@@ -0,0 +1,321 @@
+/* symbolresolver.vala
+ *
+ * Copyright (C) 2011 Florian Brosch
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Author:
+ * Florian Brosch <[email protected]>
+ */
+
+using Valadoc.Api;
+using Gee;
+
+
+public class Valadoc.Drivers.SymbolResolver : Visitor {
+ private HashMap<Vala.Symbol, Symbol> symbol_map;
+ private Valadoc.Api.Class glib_error;
+ private Api.Tree root;
+
+ public SymbolResolver (TreeBuilder builder) {
+ this.symbol_map = builder.get_symbol_map ();
+ this.glib_error = builder.get_glib_error ();
+ }
+
+ public Symbol? resolve (Vala.Symbol symbol) {
+ return symbol_map.get (symbol);
+ }
+
+ private void resolve_thrown_list (Symbol symbol, Vala.List<Vala.DataType> types) {
+ foreach (Vala.DataType type in types) {
+ Vala.ErrorDomain vala_edom = (Vala.ErrorDomain) type.data_type;
+ Symbol? edom = symbol_map.get (vala_edom);
+ symbol.add_child (edom ?? glib_error);
+ }
+ }
+
+ private void resolve_array_type_references (Api.Array ptr) {
+ Api.Item data_type = ptr.data_type;
+ if (data_type == null) {
+ // void
+ } else if (data_type is Api.Array) {
+ resolve_array_type_references ((Api.Array) data_type);
+ } else if (data_type is Pointer) {
+ resolve_pointer_type_references ((Api.Pointer) data_type);
+ } else {
+ resolve_type_reference ((TypeReference) data_type);
+ }
+ }
+
+ private void resolve_pointer_type_references (Pointer ptr) {
+ Api.Item type = ptr.data_type;
+ if (type == null) {
+ // void
+ } else if (type is Api.Array) {
+ resolve_array_type_references ((Api.Array) type);
+ } else if (type is Pointer) {
+ resolve_pointer_type_references ((Pointer) type);
+ } else {
+ resolve_type_reference ((TypeReference) type);
+ }
+ }
+
+ private void resolve_type_reference (TypeReference reference) {
+ Vala.DataType vtyperef = (Vala.DataType) reference.data;
+ if (vtyperef is Vala.ErrorType) {
+ Vala.ErrorDomain verrdom = ((Vala.ErrorType) vtyperef).error_domain;
+ if (verrdom != null) {
+ reference.data_type = resolve (verrdom);
+ } else {
+ reference.data_type = glib_error;
+ }
+ } else if (vtyperef is Vala.DelegateType) {
+ reference.data_type = resolve (((Vala.DelegateType) vtyperef).delegate_symbol);
+ } else if (vtyperef.data_type != null) {
+ reference.data_type = resolve (vtyperef.data_type);
+ }
+
+ // Type parameters:
+ foreach (TypeReference type_param_ref in reference.get_type_arguments ()) {
+ resolve_type_reference (type_param_ref);
+ }
+
+ if (reference.data_type is Pointer) {
+ resolve_pointer_type_references ((Pointer)reference.data_type);
+ } else if (reference.data_type is Api.Array) {
+ resolve_array_type_references ((Api.Array)reference.data_type);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_tree (Api.Tree item) {
+ this.root = item;
+ item.accept_children (this);
+ this.root = null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_package (Package item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_namespace (Namespace item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_interface (Interface item) {
+ Collection<TypeReference> interfaces = item.get_implemented_interface_list ();
+ foreach (var type_ref in interfaces) {
+ resolve_type_reference (type_ref);
+ }
+
+ if (item.base_type != null) {
+ resolve_type_reference (item.base_type);
+ }
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_class (Class item) {
+ Collection<TypeReference> interfaces = item.get_implemented_interface_list ();
+ foreach (TypeReference type_ref in interfaces) {
+ resolve_type_reference (type_ref);
+ }
+
+ if (item.base_type != null) {
+ resolve_type_reference (item.base_type);
+ }
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_struct (Struct item) {
+ if (item.base_type != null) {
+ resolve_type_reference (item.base_type);
+ }
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_property (Property item) {
+ Vala.Property vala_property = item.data as Vala.Property;
+ Vala.Property? base_vala_property = null;
+
+ if (vala_property.base_property != null) {
+ base_vala_property = vala_property.base_property;
+ } else if (vala_property.base_interface_property != null) {
+ base_vala_property = vala_property.base_interface_property;
+ }
+ if (base_vala_property == vala_property && vala_property.base_interface_property != null) {
+ base_vala_property = vala_property.base_interface_property;
+ }
+ if (base_vala_property != null) {
+ item.base_property = (Property?) resolve (base_vala_property);
+ }
+
+ resolve_type_reference (item.property_type);
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_field (Field item) {
+ resolve_type_reference (item.field_type);
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_constant (Constant item) {
+ resolve_type_reference (item.constant_type);
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_delegate (Delegate item) {
+ Vala.Delegate vala_delegate = item.data as Vala.Delegate;
+
+ resolve_type_reference (item.return_type);
+
+ resolve_thrown_list (item, vala_delegate.get_error_types ());
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_signal (Api.Signal item) {
+ resolve_type_reference (item.return_type);
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_method (Method item) {
+ Vala.Method vala_method = item.data as Vala.Method;
+ Vala.Method? base_vala_method = null;
+ if (vala_method.base_method != null) {
+ base_vala_method = vala_method.base_method;
+ } else if (vala_method.base_interface_method != null) {
+ base_vala_method = vala_method.base_interface_method;
+ }
+ if (base_vala_method == vala_method && vala_method.base_interface_method != null) {
+ base_vala_method = vala_method.base_interface_method;
+ }
+ if (base_vala_method != null) {
+ item.base_method = (Method?) resolve (base_vala_method);
+ }
+
+ resolve_thrown_list (item, vala_method.get_error_types ());
+
+ resolve_type_reference (item.return_type);
+
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_type_parameter (TypeParameter item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_formal_parameter (FormalParameter item) {
+ if (item.ellipsis) {
+ return;
+ }
+
+ if (((Vala.Parameter) item.data).initializer != null) {
+ SignatureBuilder signature = new SignatureBuilder ();
+ InitializerBuilder ibuilder = new InitializerBuilder (signature, symbol_map);
+ ((Vala.Parameter) item.data).initializer.accept (ibuilder);
+ item.default_value = signature.get ();
+ }
+
+ resolve_type_reference (item.parameter_type);
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_domain (ErrorDomain item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_code (ErrorCode item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum (Enum item) {
+ item.accept_all_children (this, false);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum_value (Api.EnumValue item) {
+
+ if (((Vala.EnumValue) item.data).value != null) {
+ SignatureBuilder signature = new SignatureBuilder ();
+ InitializerBuilder ibuilder = new InitializerBuilder (signature, symbol_map);
+ ((Vala.EnumValue) item.data).value.accept (ibuilder);
+ item.default_value = signature.get ();
+ }
+
+ item.accept_all_children (this, false);
+ }
+}
+
+
+
diff --git a/src/driver/0.20.x/treebuilder.vala b/src/driver/0.20.x/treebuilder.vala
new file mode 100644
index 0000000000..cc135d4444
--- /dev/null
+++ b/src/driver/0.20.x/treebuilder.vala
@@ -0,0 +1,1263 @@
+/* treebuilder.vala
+ *
+ * Copyright (C) 2011 Florian Brosch
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Author:
+ * Florian Brosch <[email protected]>
+ */
+
+
+using Valadoc.Api;
+using Gee;
+
+
+/**
+ * Creates an simpler, minimized, more abstract AST for valacs AST.
+ */
+public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor {
+ private ArrayList<PackageMetaData> packages = new ArrayList<PackageMetaData> ();
+ private PackageMetaData source_package;
+
+ private HashMap<Vala.SourceFile, SourceFile> files = new HashMap<Vala.SourceFile, SourceFile> ();
+ private HashMap<Vala.Symbol, Symbol> symbol_map = new HashMap<Vala.Symbol, Symbol> ();
+
+ private ErrorReporter reporter;
+ private Settings settings;
+
+ private Api.Node current_node;
+ private Api.Tree tree;
+
+ private Valadoc.Api.Class glib_error = null;
+
+
+ //
+ // Accessors
+ //
+
+ public Api.Class get_glib_error () {
+ return glib_error;
+ }
+
+ public HashMap<Vala.Symbol, Symbol> get_symbol_map () {
+ return symbol_map;
+ }
+
+
+ //
+ //
+ //
+
+ private class PackageMetaData {
+ public Package package;
+ public HashMap<Vala.Namespace, Namespace> namespaces = new HashMap<Vala.Namespace, Namespace> ();
+ public ArrayList<Vala.SourceFile> files = new ArrayList<Vala.SourceFile> ();
+
+ public PackageMetaData (Package package) {
+ this.package = package;
+ }
+
+ public Namespace get_namespace (Vala.Namespace vns, SourceFile file) {
+ Namespace? ns = namespaces.get (vns);
+ if (ns != null) {
+ return ns;
+ }
+
+ // find documentation comment if existing:
+ SourceComment? comment = null;
+ if (vns.source_reference != null) {
+ foreach (Vala.Comment c in vns.get_comments()) {
+ if (c.source_reference.file == file.data ||
+ (c.source_reference.file.file_type == Vala.SourceFileType.SOURCE
+ && ((Vala.SourceFile) file.data).file_type == Vala.SourceFileType.SOURCE)
+ ) {
+ Vala.SourceReference pos = c.source_reference;
+ if (c is Vala.GirComment) {
+ comment = new GirSourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ } else {
+ comment = new SourceComment (c.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ }
+ break;
+ }
+ }
+ }
+
+ // find parent if existing
+ var parent_vns = vns.parent_symbol;
+
+ if (parent_vns == null) {
+ ns = new Namespace (package, file, vns.name, comment, vns);
+ package.add_child (ns);
+ } else {
+ Namespace parent_ns = get_namespace ((Vala.Namespace) parent_vns, file);
+ ns = new Namespace (parent_ns, file, vns.name, comment, vns);
+ parent_ns.add_child (ns);
+ }
+
+ namespaces.set (vns, ns);
+ return ns;
+ }
+
+ public void register_source_file (Vala.SourceFile file) {
+ files.add (file);
+ }
+
+ public bool is_package_for_file (Vala.SourceFile source_file) {
+ if (source_file.file_type == Vala.SourceFileType.SOURCE && !package.is_package) {
+ return true;
+ }
+
+ return files.contains (source_file);
+ }
+ }
+
+
+ //
+ // Type constructor translation helpers:
+ //
+
+ private Pointer create_pointer (Vala.PointerType vtyperef, Item parent, Api.Node caller) {
+ Pointer ptr = new Pointer (parent, vtyperef);
+
+ Vala.DataType vntype = vtyperef.base_type;
+ if (vntype is Vala.PointerType) {
+ ptr.data_type = create_pointer ((Vala.PointerType) vntype, ptr, caller);
+ } else if (vntype is Vala.ArrayType) {
+ ptr.data_type = create_array ((Vala.ArrayType) vntype, ptr, caller);
+ } else {
+ ptr.data_type = create_type_reference (vntype, ptr, caller);
+ }
+
+ return ptr;
+ }
+
+ private Api.Array create_array (Vala.ArrayType vtyperef, Item parent, Api.Node caller) {
+ Api.Array arr = new Api.Array (parent, vtyperef);
+
+ Vala.DataType vntype = vtyperef.element_type;
+ if (vntype is Vala.ArrayType) {
+ arr.data_type = create_array ((Vala.ArrayType) vntype, arr, caller);
+ } else {
+ arr.data_type = create_type_reference (vntype, arr, caller);
+ }
+
+ return arr;
+ }
+
+ private TypeReference create_type_reference (Vala.DataType? vtyperef, Item parent, Api.Node caller) {
+ bool is_nullable = vtyperef != null && vtyperef.nullable && !(vtyperef is Vala.GenericType) && !(vtyperef is Vala.PointerType);
+ string? signature = (vtyperef != null && vtyperef.data_type != null)? Vala.GVariantModule.get_dbus_signature (vtyperef.data_type) : null;
+ bool pass_ownership = type_reference_pass_ownership (vtyperef);
+ Ownership ownership = get_type_reference_ownership (vtyperef);
+ bool is_dynamic = vtyperef != null && vtyperef.is_dynamic;
+
+ TypeReference type_ref = new TypeReference (parent, ownership, pass_ownership, is_dynamic, is_nullable, signature, vtyperef);
+
+ if (vtyperef is Vala.PointerType) {
+ type_ref.data_type = create_pointer ((Vala.PointerType) vtyperef, type_ref, caller);
+ } else if (vtyperef is Vala.ArrayType) {
+ type_ref.data_type = create_array ((Vala.ArrayType) vtyperef, type_ref, caller);
+ } else if (vtyperef is Vala.GenericType) {
+ type_ref.data_type = new TypeParameter (caller, caller.get_source_file (), ((Vala.GenericType) vtyperef).type_parameter.name, vtyperef);
+ }
+
+ // type parameters:
+ if (vtyperef != null) {
+ foreach (Vala.DataType vdtype in vtyperef.get_type_arguments ()) {
+ var type_param = create_type_reference (vdtype, type_ref, caller);
+ type_ref.add_type_argument (type_param);
+ }
+ }
+
+ return type_ref;
+ }
+
+
+
+ //
+ // Translation helpers:
+ //
+
+ private void process_attributes (Api.Symbol parent, GLib.List<Vala.Attribute> lst) {
+ // attributes wihtout arguments:
+ string[] attributes = {
+ "ReturnsModifiedPointer",
+ "DestroysInstance",
+ "NoAccessorMethod",
+ "NoArrayLength",
+ "Experimental",
+ "Diagnostics",
+ "PrintfFormat",
+ "PointerType",
+ "ScanfFormat",
+ "ThreadLocal",
+ "SimpleType",
+ "HasEmitter",
+ "ModuleInit",
+ "NoWrapper",
+ "Immutable",
+ "ErrorBase",
+ "NoReturn",
+ "NoThrow",
+ "Compact",
+ "Assert",
+ "Flags"
+ };
+
+ string? tmp = "";
+
+ foreach (Vala.Attribute att in lst) {
+ if (att.name == "CCode" && (tmp = att.args.get ("has_target")) != null && tmp == "false") {
+ Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att);
+ new_attribute.add_boolean ("has_target", false, att);
+ parent.add_attribute (new_attribute);
+ } else if (att.name == "Deprecated") {
+ Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att);
+ parent.add_attribute (new_attribute);
+ if ((tmp = att.args.get ("since")) != null) {
+ new_attribute.add_string ("since", tmp, att);
+ }
+
+ if ((tmp = att.args.get ("replacement")) != null) {
+ new_attribute.add_string ("replacement", tmp, att);
+ }
+ } else if (att.name in attributes) {
+ Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att);
+ parent.add_attribute (new_attribute);
+ }
+ }
+ }
+
+ private string? get_ccode_type_id (Vala.CodeNode node) {
+ return Vala.CCodeBaseModule.get_ccode_type_id (node);
+ }
+
+ private bool is_reference_counting (Vala.TypeSymbol sym) {
+ return Vala.CCodeBaseModule.is_reference_counting (sym);
+ }
+
+ private string? get_ref_function (Vala.Class sym) {
+ return Vala.CCodeBaseModule.get_ccode_ref_function (sym);
+ }
+
+ private string? get_unref_function (Vala.Class sym) {
+ return Vala.CCodeBaseModule.get_ccode_unref_function (sym);
+ }
+
+ private string? get_finalize_function_name (Vala.Class element) {
+ if (!element.is_fundamental ()) {
+ return null;
+ }
+
+ return "%s_finalize".printf (Vala.CCodeBaseModule.get_ccode_lower_case_name (element, null));
+ }
+
+ private string? get_free_function_name (Vala.Class element) {
+ if (!element.is_compact) {
+ return null;
+ }
+
+ return Vala.CCodeBaseModule.get_ccode_free_function (element);
+ }
+
+ private string? get_finish_name (Vala.Method m) {
+ return Vala.CCodeBaseModule.get_ccode_finish_name (m);
+ }
+
+ private string? get_take_value_function (Vala.Class sym) {
+ return Vala.CCodeBaseModule.get_ccode_take_value_function (sym);
+ }
+
+ private string? get_get_value_function (Vala.Class sym) {
+ return Vala.CCodeBaseModule.get_ccode_get_value_function (sym);
+ }
+
+ private string? get_set_value_function (Vala.Class sym) {
+ return Vala.CCodeBaseModule.get_ccode_set_value_function (sym);
+ }
+
+
+ private string? get_param_spec_function (Vala.CodeNode sym) {
+ return Vala.CCodeBaseModule.get_ccode_param_spec_function (sym);
+ }
+
+ private string? get_dup_function (Vala.TypeSymbol sym) {
+ return Vala.CCodeBaseModule.get_ccode_dup_function (sym);
+ }
+
+ private string? get_free_function (Vala.TypeSymbol sym) {
+ return Vala.CCodeBaseModule.get_ccode_free_function (sym);
+ }
+
+ private string? get_nick (Vala.Property prop) {
+ return Vala.CCodeBaseModule.get_ccode_nick (prop);
+ }
+
+ private string? get_cname (Vala.Symbol symbol) {
+ return Vala.CCodeBaseModule.get_ccode_name (symbol);
+ }
+
+ private SourceComment? create_comment (Vala.Comment? comment) {
+ if (comment != null) {
+ Vala.SourceReference pos = comment.source_reference;
+ SourceFile file = files.get (pos.file);
+ if (comment is Vala.GirComment) {
+ var tmp = new GirSourceComment (comment.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ if (((Vala.GirComment) comment).return_content != null) {
+ Vala.SourceReference return_pos = ((Vala.GirComment) comment).return_content.source_reference;
+ tmp.return_comment = new SourceComment (((Vala.GirComment) comment).return_content.content, file, return_pos.begin.line, return_pos.begin.column, return_pos.end.line, return_pos.end.column);
+ }
+
+ Vala.MapIterator<string, Vala.Comment> it = ((Vala.GirComment) comment).parameter_iterator ();
+ while (it.next ()) {
+ Vala.Comment vala_param = it.get_value ();
+ Vala.SourceReference param_pos = vala_param.source_reference;
+ var param_comment = new SourceComment (vala_param.content, file, param_pos.begin.line, param_pos.begin.column, param_pos.end.line, param_pos.end.column);
+ tmp.add_parameter_content (it.get_key (), param_comment);
+ }
+ return tmp;
+ } else {
+ return new SourceComment (comment.content, file, pos.begin.line, pos.begin.column, pos.end.line, pos.end.column);
+ }
+ }
+
+ return null;
+ }
+
+ private string get_method_name (Vala.Method element) {
+ if (element is Vala.CreationMethod) {
+ if (element.name == ".new") {
+ return element.parent_symbol.name;
+ } else {
+ return element.parent_symbol.name + "." + element.name;
+ }
+ }
+
+ return element.name;
+ }
+
+ private string? get_quark_macro_name (Vala.ErrorDomain element) {
+ return Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null);
+ }
+
+ private string? get_private_cname (Vala.Class element) {
+ if (element.is_compact) {
+ return null;
+ }
+
+ string? cname = get_cname (element);
+ return (cname != null)? cname + "Private" : null;
+ }
+
+ private string? get_class_macro_name (Vala.Class element) {
+ if (element.is_compact) {
+ return null;
+ }
+
+ return "%s_GET_CLASS".printf (Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null));
+ }
+
+ private string? get_class_type_macro_name (Vala.Class element) {
+ if (element.is_compact) {
+ return null;
+ }
+
+ return "%s_CLASS".printf (Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null));
+ }
+
+ private string? get_is_type_macro_name (Vala.TypeSymbol element) {
+ string? name = Vala.CCodeBaseModule.get_ccode_type_check_function (element);
+ return (name != null && name != "")? name : null;
+ }
+
+ private string? get_is_class_type_macro_name (Vala.TypeSymbol element) {
+ string? name = get_is_type_macro_name (element);
+ return (name != null)? name + "_CLASS" : null;
+ }
+
+ private string? get_type_function_name (Vala.TypeSymbol element) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ return null;
+ }
+
+ return "%s_get_type".printf (Vala.CCodeBaseModule.get_ccode_lower_case_name (element, null));
+ }
+
+ private string? get_type_macro_name (Vala.TypeSymbol element) {
+ if ((element is Vala.Class && ((Vala.Class) element).is_compact) || element is Vala.ErrorDomain || element is Vala.Delegate) {
+ return null;
+ }
+
+ return Vala.CCodeBaseModule.get_ccode_type_id (element);
+ }
+
+ private string? get_type_cast_macro_name (Vala.TypeSymbol element) {
+ if ((element is Vala.Class && !((Vala.Class) element).is_compact) || element is Vala.Interface) {
+ return Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null);
+ } else {
+ return null;
+ }
+ }
+
+ private string? get_interface_macro_name (Vala.Interface element) {
+ return "%s_GET_INTERFACE".printf (Vala.CCodeBaseModule.get_ccode_upper_case_name (element, null));
+ }
+
+ private string get_quark_function_name (Vala.ErrorDomain element) {
+ return Vala.CCodeBaseModule.get_ccode_lower_case_prefix (element) + "quark";
+ }
+
+ private PackageMetaData? get_package_meta_data (Package pkg) {
+ foreach (PackageMetaData data in packages) {
+ if (data.package == pkg) {
+ return data;
+ }
+ }
+
+ return null;
+ }
+
+ private PackageMetaData register_package (Package package) {
+ PackageMetaData meta_data = new PackageMetaData (package);
+ tree.add_package (package);
+ packages.add (meta_data);
+ return meta_data;
+ }
+
+ private SourceFile register_source_file (PackageMetaData meta_data, Vala.SourceFile source_file) {
+ SourceFile file = new SourceFile (meta_data.package, source_file.get_relative_filename (), source_file.get_csource_filename (), source_file);
+ files.set (source_file, file);
+
+ meta_data.register_source_file (source_file);
+ return file;
+ }
+
+ private SourceFile? get_source_file (Vala.Symbol symbol) {
+ Vala.SourceReference source_ref = symbol.source_reference;
+ if (source_ref == null) {
+ return null;
+ }
+
+ SourceFile? file = files.get (source_ref.file);
+ assert (file != null);
+ return file;
+ }
+
+ private Package? find_package_for_file (Vala.SourceFile source_file) {
+ foreach (PackageMetaData pkg in this.packages) {
+ if (pkg.is_package_for_file (source_file)) {
+ return pkg.package;
+ }
+ }
+
+ return null;
+ }
+
+
+ private Namespace get_namespace (Package pkg, Vala.Symbol symbol, SourceFile? file) {
+ // Find the closest namespace in our vala-tree
+ Vala.Symbol namespace_symbol = symbol;
+ while (!(namespace_symbol is Vala.Namespace)) {
+ namespace_symbol = namespace_symbol.parent_symbol;
+ }
+
+ PackageMetaData? meta_data = get_package_meta_data (pkg);
+ assert (meta_data != null);
+
+ return meta_data.get_namespace ((Vala.Namespace) namespace_symbol, file);
+ }
+
+ private MethodBindingType get_method_binding_type (Vala.Method element) {
+ if (element.is_inline) {
+ return MethodBindingType.INLINE;
+ } else if (element.is_abstract) {
+ return MethodBindingType.ABSTRACT;
+ } else if (element.is_virtual) {
+ return MethodBindingType.VIRTUAL;
+ } else if (element.overrides) {
+ return MethodBindingType.OVERRIDE;
+ } else if (element.is_inline) {
+ return MethodBindingType.INLINE;
+ } else if (element.binding != Vala.MemberBinding.INSTANCE) {
+ return MethodBindingType.STATIC;
+ }
+ return MethodBindingType.UNMODIFIED;
+ }
+
+
+ private SymbolAccessibility get_access_modifier(Vala.Symbol symbol) {
+ switch (symbol.access) {
+ case Vala.SymbolAccessibility.PROTECTED:
+ return SymbolAccessibility.PROTECTED;
+
+ case Vala.SymbolAccessibility.INTERNAL:
+ return SymbolAccessibility.INTERNAL;
+
+ case Vala.SymbolAccessibility.PRIVATE:
+ return SymbolAccessibility.PRIVATE;
+
+ case Vala.SymbolAccessibility.PUBLIC:
+ return SymbolAccessibility.PUBLIC;
+
+ default:
+ error ("Unknown symbol accessibility modifier found");
+ }
+ }
+
+ private PropertyAccessorType get_property_accessor_type (Vala.PropertyAccessor element) {
+ if (element.construction) {
+ return PropertyAccessorType.CONSTRUCT;
+ } else if (element.writable) {
+ return PropertyAccessorType.SET;
+ } else if (element.readable) {
+ return PropertyAccessorType.GET;
+ }
+
+ error ("Unknown symbol accessibility type");
+ }
+
+ private bool type_reference_pass_ownership (Vala.DataType? element) {
+ if (element == null) {
+ return false;
+ }
+
+ weak Vala.CodeNode? node = element.parent_node;
+ if (node == null) {
+ return false;
+ }
+ if (node is Vala.Parameter) {
+ return (((Vala.Parameter)node).direction == Vala.ParameterDirection.IN &&
+ ((Vala.Parameter)node).variable_type.value_owned);
+ }
+ if (node is Vala.Property) {
+ return ((Vala.Property)node).property_type.value_owned;
+ }
+
+ return false;
+ }
+
+ private bool is_type_reference_unowned (Vala.DataType? element) {
+ if (element == null) {
+ return false;
+ }
+
+ // non ref counted types are weak, not unowned
+ if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) {
+ return false;
+ }
+
+ // FormalParameters are weak by default
+ return (element.parent_node is Vala.Parameter == false)? element.is_weak () : false;
+ }
+
+ private bool is_type_reference_owned (Vala.DataType? element) {
+ if (element == null) {
+ return false;
+ }
+
+ weak Vala.CodeNode parent = element.parent_node;
+
+ // parameter:
+ if (parent is Vala.Parameter) {
+ if (((Vala.Parameter)parent).direction != Vala.ParameterDirection.IN) {
+ return false;
+ }
+ return ((Vala.Parameter)parent).variable_type.value_owned;
+ }
+
+ return false;
+ }
+
+ private bool is_type_reference_weak (Vala.DataType? element) {
+ if (element == null) {
+ return false;
+ }
+
+ // non ref counted types are unowned, not weak
+ if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) {
+ return false;
+ }
+
+ // FormalParameters are weak by default
+ return (element.parent_node is Vala.Parameter == false)? element.is_weak () : false;
+ }
+
+ private Ownership get_type_reference_ownership (Vala.DataType? element) {
+ if (is_type_reference_owned (element)) {
+ return Ownership.OWNED;
+ } else if (is_type_reference_weak (element)) {
+ return Ownership.WEAK;
+ } else if (is_type_reference_unowned (element)) {
+ return Ownership.UNOWNED;
+ }
+
+ return Ownership.DEFAULT;
+ }
+
+ private Ownership get_property_ownership (Vala.PropertyAccessor element) {
+ if (element.value_type.value_owned) {
+ return Ownership.OWNED;
+ }
+
+ // the exact type (weak, unowned) does not matter
+ return Ownership.UNOWNED;
+ }
+
+ private PropertyBindingType get_property_binding_type (Vala.Property element) {
+ if (element.is_abstract) {
+ return PropertyBindingType.ABSTRACT;
+ } else if (element.is_virtual) {
+ return PropertyBindingType.VIRTUAL;
+ } else if (element.overrides) {
+ return PropertyBindingType.OVERRIDE;
+ }
+
+ return PropertyBindingType.UNMODIFIED;
+ }
+
+ private FormalParameterType get_formal_parameter_type (Vala.Parameter element) {
+ if (element.direction == Vala.ParameterDirection.OUT) {
+ return FormalParameterType.OUT;
+ } else if (element.direction == Vala.ParameterDirection.REF) {
+ return FormalParameterType.REF;
+ } else if (element.direction == Vala.ParameterDirection.IN) {
+ return FormalParameterType.IN;
+ }
+
+ error ("Unknown formal parameter type");
+ }
+
+
+ //
+ // Vala tree creation:
+ //
+
+ private string get_package_name (string path) {
+ string file_name = Path.get_basename (path);
+ return file_name.substring (0, file_name.last_index_of_char ('.'));
+ }
+
+ private bool add_package (Vala.CodeContext context, string pkg) {
+ // ignore multiple occurences of the same package
+ if (context.has_package (pkg)) {
+ return true;
+ }
+
+ string vapi_name = pkg + ".vapi";
+ string gir_name = pkg + ".gir";
+ foreach (string source_file in settings.source_files) {
+ string basename = Path.get_basename (source_file);
+ if (basename == vapi_name || basename == gir_name) {
+ return true;
+ }
+ }
+
+
+ var package_path = context.get_vapi_path (pkg) ?? context.get_gir_path (pkg);
+ if (package_path == null) {
+ Vala.Report.error (null, "Package `%s' not found in specified Vala API directories or GObject-Introspection GIR directories".printf (pkg));
+ return false;
+ }
+
+ context.add_package (pkg);
+
+ var vfile = new Vala.SourceFile (context, Vala.SourceFileType.PACKAGE, package_path);
+ context.add_source_file (vfile);
+ Package vdpkg = new Package (pkg, true, null);
+ register_source_file (register_package (vdpkg), vfile);
+
+ add_deps (context, Path.build_filename (Path.get_dirname (package_path), "%s.deps".printf (pkg)), pkg);
+ return true;
+ }
+
+ private void add_deps (Vala.CodeContext context, string file_path, string pkg_name) {
+ if (FileUtils.test (file_path, FileTest.EXISTS)) {
+ try {
+ string deps_content;
+ ulong deps_len;
+ FileUtils.get_contents (file_path, out deps_content, out deps_len);
+ foreach (string dep in deps_content.split ("\n")) {
+ dep = dep.strip ();
+ if (dep != "") {
+ if (!add_package (context, dep)) {
+ Vala.Report.error (null, "%s, dependency of %s, not found in specified Vala API directories".printf (dep, pkg_name));
+ }
+ }
+ }
+ } catch (FileError e) {
+ Vala.Report.error (null, "Unable to read dependency file: %s".printf (e.message));
+ }
+ }
+ }
+
+ /**
+ * Adds the specified packages to the list of used packages.
+ *
+ * @param context The code context
+ * @param packages a list of package names
+ */
+ private void add_depencies (Vala.CodeContext context, string[] packages) {
+ foreach (string package in packages) {
+ if (!add_package (context, package)) {
+ Vala.Report.error (null, "Package `%s' not found in specified Vala API directories or GObject-Introspection GIR directories".printf (package));
+ }
+ }
+ }
+
+ /**
+ * Add the specified source file to the context. Only .vala, .vapi, .gs,
+ * and .c files are supported.
+ */
+ private void add_documented_files (Vala.CodeContext context, string[] sources) {
+ if (sources == null) {
+ return;
+ }
+
+ foreach (string source in sources) {
+ if (FileUtils.test (source, FileTest.EXISTS)) {
+ var rpath = realpath (source);
+ if (source.has_suffix (".vala") || source.has_suffix (".gs")) {
+ var source_file = new Vala.SourceFile (context, Vala.SourceFileType.SOURCE, rpath);
+
+ if (source_package == null) {
+ source_package = register_package (new Package (settings.pkg_name, false, null));
+ }
+
+ register_source_file (source_package, source_file);
+
+ if (context.profile == Vala.Profile.GOBJECT) {
+ // import the GLib namespace by default (namespace of backend-specific standard library)
+ var ns_ref = new Vala.UsingDirective (new Vala.UnresolvedSymbol (null, "GLib", null));
+ source_file.add_using_directive (ns_ref);
+ context.root.add_using_directive (ns_ref);
+ }
+
+ context.add_source_file (source_file);
+ } else if (source.has_suffix (".vapi") || source.has_suffix (".gir")) {
+ string file_name = get_package_name (source);
+
+ var vfile = new Vala.SourceFile (context, Vala.SourceFileType.PACKAGE, rpath);
+ context.add_source_file (vfile);
+
+ if (source_package == null) {
+ source_package = register_package (new Package (settings.pkg_name, false, null));
+ }
+
+ register_source_file (source_package, vfile);
+
+ add_deps (context, Path.build_filename (Path.get_dirname (source), "%s.deps".printf (file_name)), file_name);
+ } else if (source.has_suffix (".c")) {
+ context.add_c_source_file (rpath);
+ tree.add_external_c_files (rpath);
+ } else {
+ Vala.Report.error (null, "%s is not a supported source file type. Only .vala, .vapi, .gs, and .c files are supported.".printf (source));
+ }
+ } else {
+ Vala.Report.error (null, "%s not found".printf (source));
+ }
+ }
+ }
+
+ private Vala.CodeContext create_valac_tree (Settings settings) {
+ // init context:
+ var context = new Vala.CodeContext ();
+ Vala.CodeContext.push (context);
+
+
+ // settings:
+ context.experimental = settings.experimental;
+ context.experimental_non_null = settings.experimental || settings.experimental_non_null;
+ context.vapi_directories = settings.vapi_directories;
+ context.report.enable_warnings = settings.verbose;
+ context.metadata_directories = settings.metadata_directories;
+ context.gir_directories = settings.gir_directories;
+
+ if (settings.basedir == null) {
+ context.basedir = realpath (".");
+ } else {
+ context.basedir = realpath (settings.basedir);
+ }
+
+ if (settings.directory != null) {
+ context.directory = realpath (settings.directory);
+ } else {
+ context.directory = context.basedir;
+ }
+
+
+ // add default packages:
+ if (settings.profile == "gobject-2.0" || settings.profile == "gobject" || settings.profile == null) {
+ context.profile = Vala.Profile.GOBJECT;
+ context.add_define ("GOBJECT");
+ }
+
+
+ if (settings.defines != null) {
+ foreach (string define in settings.defines) {
+ context.add_define (define);
+ }
+ }
+
+ if (context.profile == Vala.Profile.GOBJECT) {
+ int glib_major = 2;
+ int glib_minor = 12;
+
+ context.target_glib_major = glib_major;
+ context.target_glib_minor = glib_minor;
+ if (context.target_glib_major != 2) {
+ Vala.Report.error (null, "This version of valac only supports GLib 2");
+ }
+
+ if (settings.target_glib != null && settings.target_glib.scanf ("%d.%d", out glib_major, out glib_minor) != 2) {
+ Vala.Report.error (null, "Invalid format for --target-glib");
+ }
+
+ context.target_glib_major = glib_major;
+ context.target_glib_minor = glib_minor;
+ if (context.target_glib_major != 2) {
+ Vala.Report.error (null, "This version of valac only supports GLib 2");
+ }
+
+ for (int i = 16; i <= glib_minor; i += 2) {
+ context.add_define ("GLIB_2_%d".printf (i));
+ }
+
+ // default packages
+ if (!this.add_package (context, "glib-2.0")) { //
+ Vala.Report.error (null, "glib-2.0 not found in specified Vala API directories");
+ }
+
+ if (!this.add_package (context, "gobject-2.0")) { //
+ Vala.Report.error (null, "gobject-2.0 not found in specified Vala API directories");
+ }
+ }
+
+ // add user defined files:
+ add_depencies (context, settings.packages);
+ if (reporter.errors > 0) {
+ return context;
+ }
+
+ add_documented_files (context, settings.source_files);
+ if (reporter.errors > 0) {
+ return context;
+ }
+
+
+ // parse vala-code:
+ Vala.Parser parser = new Vala.Parser ();
+
+ parser.parse (context);
+ if (context.report.get_errors () > 0) {
+ return context;
+ }
+
+ // parse gir:
+ Vala.GirParser gir_parser = new Vala.GirParser ();
+
+ gir_parser.parse (context);
+ if (context.report.get_errors () > 0) {
+ return context;
+ }
+
+
+
+ // check context:
+ context.check ();
+ if (context.report.get_errors () > 0) {
+ return context;
+ }
+
+ return context;
+ }
+
+
+
+ //
+ // Valadoc tree creation:
+ //
+
+ private void process_children (Api.Node node, Vala.CodeNode element) {
+ Api.Node old_node = current_node;
+ current_node = node;
+ element.accept_children (this);
+ current_node = old_node;
+ }
+
+ private Api.Node get_parent_node_for (Vala.Symbol element) {
+ if (current_node != null) {
+ return current_node;
+ }
+
+ Vala.SourceFile vala_source_file = element.source_reference.file;
+ Package package = find_package_for_file (vala_source_file);
+ SourceFile? source_file = get_source_file (element);
+
+ return get_namespace (package, element, source_file);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_namespace (Vala.Namespace element) {
+ element.accept_children (this);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_class (Vala.Class element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ bool is_basic_type = element.base_class == null && element.name == "string";
+
+ Class node = new Class (parent, file, element.name, get_access_modifier (element), comment, get_cname (element), get_private_cname (element), get_class_macro_name (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_class_type_macro_name (element), get_is_class_type_macro_name (element), Vala.GDBusModule.get_dbus_name (element), get_ccode_type_id (element), get_param_spec_function (element), get_ref_function (element), get_unref_function (element), get_free_function_name (element), get_finalize_function_name (element), get_take_value_function (element), get_get_value_function (element), get_set_value_function (element), element.is_fundamental (), element.is_abstract, is_basic_type, element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ // relations
+ foreach (Vala.DataType vala_type_ref in element.get_base_types ()) {
+ var type_ref = create_type_reference (vala_type_ref, node, node);
+
+ if (vala_type_ref.data_type is Vala.Interface) {
+ node.add_interface (type_ref);
+ } else if (vala_type_ref.data_type is Vala.Class) {
+ node.base_type = type_ref;
+ }
+ }
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+
+ // save GLib.Error
+ if (glib_error == null && node.get_full_name () == "GLib.Error") {
+ glib_error = node;
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_interface (Vala.Interface element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Interface node = new Interface (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), get_type_macro_name (element), get_is_type_macro_name (element), get_type_cast_macro_name (element), get_type_function_name (element), get_interface_macro_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ // prerequisites:
+ foreach (Vala.DataType vala_type_ref in element.get_prerequisites ()) {
+ TypeReference type_ref = create_type_reference (vala_type_ref, node, node);
+ if (vala_type_ref.data_type is Vala.Interface) {
+ node.add_interface (type_ref);
+ } else {
+ node.base_type = type_ref;
+ }
+ }
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_struct (Vala.Struct element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ bool is_basic_type = element.base_type == null && (element.is_boolean_type () || element.is_floating_type () || element.is_integer_type ());
+
+ Struct node = new Struct (parent, file, element.name, get_access_modifier (element), comment, get_cname (element), get_type_macro_name (element), get_type_function_name (element), get_ccode_type_id (element), get_dup_function (element), get_free_function (element), is_basic_type, element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ // parent type:
+ Vala.ValueType? basetype = element.base_type as Vala.ValueType;
+ if (basetype != null) {
+ node.base_type = create_type_reference (basetype, node, node);
+ }
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_field (Vala.Field element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Field node = new Field (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element.binding == Vala.MemberBinding.STATIC, element.is_volatile, element);
+ node.field_type = create_type_reference (element.variable_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_property (Vala.Property element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Property node = new Property (parent, file, element.name, get_access_modifier(element), comment, get_nick (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.is_dbus_visible (element), get_property_binding_type (element), element);
+ node.property_type = create_type_reference (element.property_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ // Process property type
+ if (element.get_accessor != null) {
+ var accessor = element.get_accessor;
+ node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ }
+
+ if (element.set_accessor != null) {
+ var accessor = element.set_accessor;
+ node.setter = new PropertyAccessor (node, file, element.name, get_access_modifier (accessor), get_cname (accessor), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor);
+ }
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_creation_method (Vala.CreationMethod element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Method node = new Method (parent, file, get_method_name (element), get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.dbus_result_name (element), (element.coroutine)? get_finish_name (element) : null, get_method_binding_type (element), element.coroutine, Vala.GDBusServerModule.is_dbus_visible (element), element is Vala.CreationMethod, element);
+ node.return_type = create_type_reference (element.return_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_method (Vala.Method element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Method node = new Method (parent, file, get_method_name (element), get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.dbus_result_name (element), (element.coroutine)? get_finish_name (element) : null, get_method_binding_type (element), element.coroutine, Vala.GDBusServerModule.is_dbus_visible (element), element is Vala.CreationMethod, element);
+ node.return_type = create_type_reference (element.return_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_signal (Vala.Signal element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Api.Signal node = new Api.Signal (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.is_dbus_visible (element), element.is_virtual, element);
+ node.return_type = create_type_reference (element.return_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_delegate (Vala.Delegate element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Delegate node = new Delegate (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), !element.has_target, element);
+ node.return_type = create_type_reference (element.return_type, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum (Vala.Enum element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Symbol node = new Enum (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), get_type_macro_name (element), get_type_function_name (element), element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_enum_value (Vala.EnumValue element) {
+ Api.Enum parent = (Enum) get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Symbol node = new Api.EnumValue (parent, file, element.name, comment, get_cname (element), element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_constant (Vala.Constant element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Constant node = new Constant (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element);
+ node.constant_type = create_type_reference (element.type_reference, node, node);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_domain (Vala.ErrorDomain element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ SourceComment? comment = create_comment (element.comment);
+
+ Symbol node = new ErrorDomain (parent, file, element.name, get_access_modifier (element), comment, get_cname (element), get_quark_macro_name (element), get_quark_function_name (element), Vala.GDBusModule.get_dbus_name (element), element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_error_code (Vala.ErrorCode element) {
+ Api.ErrorDomain parent = (ErrorDomain) get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+ if (file == null) {
+ file = parent.get_source_file ();
+ }
+
+ SourceComment? comment = create_comment (element.comment);
+
+ Symbol node = new Api.ErrorCode (parent, file, element.name, comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), element);
+ symbol_map.set (element, node);
+ parent.add_child (node);
+
+ process_attributes (node, element.attributes);
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_type_parameter (Vala.TypeParameter element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+
+ Symbol node = new TypeParameter (parent, file, element.name, element);
+ parent.add_child (node);
+
+ process_children (node, element);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public override void visit_formal_parameter (Vala.Parameter element) {
+ Api.Node parent = get_parent_node_for (element);
+ SourceFile? file = get_source_file (element);
+
+ FormalParameter node = new FormalParameter (parent, file, element.name, get_access_modifier(element), get_formal_parameter_type (element), element.ellipsis, element);
+ node.parameter_type = create_type_reference (element.variable_type, node, node);
+ parent.add_child (node);
+
+ process_children (node, element);
+ }
+
+
+ //
+ // startpoint:
+ //
+
+ public Api.Tree? build (Settings settings, ErrorReporter reporter) {
+ this.settings = settings;
+ this.reporter = reporter;
+
+ this.tree = new Api.Tree (reporter, settings);
+ var context = create_valac_tree (settings);
+ this.tree.data = context;
+
+ reporter.warnings_offset = context.report.get_warnings ();
+ reporter.errors_offset = context.report.get_errors ();
+
+ if (context == null) {
+ return null;
+ }
+
+ // TODO: Register all packages here
+ // register packages included by gir-files
+ foreach (Vala.SourceFile vfile in context.get_source_files ()) {
+ if (vfile.file_type == Vala.SourceFileType.PACKAGE && vfile.get_nodes ().size > 0 && files.contains (vfile) == false) {
+ Package vdpkg = new Package (get_package_name (vfile.filename), true, null);
+ register_source_file (register_package (vdpkg), vfile);
+ }
+ }
+
+ context.accept(this);
+
+ return (reporter.errors == 0)? tree : null;
+ }
+}
+
+
diff --git a/src/driver/Makefile.am b/src/driver/Makefile.am
index 4ed5eef0ae..2fd93983ac 100644
--- a/src/driver/Makefile.am
+++ b/src/driver/Makefile.am
@@ -46,6 +46,10 @@ if HAVE_LIBVALA_0_18_X
DRIVER_0_18_X_DIR = 0.18.x
endif
+if HAVE_LIBVALA_0_20_X
+DRIVER_0_20_X_DIR = 0.20.x
+endif
+
SUBDIRS = \
$(DRIVER_0_10_X_DIR) \
@@ -53,6 +57,7 @@ SUBDIRS = \
$(DRIVER_0_14_X_DIR) \
$(DRIVER_0_16_X_DIR) \
$(DRIVER_0_18_X_DIR) \
+ $(DRIVER_0_20_X_DIR) \
$(NULL)
diff --git a/src/libvaladoc/moduleloader.vala b/src/libvaladoc/moduleloader.vala
index 1571d51ebd..2dc8baae7e 100644
--- a/src/libvaladoc/moduleloader.vala
+++ b/src/libvaladoc/moduleloader.vala
@@ -153,7 +153,8 @@ public class Valadoc.ModuleLoader : Object {
DriverMetaData (0, 11, 0, 12, "0.12.x"),
DriverMetaData (0, 13, 0, 14, "0.14.x"),
DriverMetaData (0, 15, 0, 16, "0.16.x"),
- DriverMetaData (0, 17, 0, 18, "0.18.x")
+ DriverMetaData (0, 17, 0, 18, "0.18.x"),
+ DriverMetaData (0, 19, 0, 20, "0.20.x")
};
diff --git a/tests/Makefile.am b/tests/Makefile.am
index c76456a3ec..8ef21f1a80 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -28,6 +28,7 @@ TESTS = \
drivers/driver-0-14.vala \
drivers/driver-0-16.vala \
drivers/driver-0-18.vala \
+ drivers/driver-0-20.vala \
$(NULL)
check-TESTS: $(TESTS)
diff --git a/tests/drivers/driver-0-20.vala b/tests/drivers/driver-0-20.vala
new file mode 100644
index 0000000000..787cb8553b
--- /dev/null
+++ b/tests/drivers/driver-0-20.vala
@@ -0,0 +1,6 @@
+
+
+public static void main () {
+ test_driver ("../../src/driver/0.20.x/.libs");
+}
+
|
ca2f1678d75d9d42867f2124fa3e7dfcf1c367f7
|
hbase
|
HBASE-2757. Fix flaky TestFromClientSide test by- forcing region assignment--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@956716 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/CHANGES.txt b/CHANGES.txt
index 6bba3feb2be6..a0cfef66001f 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -403,6 +403,7 @@ Release 0.21.0 - Unreleased
HBASE-2760 Fix MetaScanner TableNotFoundException when scanning starting at
the first row in a table.
HBASE-1025 Reconstruction log playback has no bounds on memory used
+ HBASE-2757 Fix flaky TestFromClientSide test by forcing region assignment
IMPROVEMENTS
HBASE-1760 Cleanup TODOs in HTable
diff --git a/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java b/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
index 74a0c63c9a96..fc7b2afa7132 100644
--- a/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
+++ b/src/test/java/org/apache/hadoop/hbase/client/TestFromClientSide.java
@@ -3637,7 +3637,13 @@ public void testRegionCachePreWarm() throws Exception {
// create many regions for the table.
TEST_UTIL.createMultiRegions(table, FAMILY);
-
+ // This count effectively waits until the regions have been
+ // fully assigned
+ TEST_UTIL.countRows(table);
+ table.getConnection().clearRegionCache();
+ assertEquals("Clearing cache should have 0 cached ", 0,
+ HConnectionManager.getCachedRegionCount(conf, TABLENAME));
+
// A Get is suppose to do a region lookup request
Get g = new Get(Bytes.toBytes("aaa"));
table.get(g);
|
8c3a7e4a7dc3a575720b6e812fc91b38cdd211c5
|
hbase
|
HBASE-8703 [WINDOWS] Timed-out processes exit- with non-zero code causing HealthChecker to report incorrectly. ADDENDUM- patch to fix flaky test--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1499047 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestNodeHealthCheckChore.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestNodeHealthCheckChore.java
index 9f36e7e5d50f..17036bec5d18 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestNodeHealthCheckChore.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestNodeHealthCheckChore.java
@@ -25,6 +25,7 @@
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
+import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -55,32 +56,38 @@ public void cleanUp() throws IOException {
}
@Test
- public void testHealthChecker() throws Exception {
+ public void testHealthCheckerSuccess() throws Exception {
+ String normalScript = "echo \"I am all fine\"";
+ healthCheckerTest(normalScript, HealthCheckerExitStatus.SUCCESS);
+ }
+
+ @Test
+ public void testHealthCheckerFail() throws Exception {
+ String errorScript = "echo ERROR" + eol + "echo \"Node not healthy\"";
+ healthCheckerTest(errorScript, HealthCheckerExitStatus.FAILED);
+ }
+
+ @Test
+ public void testHealthCheckerTimeout() throws Exception {
+ String timeOutScript = "sleep 4" + eol + "echo \"I am fine\"";
+ healthCheckerTest(timeOutScript, HealthCheckerExitStatus.TIMED_OUT);
+ }
+
+ public void healthCheckerTest(String script, HealthCheckerExitStatus expectedStatus)
+ throws Exception {
Configuration config = getConfForNodeHealthScript();
config.addResource(healthScriptFile.getName());
String location = healthScriptFile.getAbsolutePath();
long timeout = config.getLong(HConstants.HEALTH_SCRIPT_TIMEOUT, 2000);
+
HealthChecker checker = new HealthChecker();
checker.init(location, timeout);
- String normalScript = "echo \"I am all fine\"";
- createScript(normalScript, true);
+ createScript(script, true);
HealthReport report = checker.checkHealth();
+ assertEquals(expectedStatus, report.getStatus());
LOG.info("Health Status:" + report.getHealthReport());
- assertEquals(HealthCheckerExitStatus.SUCCESS, report.getStatus());
-
- String errorScript = "echo ERROR" + eol + "echo \"Server not healthy\"";
- createScript(errorScript, true);
- report = checker.checkHealth();
- LOG.info("Health Status:" + report.getHealthReport());
- assertEquals(HealthCheckerExitStatus.FAILED, report.getStatus());
-
- String timeOutScript = "sleep 4" + eol + "echo \"I am fine\"";
- createScript(timeOutScript, true);
- report = checker.checkHealth();
- LOG.info("Health Status:" + report.getHealthReport());
- assertEquals(HealthCheckerExitStatus.TIMED_OUT, report.getStatus());
this.healthScriptFile.delete();
}
@@ -130,7 +137,8 @@ private Configuration getConfForNodeHealthScript() throws IOException {
throw new IOException("Failed mkdirs " + tempDir);
}
}
- String scriptName = Shell.WINDOWS ? "HealthScript.cmd" : "HealthScript.sh";
+ String scriptName = "HealthScript" + UUID.randomUUID().toString()
+ + (Shell.WINDOWS ? ".cmd" : ".sh");
healthScriptFile = new File(tempDir.getAbsolutePath(), scriptName);
conf.set(HConstants.HEALTH_SCRIPT_LOC, healthScriptFile.getAbsolutePath());
conf.setLong(HConstants.HEALTH_FAILURE_THRESHOLD, 3);
|
df18e9173dfbf6aa97852a25db100294b72e6eb5
|
spring-framework
|
Revised- PersistenceExceptionTranslationInterceptor to lazily retrieve- PersistenceExceptionTranslator beans on demand--Issue: SPR-10894-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/spring-tx/src/main/java/org/springframework/dao/support/PersistenceExceptionTranslationInterceptor.java b/spring-tx/src/main/java/org/springframework/dao/support/PersistenceExceptionTranslationInterceptor.java
index b486dccdfaa6..bca8154dc53c 100644
--- a/spring-tx/src/main/java/org/springframework/dao/support/PersistenceExceptionTranslationInterceptor.java
+++ b/spring-tx/src/main/java/org/springframework/dao/support/PersistenceExceptionTranslationInterceptor.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -47,10 +47,12 @@
public class PersistenceExceptionTranslationInterceptor
implements MethodInterceptor, BeanFactoryAware, InitializingBean {
- private PersistenceExceptionTranslator persistenceExceptionTranslator;
+ private volatile PersistenceExceptionTranslator persistenceExceptionTranslator;
private boolean alwaysTranslate = false;
+ private ListableBeanFactory beanFactory;
+
/**
* Create a new PersistenceExceptionTranslationInterceptor.
@@ -63,10 +65,11 @@ public PersistenceExceptionTranslationInterceptor() {
/**
* Create a new PersistenceExceptionTranslationInterceptor
* for the given PersistenceExceptionTranslator.
- * @param persistenceExceptionTranslator the PersistenceExceptionTranslator to use
+ * @param pet the PersistenceExceptionTranslator to use
*/
- public PersistenceExceptionTranslationInterceptor(PersistenceExceptionTranslator persistenceExceptionTranslator) {
- setPersistenceExceptionTranslator(persistenceExceptionTranslator);
+ public PersistenceExceptionTranslationInterceptor(PersistenceExceptionTranslator pet) {
+ Assert.notNull(pet, "PersistenceExceptionTranslator must not be null");
+ this.persistenceExceptionTranslator = pet;
}
/**
@@ -76,7 +79,8 @@ public PersistenceExceptionTranslationInterceptor(PersistenceExceptionTranslator
* PersistenceExceptionTranslators from
*/
public PersistenceExceptionTranslationInterceptor(ListableBeanFactory beanFactory) {
- this.persistenceExceptionTranslator = detectPersistenceExceptionTranslators(beanFactory);
+ Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
+ this.beanFactory = beanFactory;
}
@@ -87,7 +91,6 @@ public PersistenceExceptionTranslationInterceptor(ListableBeanFactory beanFactor
* @see #detectPersistenceExceptionTranslators
*/
public void setPersistenceExceptionTranslator(PersistenceExceptionTranslator pet) {
- Assert.notNull(pet, "PersistenceExceptionTranslator must not be null");
this.persistenceExceptionTranslator = pet;
}
@@ -115,19 +118,37 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
throw new IllegalArgumentException(
"Cannot use PersistenceExceptionTranslator autodetection without ListableBeanFactory");
}
- this.persistenceExceptionTranslator =
- detectPersistenceExceptionTranslators((ListableBeanFactory) beanFactory);
+ this.beanFactory = (ListableBeanFactory) beanFactory;
}
}
@Override
public void afterPropertiesSet() {
- if (this.persistenceExceptionTranslator == null) {
+ if (this.persistenceExceptionTranslator == null && this.beanFactory == null) {
throw new IllegalArgumentException("Property 'persistenceExceptionTranslator' is required");
}
}
+ @Override
+ public Object invoke(MethodInvocation mi) throws Throwable {
+ try {
+ return mi.proceed();
+ }
+ catch (RuntimeException ex) {
+ // Let it throw raw if the type of the exception is on the throws clause of the method.
+ if (!this.alwaysTranslate && ReflectionUtils.declaresException(mi.getMethod(), ex.getClass())) {
+ throw ex;
+ }
+ else {
+ if (this.persistenceExceptionTranslator == null) {
+ this.persistenceExceptionTranslator = detectPersistenceExceptionTranslators(this.beanFactory);
+ }
+ throw DataAccessUtils.translateIfNecessary(ex, this.persistenceExceptionTranslator);
+ }
+ }
+ }
+
/**
* Detect all PersistenceExceptionTranslators in the given BeanFactory.
* @param beanFactory the ListableBeanFactory to obtaining all
@@ -140,10 +161,6 @@ protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(L
// Find all translators, being careful not to activate FactoryBeans.
Map<String, PersistenceExceptionTranslator> pets = BeanFactoryUtils.beansOfTypeIncludingAncestors(
beanFactory, PersistenceExceptionTranslator.class, false, false);
- if (pets.isEmpty()) {
- throw new IllegalStateException(
- "No persistence exception translators found in bean factory. Cannot perform exception translation.");
- }
ChainedPersistenceExceptionTranslator cpet = new ChainedPersistenceExceptionTranslator();
for (PersistenceExceptionTranslator pet : pets.values()) {
cpet.addDelegate(pet);
@@ -151,21 +168,4 @@ protected PersistenceExceptionTranslator detectPersistenceExceptionTranslators(L
return cpet;
}
-
- @Override
- public Object invoke(MethodInvocation mi) throws Throwable {
- try {
- return mi.proceed();
- }
- catch (RuntimeException ex) {
- // Let it throw raw if the type of the exception is on the throws clause of the method.
- if (!this.alwaysTranslate && ReflectionUtils.declaresException(mi.getMethod(), ex.getClass())) {
- throw ex;
- }
- else {
- throw DataAccessUtils.translateIfNecessary(ex, this.persistenceExceptionTranslator);
- }
- }
- }
-
}
diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java
index fb6259de9321..ef2a0c2236a5 100644
--- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java
+++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.dao.annotation;
+import javax.persistence.PersistenceException;
+
import junit.framework.TestCase;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
@@ -25,38 +27,23 @@
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
-import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.dao.DataAccessException;
+import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterface;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.RepositoryInterfaceImpl;
import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisorTests.StereotypedRepositoryInterfaceImpl;
-import org.springframework.dao.support.ChainedPersistenceExceptionTranslator;
+import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.stereotype.Repository;
/**
- * Unit tests for PersistenceExceptionTranslationPostProcessor. Does not test translation; there are separate unit tests
- * for the Spring AOP Advisor. Just checks whether proxying occurs correctly, as a unit test should.
- *
* @author Rod Johnson
+ * @author Juergen Hoeller
*/
public class PersistenceExceptionTranslationPostProcessorTests extends TestCase {
- public void testFailsWithNoPersistenceExceptionTranslators() {
- GenericApplicationContext gac = new GenericApplicationContext();
- gac.registerBeanDefinition("translator",
- new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class));
- gac.registerBeanDefinition("proxied", new RootBeanDefinition(StereotypedRepositoryInterfaceImpl.class));
- try {
- gac.refresh();
- fail("Should fail with no translators");
- }
- catch (BeansException ex) {
- // Ok
- }
- }
-
public void testProxiesCorrectly() {
GenericApplicationContext gac = new GenericApplicationContext();
gac.registerBeanDefinition("translator",
@@ -66,8 +53,8 @@ public void testProxiesCorrectly() {
gac.registerBeanDefinition("classProxied", new RootBeanDefinition(RepositoryWithoutInterface.class));
gac.registerBeanDefinition("classProxiedAndAdvised",
new RootBeanDefinition(RepositoryWithoutInterfaceAndOtherwiseAdvised.class));
- gac.registerBeanDefinition("chainedTranslator",
- new RootBeanDefinition(ChainedPersistenceExceptionTranslator.class));
+ gac.registerBeanDefinition("myTranslator",
+ new RootBeanDefinition(MyPersistenceExceptionTranslator.class));
gac.registerBeanDefinition("proxyCreator",
BeanDefinitionBuilder.rootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class).
addPropertyValue("order", 50).getBeanDefinition());
@@ -84,8 +71,15 @@ public void testProxiesCorrectly() {
Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised");
assertTrue(AopUtils.isAopProxy(rwi2));
- rwi2.additionalMethod();
+ rwi2.additionalMethod(false);
checkWillTranslateExceptions(rwi2);
+ try {
+ rwi2.additionalMethod(true);
+ fail("Should have thrown DataAccessResourceFailureException");
+ }
+ catch (DataAccessResourceFailureException ex) {
+ assertEquals("my failure", ex.getMessage());
+ }
}
protected void checkWillTranslateExceptions(Object o) {
@@ -99,6 +93,7 @@ protected void checkWillTranslateExceptions(Object o) {
fail("No translation");
}
+
@Repository
public static class RepositoryWithoutInterface {
@@ -106,19 +101,38 @@ public void nameDoesntMatter() {
}
}
+
public interface Additional {
- void additionalMethod();
+ void additionalMethod(boolean fail);
}
+
public static class RepositoryWithoutInterfaceAndOtherwiseAdvised extends StereotypedRepositoryInterfaceImpl
implements Additional {
@Override
- public void additionalMethod() {
+ public void additionalMethod(boolean fail) {
+ if (fail) {
+ throw new PersistenceException("my failure");
+ }
}
}
+
+ public static class MyPersistenceExceptionTranslator implements PersistenceExceptionTranslator {
+
+
+ @Override
+ public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
+ if (ex instanceof PersistenceException) {
+ return new DataAccessResourceFailureException(ex.getMessage());
+ }
+ return null;
+ }
+ }
+
+
@Aspect
public static class LogAllAspect {
|
8dc2374ecad31a3fd1f58bbd61a39611cbb061aa
|
mambu-gmbh$mambu-apis-java
|
Updated for improved testability
|
p
|
https://github.com/mambu-gmbh/mambu-apis-java
|
diff --git a/pom.xml b/pom.xml
index 0d08bc79..9e32da55 100644
--- a/pom.xml
+++ b/pom.xml
@@ -102,5 +102,10 @@
<artifactId>jdo-api</artifactId>
<version>3.0</version>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.8.5</version>
+</dependency>
</dependencies>
</project>
\ No newline at end of file
diff --git a/src/Launch.java b/src/Launch.java
index d1c56617..8327818b 100644
--- a/src/Launch.java
+++ b/src/Launch.java
@@ -26,7 +26,7 @@ public static void main(String[] args) {
try {
MambuAPIService mambu = MambuAPIFactory.crateService("api",
- "api", "demo.mambuonline.com");
+ "api", "demo.mambucloud.com");
// get the org currency
Currency currency = mambu.getCurrency();
diff --git a/src/com/mambu/apisdk/MambuAPIFactory.java b/src/com/mambu/apisdk/MambuAPIFactory.java
index b6dbae2f..adf87c76 100644
--- a/src/com/mambu/apisdk/MambuAPIFactory.java
+++ b/src/com/mambu/apisdk/MambuAPIFactory.java
@@ -1,15 +1,16 @@
package com.mambu.apisdk;
import com.mambu.apisdk.exception.MambuApiException;
+import com.mambu.apisdk.util.RequestExecutorImpl;
/**
- * Factor for creating Mambu API Services
+ * Factory for creating Mambu API Services
*
* @author edanilkis
*
*/
public class MambuAPIFactory {
-
+
/**
* Creates a mambu API services for a given username, password and domain
*
@@ -24,7 +25,8 @@ public class MambuAPIFactory {
*/
public static MambuAPIService crateService(String username,
String password, String domainName) throws MambuApiException {
- return new MambuAPIService(username, password, domainName);
+
+ return new MambuAPIService(username, password, domainName, new RequestExecutorImpl());
}
}
diff --git a/src/com/mambu/apisdk/MambuAPIService.java b/src/com/mambu/apisdk/MambuAPIService.java
index c2012c94..97032296 100644
--- a/src/com/mambu/apisdk/MambuAPIService.java
+++ b/src/com/mambu/apisdk/MambuAPIService.java
@@ -1,21 +1,16 @@
package com.mambu.apisdk;
-import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
import java.math.BigDecimal;
-import java.net.HttpURLConnection;
import java.net.MalformedURLException;
-import java.net.URL;
import java.util.HashMap;
-import org.apache.commons.codec.binary.Base64;
-
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.mambu.accounting.shared.model.GLAccount;
import com.mambu.apisdk.exception.MambuApiException;
+import com.mambu.apisdk.util.RequestExecutor;
+import com.mambu.apisdk.util.RequestExecutor.Method;
import com.mambu.clients.shared.model.Client;
import com.mambu.clients.shared.model.ClientExpanded;
import com.mambu.core.shared.model.Currency;
@@ -31,11 +26,10 @@ public class MambuAPIService {
private String domainName;
private String protocol = "http";
- private String encodedAuthorization;
+ private RequestExecutor executor;
// creat the gson deserializer
- private static GsonBuilder gsonBuilder = new GsonBuilder()
- .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
+ private static GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
/**
* Creates a Mambu API Service class
@@ -48,13 +42,14 @@ public class MambuAPIService {
* based domain name for the tenant (eg: mytenant.mambu.com)
* @throws MambuApiException
*/
- MambuAPIService(String username, String password, String domainName)
+ public MambuAPIService(String username, String password, String domainName, RequestExecutor executor)
throws MambuApiException {
+
this.domainName = domainName;
+ this.executor = executor;
+
+ executor.setAuthorization(username, password);
- // encode the username and password
- String userNamePassword = username + ":" + password;
- encodedAuthorization = new String(Base64.encodeBase64(userNamePassword.getBytes()));
}
/**
@@ -68,10 +63,8 @@ public Client getClient(String clientId) throws MambuApiException {
// create the api call
String urlString = new String(createUrl("clients" + "/" + clientId));
- String method = "GET";
- String jsonResposne = executeRequest(urlString, method);
- Client clientResult = gsonBuilder.create().fromJson(jsonResposne,
- Client.class);
+ String jsonResposne = executeRequest(urlString, Method.GET);
+ Client clientResult = gsonBuilder.create().fromJson(jsonResposne, Client.class);
return clientResult;
}
@@ -92,7 +85,7 @@ public GLAccount getGLAccount(String glCode) throws MambuApiException {
return glAccount;
}
-
+
/**
* Requests the organization currency
*
@@ -104,18 +97,22 @@ public Currency getCurrency() throws MambuApiException {
// create the api call
String url = "currencies";
String urlString = new String(createUrl(url));
- String method = "GET";
- String jsonResponse = executeRequest(urlString, method);
-
- //conver to collection
+ String jsonResponse = executeRequest(urlString, Method.GET);
+
+ // conver to collection
Currency[] currencies = gsonBuilder.create().fromJson(jsonResponse, Currency[].class);
- return currencies[0];
+ if (currencies != null && currencies.length > 0) {
+ return currencies[0];
+ } else {
+ return null;
+ }
}
-
+
/**
- * Requests a gl account by its gl code with a balance over a certain date range
+ * Requests a gl account by its gl code with a balance over a certain date
+ * range
*
* @param glCode
* @return the Mambu gl account
@@ -125,18 +122,23 @@ public GLAccount getGLAccount(String glCode, String fromDate, String toDate) thr
// create the api call
String url = "glaccounts" + "/" + glCode + "?" + "from=" + fromDate + "&to=" + toDate;
-
+
GLAccount glAccount = getGLAccountResponse(url);
return glAccount;
}
+ /**
+ * Returns the gl account response witha given url & parameters
+ *
+ * @param url
+ * @return
+ * @throws MambuApiException
+ */
private GLAccount getGLAccountResponse(String url) throws MambuApiException {
String urlString = new String(createUrl(url));
- String method = "GET";
- String jsonResponse = executeRequest(urlString, method);
- GLAccount glAccount = gsonBuilder.create().fromJson(jsonResponse,
- GLAccount.class);
+ String jsonResponse = executeRequest(urlString, Method.GET);
+ GLAccount glAccount = gsonBuilder.create().fromJson(jsonResponse, GLAccount.class);
return glAccount;
}
@@ -147,19 +149,20 @@ private GLAccount getGLAccountResponse(String url) throws MambuApiException {
* @return the big decimal indicator value
* @throws MambuApiException
*/
- public BigDecimal getIndicator(Indicator indicator)
- throws MambuApiException {
+ public BigDecimal getIndicator(Indicator indicator) throws MambuApiException {
// create the api call
- String urlString = new String(createUrl("indicators" + "/"
- + indicator.toString()));
- String method = "GET";
- String jsonResponse = executeRequest(urlString, method);
- HashMap<String, String> result = gsonBuilder.create().fromJson(
- jsonResponse, new TypeToken<HashMap<String, String>>() {
+ String urlString = new String(createUrl("indicators" + "/" + indicator.toString()));
+ String jsonResponse = executeRequest(urlString, Method.GET);
+ HashMap<String, String> result = gsonBuilder.create().fromJson(jsonResponse,
+ new TypeToken<HashMap<String, String>>() {
}.getType());
- String resultString = result.get(indicator.toString());
- return new BigDecimal(resultString);
+ if (result != null) {
+ String resultString = result.get(indicator.toString());
+ return new BigDecimal(resultString);
+ } else {
+ return null;
+ }
}
@@ -171,15 +174,11 @@ public BigDecimal getIndicator(Indicator indicator)
* @return
* @throws MambuApiException
*/
- public ClientExpanded getClientDetails(String clientId)
- throws MambuApiException {
+ public ClientExpanded getClientDetails(String clientId) throws MambuApiException {
// create the api call
- String urlString = new String(createUrl("clients" + "/" + clientId
- + "?fullDetails=true"));
- String method = "GET";
- String jsonResposne = executeRequest(urlString, method);
- ClientExpanded clientResult = gsonBuilder.create().fromJson(
- jsonResposne, ClientExpanded.class);
+ String urlString = new String(createUrl("clients" + "/" + clientId + "?fullDetails=true"));
+ String jsonResposne = executeRequest(urlString, Method.GET);
+ ClientExpanded clientResult = gsonBuilder.create().fromJson(jsonResposne, ClientExpanded.class);
return clientResult;
}
@@ -197,46 +196,12 @@ public ClientExpanded getClientDetails(String clientId)
* @return
* @throws MambuApiException
*/
- private String executeRequest(String urlString, String method)
- throws MambuApiException {
+ private String executeRequest(String urlString, Method method) throws MambuApiException {
String response = "";
- Integer errorCode = null;
-
try {
- // create the url
- URL url = new URL(urlString);
-
- // set up the connection
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
- connection.setRequestMethod(method);
- connection.setDoOutput(true);
- connection.setRequestProperty("Authorization", "Basic "
- + encodedAuthorization);
-
- // get the status
- int status = ((HttpURLConnection) connection).getResponseCode();
-
- // setup the content
- InputStream content;
-
- // ensure it's an ok response
- if (status != 200) {
- errorCode = status;
- // if there was an error, read the error message
- content = connection.getErrorStream();
- } else {
- content = connection.getInputStream();
- }
-
- response = readStream(content);
-
- // check if we hit an error
- if (errorCode != null) {
- throw new MambuApiException(errorCode, response);
- }
+ response = executor.executeRequest(urlString, method);
} catch (MalformedURLException e) {
throw new MambuApiException(e);
@@ -247,26 +212,6 @@ private String executeRequest(String urlString, String method)
return response;
}
- /**
- * Reads a stream as
- *
- * @param content
- * @return
- * @throws IOException
- */
- private String readStream(InputStream content) throws IOException {
- String response = "";
- // read the response content
- BufferedReader in = new BufferedReader(new InputStreamReader(content));
- String line;
- while ((line = in.readLine()) != null) {
- response += line;
- }
-
- return response;
-
- }
-
/**
* Creates the URL for the cron servlet
*
diff --git a/src/com/mambu/apisdk/exception/MambuApiException.java b/src/com/mambu/apisdk/exception/MambuApiException.java
index d4c221a7..a54691b4 100644
--- a/src/com/mambu/apisdk/exception/MambuApiException.java
+++ b/src/com/mambu/apisdk/exception/MambuApiException.java
@@ -1,7 +1,7 @@
package com.mambu.apisdk.exception;
/**
- * Encapculation for exceptions which may occur when calling Mambu APIs
+ * Encapsulation for exceptions which may occur when calling Mambu APIs
*
* @author edanilkis
*
diff --git a/src/com/mambu/apisdk/DateUtils.java b/src/com/mambu/apisdk/util/DateUtils.java
similarity index 92%
rename from src/com/mambu/apisdk/DateUtils.java
rename to src/com/mambu/apisdk/util/DateUtils.java
index 9c88a078..8698706c 100644
--- a/src/com/mambu/apisdk/DateUtils.java
+++ b/src/com/mambu/apisdk/util/DateUtils.java
@@ -1,4 +1,4 @@
-package com.mambu.apisdk;
+package com.mambu.apisdk.util;
import java.text.SimpleDateFormat;
import java.util.Date;
diff --git a/src/com/mambu/apisdk/util/RequestExecutor.java b/src/com/mambu/apisdk/util/RequestExecutor.java
new file mode 100644
index 00000000..a7cb8b7c
--- /dev/null
+++ b/src/com/mambu/apisdk/util/RequestExecutor.java
@@ -0,0 +1,36 @@
+package com.mambu.apisdk.util;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+
+import com.mambu.apisdk.exception.MambuApiException;
+
+/**
+ * Interface for executing url requests
+ *
+ * @author edanilkis
+ *
+ */
+public interface RequestExecutor {
+
+ public enum Method {
+ GET,
+ POST,
+ PUT,
+ DELETE,
+ }
+
+ public void setAuthorization(String username, String password);
+
+ /**
+ * Executs a given url with a given request method
+ *
+ * @param urlString
+ * the url to execute on. eg: https://demo.mambu.com/api/clients
+ * @param method
+ * the method for execution: one of GET, POST, PUT or Delete
+ * @return
+ * @throws MambuApiException
+ */
+ public String executeRequest(String urlString, Method method) throws MalformedURLException, IOException, MambuApiException;
+}
diff --git a/src/com/mambu/apisdk/util/RequestExecutorImpl.java b/src/com/mambu/apisdk/util/RequestExecutorImpl.java
new file mode 100644
index 00000000..f5d79101
--- /dev/null
+++ b/src/com/mambu/apisdk/util/RequestExecutorImpl.java
@@ -0,0 +1,98 @@
+package com.mambu.apisdk.util;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.apache.commons.codec.binary.Base64;
+
+import com.mambu.apisdk.exception.MambuApiException;
+
+/**
+ * Implementation of executing url requests with basic authorization
+ *
+ * @author edanilkis
+ *
+ */
+public class RequestExecutorImpl implements RequestExecutor {
+
+ private String encodedAuthorization;
+
+ /**
+ * Executes the request as per the interface specification
+ */
+ @Override
+ public String executeRequest(String urlString, Method method) throws MalformedURLException, IOException, MambuApiException {
+
+ String response = "";
+ Integer errorCode = null;
+
+ // create the url
+ URL url = new URL(urlString);
+
+ // set up the connection
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod(method.toString());
+ connection.setDoOutput(true);
+
+ //add the authorization
+ connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
+
+ // get the status
+ int status = ((HttpURLConnection) connection).getResponseCode();
+
+ // setup the content
+ InputStream content;
+
+ // ensure it's an ok response
+ if (status != 200) {
+ errorCode = status;
+ // if there was an error, read the error message
+ content = connection.getErrorStream();
+ } else {
+ content = connection.getInputStream();
+ }
+
+ response = readStream(content);
+
+ // check if we hit an error
+ if (errorCode != null) {
+ throw new MambuApiException(errorCode, response);
+ }
+
+ return response;
+
+ }
+
+ /**
+ * Reads a stream as
+ *
+ * @param content
+ * @return
+ * @throws IOException
+ */
+ private String readStream(InputStream content) throws IOException {
+ String response = "";
+ // read the response content
+ BufferedReader in = new BufferedReader(new InputStreamReader(content));
+ String line;
+ while ((line = in.readLine()) != null) {
+ response += line;
+ }
+
+ return response;
+
+ }
+
+ @Override
+ public void setAuthorization(String username, String password) {
+ // encode the username and password
+ String userNamePassword = username + ":" + password;
+ encodedAuthorization = new String(Base64.encodeBase64(userNamePassword.getBytes()));
+ }
+
+}
diff --git a/test/com/mambu/apisdk/MambuAPIServiceTest.java b/test/com/mambu/apisdk/MambuAPIServiceTest.java
new file mode 100644
index 00000000..30d54cda
--- /dev/null
+++ b/test/com/mambu/apisdk/MambuAPIServiceTest.java
@@ -0,0 +1,93 @@
+package com.mambu.apisdk;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.mambu.apisdk.MambuAPIService;
+import com.mambu.apisdk.exception.MambuApiException;
+import com.mambu.apisdk.util.RequestExecutor;
+import com.mambu.apisdk.util.RequestExecutor.Method;
+import com.mambu.intelligence.shared.model.Intelligence.Indicator;
+
+
+public class MambuAPIServiceTest {
+
+ MambuAPIService service;
+ RequestExecutor executor;
+ String username = "user";
+ String password = "password";
+ String domain = "demo.mambutest.com";
+
+ @Before
+ public void setUp() throws Exception {
+ executor = Mockito.mock(RequestExecutor.class);
+
+ service = new MambuAPIService(username, password, domain, executor);
+ service.setProtocol("http");
+
+ }
+
+ @Test
+ public void testGetClient() throws MalformedURLException, IOException, MambuApiException {
+
+ //execute
+ service.getClient("abc123");
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/clients/abc123", Method.GET);
+ }
+
+ @Test
+ public void testGetGLAccountById() throws MalformedURLException, IOException, MambuApiException {
+
+ //execute
+ service.getGLAccount("1000");
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/glaccounts/1000", Method.GET);
+ }
+
+ @Test
+ public void testGetCurrency() throws MalformedURLException, IOException, MambuApiException {
+
+ //execute
+ service.getCurrency();
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/currencies", Method.GET);
+ }
+
+ @Test
+ public void testGetGLAccountDateRange() throws MalformedURLException, IOException, MambuApiException {
+
+ //execute
+ service.getGLAccount("100", "2001-01-01", "2005-01-01");
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/glaccounts/100?from=2001-01-01&to=2005-01-01", Method.GET);
+ }
+
+ @Test
+ public void testGetIndicator() throws MalformedURLException, IOException, MambuApiException {
+ //execute
+ service.getIndicator(Indicator.INTEREST_IN_SUSPENSE);
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/indicators/INTEREST_IN_SUSPENSE", Method.GET);
+ }
+
+ @Test
+ public void testGetClientDetails() throws MalformedURLException, IOException, MambuApiException {
+ //execute
+ service.getClientDetails("abc123");
+
+ //verify
+ Mockito.verify(executor).executeRequest("http://demo.mambutest.com/api/clients/abc123?fullDetails=true", Method.GET);
+
+ }
+
+}
|
6382a9cbb91110081670f6acb47951712e68526e
|
Search_api
|
Issue #2083481 by drunken monkey, nickgs: Added "exclude" option for facets.
|
a
|
https://github.com/lucidworks/drupal_search_api
|
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index 3568aaac..f1b6d194 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -1,5 +1,6 @@
Search API 1.x, dev (xx/xx/xxxx):
---------------------------------
+- #2083481 by drunken monkey, nickgs: Added "exclude" option for facets.
- #2084953 by Yaron Tal: Fixed issue with theme initialization.
- #2075839 by leeomara, drunken monkey: Added descriptions to field lists for
'Aggregated Fields'.
diff --git a/contrib/search_api_facetapi/plugins/facetapi/adapter.inc b/contrib/search_api_facetapi/plugins/facetapi/adapter.inc
index b99f7dcf..23dde9f6 100644
--- a/contrib/search_api_facetapi/plugins/facetapi/adapter.inc
+++ b/contrib/search_api_facetapi/plugins/facetapi/adapter.inc
@@ -196,7 +196,6 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
*/
public function settingsForm(&$form, &$form_state) {
$facet = $form['#facetapi']['facet'];
- $realm = $form['#facetapi']['realm'];
$facet_settings = $this->getFacet($facet)->getSettings();
$options = $facet_settings->settings;
$search_ids = variable_get('search_api_facets_search_ids', array());
@@ -205,6 +204,7 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
$form['global']['default_true'] = array(
'#type' => 'select',
'#title' => t('Display for searches'),
+ '#prefix' => '<div class="facetapi-global-setting">',
'#options' => array(
TRUE => t('For all except the selected'),
FALSE => t('Only for the selected'),
@@ -214,6 +214,7 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
$form['global']['facet_search_ids'] = array(
'#type' => 'select',
'#title' => t('Search IDs'),
+ '#suffix' => '</div>',
'#options' => $search_ids,
'#size' => min(4, count($search_ids)),
'#multiple' => TRUE,
@@ -246,9 +247,25 @@ class SearchApiFacetapiAdapter extends FacetapiAdapter {
'#type' => 'select',
'#title' => t('Granularity'),
'#description' => t('Determine the maximum drill-down level'),
+ '#prefix' => '<div class="facetapi-global-setting">',
+ '#suffix' => '</div>',
'#options' => $granularity_options,
'#default_value' => isset($options['date_granularity']) ? $options['date_granularity'] : FACETAPI_DATE_MINUTE,
);
}
+
+ // Add an "Exclude" option for terms.
+ if(!empty($facet['query types']) && in_array('term', $facet['query types'])) {
+ $form['global']['operator']['#weight'] = -2;
+ unset($form['global']['operator']['#suffix']);
+ $form['global']['exclude'] = array(
+ '#type' => 'checkbox',
+ '#title' => t('Exclude'),
+ '#description' => t('Make the search exclude selected facets, instead of restricting it to them.'),
+ '#suffix' => '</div>',
+ '#weight' => -1,
+ '#default_value' => !empty($options['exclude']),
+ );
+ }
}
}
diff --git a/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc b/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc
index 1d0e8ebc..96ad37b6 100644
--- a/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc
+++ b/contrib/search_api_facetapi/plugins/facetapi/query_type_term.inc
@@ -64,19 +64,22 @@ class SearchApiFacetapiTerm extends FacetapiQueryType implements FacetapiQueryTy
* Helper method for setting a facet filter on a query or query filter object.
*/
protected function addFacetFilter($query_filter, $field, $filter) {
+ // Test if this filter should be negated.
+ $settings = $this->adapter->getFacet($this->facet)->getSettings();
+ $exclude = !empty($settings->settings['exclude']);
// Integer (or other nun-string) filters might mess up some of the following
// comparison expressions.
$filter = (string) $filter;
if ($filter == '!') {
- $query_filter->condition($field, NULL);
+ $query_filter->condition($field, NULL, $exclude ? '<>' : '=');
}
elseif ($filter[0] == '[' && $filter[strlen($filter) - 1] == ']' && ($pos = strpos($filter, ' TO '))) {
$lower = trim(substr($filter, 1, $pos));
$upper = trim(substr($filter, $pos + 4, -1));
if ($lower == '*' && $upper == '*') {
- $query_filter->condition($field, NULL, '<>');
+ $query_filter->condition($field, NULL, $exclude ? '=' : '<>');
}
- else {
+ elseif (!$exclude) {
if ($lower != '*') {
// Iff we have a range with two finite boundaries, we set two
// conditions (larger than the lower bound and less than the upper
@@ -92,9 +95,22 @@ class SearchApiFacetapiTerm extends FacetapiQueryType implements FacetapiQueryTy
$query_filter->condition($field, $upper, '<=');
}
}
+ else {
+ // Same as above, but with inverted logic.
+ if ($lower != '*') {
+ if ($upper != '*' && ($query_filter instanceof SearchApiQueryInterface || $query_filter->getConjunction() === 'AND')) {
+ $original_query_filter = $query_filter;
+ $query_filter = new SearchApiQueryFilter('OR');
+ }
+ $query_filter->condition($field, $lower, '<');
+ }
+ if ($upper != '*') {
+ $query_filter->condition($field, $upper, '>');
+ }
+ }
}
else {
- $query_filter->condition($field, $filter);
+ $query_filter->condition($field, $filter, $exclude ? '<>' : '=');
}
if (isset($original_query_filter)) {
$original_query_filter->filter($query_filter);
|
495847ad95644bae1c1776b904297579d0ffe62d
|
fenix-framework$fenix-framework
|
[bplustree] New Feature: Special version of B+Trees to hold domain objects.
* The serialization of the backing maps is done via JSON objects, avoiding
serialization of byte[]. This shows greater performance as well as allowing
the trees to be portable across backends and Framework versions
* The new tree shares the code base with the regular tree, differing only in
the serialization.
|
a
|
https://github.com/fenix-framework/fenix-framework
|
diff --git a/core/adt/bplustree/pom.xml b/core/adt/bplustree/pom.xml
index fc9fffaf3..9dc8f6abf 100644
--- a/core/adt/bplustree/pom.xml
+++ b/core/adt/bplustree/pom.xml
@@ -54,5 +54,9 @@
<artifactId>fenix-framework-core-api</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/core/adt/bplustree/src/main/dml/fenix-framework-adt-bplustree.dml b/core/adt/bplustree/src/main/dml/fenix-framework-adt-bplustree.dml
index c6a4f73d7..8a07443d8 100644
--- a/core/adt/bplustree/src/main/dml/fenix-framework-adt-bplustree.dml
+++ b/core/adt/bplustree/src/main/dml/fenix-framework-adt-bplustree.dml
@@ -9,14 +9,34 @@ valueType java.util.TreeMap as GenericTreeMap {
internalizeWith pt.ist.fenixframework.adt.bplustree.AbstractNode.internalizeTreeMap();
}
+valueType java.util.TreeMap as DomainObjectMap {
+ externalizeWith {
+ String pt.ist.fenixframework.adt.bplustree.DomainLeafNode.externalizeDomainObjectMap();
+ }
+ internalizeWith pt.ist.fenixframework.adt.bplustree.DomainLeafNode.internalizeDomainObjectMap();
+}
+
+valueType java.util.TreeMap as OidIndexedMap {
+ externalizeWith {
+ String pt.ist.fenixframework.adt.bplustree.DomainInnerNode.externalizeOidIndexedMap();
+ }
+ internalizeWith pt.ist.fenixframework.adt.bplustree.DomainInnerNode.internalizeOidIndexedMap();
+}
+
class BPlusTree {}
+class DomainBPlusTree extends BPlusTree {}
+
class AbstractNode {}
class LeafNode extends AbstractNode {
// key: any Serializable and Comparable
// value: any Serializable
- GenericTreeMap<Comparable,java.io.Serializable> entries;
+ GenericTreeMap<Comparable, ? extends java.io.Serializable> entries;
+}
+
+class DomainLeafNode extends LeafNode {
+ DomainObjectMap<Comparable, pt.ist.fenixframework.core.AbstractDomainObject> domainEntries;
}
class InnerNode extends AbstractNode {
@@ -29,6 +49,10 @@ class InnerNode extends AbstractNode {
GenericTreeMap<Comparable,AbstractNode> subNodes;
}
+class DomainInnerNode extends InnerNode {
+ OidIndexedMap<Comparable, AbstractNode> indexedSubNodes;
+}
+
relation AdtBPlusTreeHasRootNode {
BPlusTree playsRole;
AbstractNode playsRole root;
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/BPlusTree.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/BPlusTree.java
index 9941e6e77..fed687d0c 100644
--- a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/BPlusTree.java
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/BPlusTree.java
@@ -56,6 +56,11 @@ protected Object writeReplace() throws ObjectStreamException {
static final Comparable LAST_KEY = new ComparableLastKey();
+ /**
+ * Textual representation of the LastKey.
+ */
+ static final String LAST_KEY_REPRESENTATION = "_$LAST_KEY$_";
+
/* Special comparator that takes into account LAST_KEY */
private static class ComparatorSupportingLastKey implements Comparator<Comparable>, Serializable {
// only LAST_KEY knows how to compare itself with others, so we must check for it before
@@ -99,7 +104,7 @@ public BPlusTree() {
initRoot();
}
- private void initRoot() {
+ protected void initRoot() {
this.setRoot(new LeafNode());
}
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainBPlusTree.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainBPlusTree.java
new file mode 100644
index 000000000..8cab4231f
--- /dev/null
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainBPlusTree.java
@@ -0,0 +1,57 @@
+package pt.ist.fenixframework.adt.bplustree;
+
+import java.io.Serializable;
+
+import pt.ist.fenixframework.NoDomainMetaObjects;
+import pt.ist.fenixframework.core.AbstractDomainObject;
+
+/**
+ * {@link BPlusTree} specialized for storing {@link AbstractDomainObject}.
+ * Uses the object's Oid as the Key, and the object as the Value.
+ *
+ * The serialization of a {@link DomainBPlusTree} is done using JSON objects,
+ * thus allowing for better performance and human-readable representation.
+ *
+ * @author João Carvalho ([email protected])
+ *
+ */
+@NoDomainMetaObjects
+public class DomainBPlusTree<T extends AbstractDomainObject> extends DomainBPlusTree_Base {
+
+ public DomainBPlusTree() {
+ super();
+ }
+
+ @Override
+ protected void initRoot() {
+ this.setRoot(new DomainLeafNode());
+ }
+
+ /**
+ * Inserts the given {@link AbstractDomainObject} into the tree.
+ *
+ * @param domainObject
+ * The object to be inserted
+ * @return Whether the object was inserted
+ */
+ public boolean insert(AbstractDomainObject domainObject) {
+ return super.insert(domainObject.getOid(), domainObject);
+ }
+
+ /**
+ *
+ * Inserting {@link Serializable} into a {@link DomainBPlusTree} is not valid.
+ * Throws {@link UnsupportedOperationException}.
+ * Use {@code insert(AbstractDomainObject)} instead.
+ */
+ @Override
+ public boolean insert(Comparable key, Serializable value) {
+ if (value instanceof AbstractDomainObject) {
+ if (((AbstractDomainObject) value).getOid().equals(key)) {
+ return super.insert(key, value);
+ }
+ }
+ throw new UnsupportedOperationException("Cannot insert Serializable in DomainBPlusTree.");
+ }
+
+}
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainInnerNode.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainInnerNode.java
new file mode 100644
index 000000000..d173c33d9
--- /dev/null
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainInnerNode.java
@@ -0,0 +1,149 @@
+package pt.ist.fenixframework.adt.bplustree;
+
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+import pt.ist.fenixframework.FenixFramework;
+import pt.ist.fenixframework.NoDomainMetaObjects;
+import pt.ist.fenixframework.backend.BackEnd;
+import pt.ist.fenixframework.core.AbstractDomainObject;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+
+/**
+ * {@link InnerNode} specialized to hold Oids as Keys.
+ *
+ * The serialization of {@link DomainInnerNode} is done using a JSON object,
+ * containing the External Id of the key objects, and the external id of
+ * the {@link AbstractNode}.
+ *
+ * @author João Carvalho ([email protected])
+ *
+ */
+@NoDomainMetaObjects
+public class DomainInnerNode extends DomainInnerNode_Base {
+
+ /*
+ * DomainInnerNode constructors.
+ *
+ * Due to the limitations of constructors in _Base classes, these have
+ * to be copied from {@link InnerNode} :(
+ */
+
+ DomainInnerNode(AbstractNode leftNode, AbstractNode rightNode, Comparable splitKey) {
+ TreeMap<Comparable, AbstractNode> newMap =
+ new TreeMap<Comparable, AbstractNode>(BPlusTree.COMPARATOR_SUPPORTING_LAST_KEY);
+ newMap.put(splitKey, leftNode);
+ newMap.put(BPlusTree.LAST_KEY, rightNode);
+
+ setSubNodes(newMap);
+ leftNode.setParent(this);
+ rightNode.setParent(this);
+ }
+
+ private DomainInnerNode(TreeMap<Comparable, AbstractNode> subNodes) {
+ setSubNodes(subNodes);
+ for (AbstractNode subNode : subNodes.values()) { // smf: either don't do this or don't setParent when making new
+ subNode.setParent(this);
+ }
+ }
+
+ /*
+ * Overriden entries getter and setter.
+ * This allows the {@link InnerNode} to use the correct serialized
+ * form without changing the parent's serialization.
+ */
+
+ @Override
+ public TreeMap<Comparable, AbstractNode> getSubNodes() {
+ return getIndexedSubNodes();
+ }
+
+ @Override
+ public void setSubNodes(TreeMap<Comparable, AbstractNode> subNodes) {
+ setIndexedSubNodes(subNodes);
+ }
+
+ /*
+ * Node instantiators.
+ *
+ * This allows for the algorithm to remain in {@link InnerNode} while
+ * still creating the correct subclasses.
+ */
+
+ @Override
+ protected InnerNode createNode(AbstractNode leftNode, AbstractNode rightNode, Comparable splitKey) {
+ return new DomainInnerNode(leftNode, rightNode, splitKey);
+ }
+
+ @Override
+ protected InnerNode createNodeWithSubNodes(TreeMap<Comparable, AbstractNode> subNodes) {
+ return new DomainInnerNode(subNodes);
+ }
+
+ /*
+ * Serialization code
+ */
+
+ /**
+ * The {@link JsonParser} to be used. Because its instances are
+ * stateless we can use only one parser.
+ */
+ private static final JsonParser parser = new JsonParser();
+
+ /**
+ * Serializes the given map to a JSON object containing a mapping between the
+ * External Ids of the Key and Value objects.
+ *
+ * Uses {@link BPlusTree.LAST_KEY_REPRESENTATION} as a well-known value to
+ * represent the Last Key.
+ *
+ * @param map
+ * Map to serialize. Must be in the form [Oid, AbstractNode]
+ * @return
+ * A JSON Object containing the mapping
+ */
+ public static String externalizeOidIndexedMap(TreeMap map) {
+ BackEnd backend = FenixFramework.getConfig().getBackEnd();
+ JsonObject jsonObject = new JsonObject();
+ for (Object obj : map.entrySet()) {
+ Entry<Comparable, AbstractNode> entry = (Entry<Comparable, AbstractNode>) obj;
+ String key;
+ if (entry.getKey().equals(BPlusTree.LAST_KEY)) {
+ key = BPlusTree.LAST_KEY_REPRESENTATION;
+ } else {
+ key = backend.fromOid(entry.getKey()).getExternalId();
+ }
+ jsonObject.add(key, new JsonPrimitive(entry.getValue().getExternalId()));
+ }
+ return jsonObject.toString();
+ }
+
+ /**
+ * Internalizes the given JSON object.
+ *
+ * @param externalizedMap
+ * A JSON array returned by {@code externalizeOidIndexedMap}
+ * @return
+ * A TreeMap containing pairs [Oid, AbstractNode]
+ */
+ public static TreeMap internalizeOidIndexedMap(String externalizedMap) {
+ TreeMap map = new TreeMap(BPlusTree.COMPARATOR_SUPPORTING_LAST_KEY);
+ JsonObject object = parser.parse(externalizedMap).getAsJsonObject();
+ for (Entry<String, JsonElement> entry : object.entrySet()) {
+ Comparable key;
+ if (entry.getKey().equals(BPlusTree.LAST_KEY_REPRESENTATION)) {
+ key = BPlusTree.LAST_KEY;
+ } else {
+ key = FenixFramework.<AbstractDomainObject> getDomainObject(entry.getKey()).getOid();
+ }
+ AbstractNode value = FenixFramework.getDomainObject(entry.getValue().getAsString());
+ map.put(key, value);
+ }
+ return map;
+ }
+
+}
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainLeafNode.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainLeafNode.java
new file mode 100644
index 000000000..41d006fbe
--- /dev/null
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/DomainLeafNode.java
@@ -0,0 +1,124 @@
+package pt.ist.fenixframework.adt.bplustree;
+
+import java.io.Serializable;
+import java.util.TreeMap;
+
+import pt.ist.fenixframework.DomainObject;
+import pt.ist.fenixframework.FenixFramework;
+import pt.ist.fenixframework.NoDomainMetaObjects;
+import pt.ist.fenixframework.core.AbstractDomainObject;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.JsonPrimitive;
+
+/**
+ * {@link LeafNode} specialized to hold a mapping of [Oid, DomainObject]
+ *
+ * The serialization of {@link DomainLeafNode} is done using a JSON array,
+ * containing the External Id of the stored objects.
+ *
+ * @author João Carvalho ([email protected])
+ *
+ */
+@NoDomainMetaObjects
+public class DomainLeafNode extends DomainLeafNode_Base {
+
+ /**
+ * Initialize a {@link DomainLeafNode} with no entries.
+ *
+ * @see LeafNode
+ */
+ public DomainLeafNode() {
+ super();
+ }
+
+ /**
+ * Initialize a {@link DomainLeafNode} with the given entries.
+ *
+ * @see LeafNode
+ */
+ private DomainLeafNode(TreeMap<Comparable, Serializable> entries) {
+ setEntries(entries);
+ }
+
+ /*
+ * Overriden entries getter and setter.
+ * This allows the {@link LeafNode} to use the correct serialized
+ * form without changing the parent's serialization.
+ */
+
+ @Override
+ public TreeMap<Comparable, ? extends Serializable> getEntries() {
+ return getDomainEntries();
+ }
+
+ @Override
+ public void setEntries(TreeMap<Comparable, ? extends Serializable> entries) {
+ setDomainEntries((TreeMap<Comparable, AbstractDomainObject>) entries);
+ }
+
+ /*
+ * Node instantiators.
+ *
+ * This allows for the algorithm to remain in {@link LeafNode} while
+ * still creating the correct subclasses.
+ */
+
+ @Override
+ protected LeafNode createNodeWithEntries(TreeMap<Comparable, Serializable> entries) {
+ return new DomainLeafNode(entries);
+ }
+
+ @Override
+ protected InnerNode createInnerNode(AbstractNode leftNode, AbstractNode rightNode, Comparable splitKey) {
+ return new DomainInnerNode(leftNode, rightNode, splitKey);
+ }
+
+ /*
+ * Serialization code
+ */
+
+ /**
+ * The {@link JsonParser} to be used. Because its instances are
+ * stateless we can use only one parser.
+ */
+ private static final JsonParser parser = new JsonParser();
+
+ /**
+ * Serializes the given map to a JSON array containing the ExternalId of
+ * the values.
+ *
+ * @param map
+ * Map to serialize. Must be in the form [Oid, DomainObject]
+ * @return
+ * A JSON array containing the External Ids
+ */
+ public static String externalizeDomainObjectMap(TreeMap map) {
+ JsonArray array = new JsonArray();
+ for (Object obj : map.values()) {
+ DomainObject domainObject = (DomainObject) obj;
+ array.add(new JsonPrimitive(domainObject.getExternalId()));
+ }
+ return array.toString();
+ }
+
+ /**
+ * Internalizes the given JSON array.
+ *
+ * @param externalizedMap
+ * A JSON array returned by {@code externalizeDomainObjectMap}
+ * @return
+ * A TreeMap containing pairs [Oid, DomainObject]
+ */
+ public static TreeMap internalizeDomainObjectMap(String externalizedMap) {
+ TreeMap map = new TreeMap();
+ JsonArray array = parser.parse(externalizedMap).getAsJsonArray();
+ for (JsonElement element : array) {
+ AbstractDomainObject ado = FenixFramework.getDomainObject(element.getAsString());
+ map.put(ado.getOid(), ado);
+ }
+ return map;
+ }
+}
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/InnerNode.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/InnerNode.java
index 230b225a6..eddd07d74 100644
--- a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/InnerNode.java
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/InnerNode.java
@@ -19,7 +19,7 @@
@NoDomainMetaObjects
public class InnerNode extends InnerNode_Base {
- private InnerNode() {
+ protected InnerNode() {
super();
}
@@ -41,6 +41,14 @@ private InnerNode(TreeMap<Comparable, AbstractNode> subNodes) {
}
}
+ protected InnerNode createNode(AbstractNode leftNode, AbstractNode rightNode, Comparable splitKey) {
+ return new InnerNode(leftNode, rightNode, splitKey);
+ }
+
+ protected InnerNode createNodeWithSubNodes(TreeMap<Comparable, AbstractNode> subNodes) {
+ return new InnerNode(subNodes);
+ }
+
private TreeMap<Comparable, AbstractNode> duplicateMap() {
return new TreeMap<Comparable, AbstractNode>(getSubNodes());
}
@@ -71,14 +79,14 @@ AbstractNode rebase(AbstractNode subLeftNode, AbstractNode subRightNode, Compara
// this level. It will be moved up.
TreeMap<Comparable, AbstractNode> leftSubNodes = new TreeMap<Comparable, AbstractNode>(newMap.headMap(keyToSplit));
leftSubNodes.put(BPlusTree.LAST_KEY, subNodeToMoveLeft);
- InnerNode leftNode = new InnerNode(leftSubNodes);
+ InnerNode leftNode = createNodeWithSubNodes(leftSubNodes);
subNodeToMoveLeft.setParent(leftNode); // smf: maybe it is not necessary because of the code in the constructor
- InnerNode rightNode = new InnerNode(new TreeMap<Comparable, AbstractNode>(newMap.tailMap(nextKey)));
+ InnerNode rightNode = createNodeWithSubNodes(new TreeMap<Comparable, AbstractNode>(newMap.tailMap(nextKey)));
// propagate split to parent
if (this.getParent() == null) {
- InnerNode newRoot = new InnerNode(leftNode, rightNode, keyToSplit);
+ InnerNode newRoot = createNode(leftNode, rightNode, keyToSplit);
return newRoot;
} else {
return this.getParent().rebase(leftNode, rightNode, keyToSplit);
diff --git a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/LeafNode.java b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/LeafNode.java
index 5a6461297..aba0145e7 100644
--- a/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/LeafNode.java
+++ b/core/adt/bplustree/src/main/java/pt/ist/fenixframework/adt/bplustree/LeafNode.java
@@ -38,13 +38,13 @@ public AbstractNode insert(Comparable key, Serializable value) {
Comparable keyToSplit = findRightMiddlePosition(localMap.keySet());
// split node in two
- LeafNode leftNode = new LeafNode(new TreeMap<Comparable, Serializable>(localMap.headMap(keyToSplit)));
- LeafNode rightNode = new LeafNode(new TreeMap<Comparable, Serializable>(localMap.tailMap(keyToSplit)));
+ LeafNode leftNode = createNodeWithEntries(new TreeMap<Comparable, Serializable>(localMap.headMap(keyToSplit)));
+ LeafNode rightNode = createNodeWithEntries(new TreeMap<Comparable, Serializable>(localMap.tailMap(keyToSplit)));
fixLeafNodesListAfterSplit(leftNode, rightNode);
// propagate split to parent
if (getParent() == null) { // make new root node
- InnerNode newRoot = new InnerNode(leftNode, rightNode, keyToSplit);
+ InnerNode newRoot = createInnerNode(leftNode, rightNode, keyToSplit);
return newRoot;
} else {
// leftNode.parent = getParent();
@@ -54,6 +54,14 @@ public AbstractNode insert(Comparable key, Serializable value) {
}
}
+ protected LeafNode createNodeWithEntries(TreeMap<Comparable, Serializable> entries) {
+ return new LeafNode(entries);
+ }
+
+ protected InnerNode createInnerNode(AbstractNode leftNode, AbstractNode rightNode, Comparable splitKey) {
+ return new InnerNode(leftNode, rightNode, splitKey);
+ }
+
private <T extends Comparable> Comparable findRightMiddlePosition(Collection<T> keys) {
Iterator<T> keysIterator = keys.iterator();
@@ -64,7 +72,7 @@ private <T extends Comparable> Comparable findRightMiddlePosition(Collection<T>
}
private TreeMap<Comparable, Serializable> justInsert(Comparable key, Serializable value) {
- TreeMap<Comparable, Serializable> localEntries = this.getEntries();
+ TreeMap<Comparable, ? extends Serializable> localEntries = this.getEntries();
// this test is performed because we need to return a new structure in
// case an update occurs. Value types must be immutable.
@@ -118,7 +126,7 @@ void delete() {
}
private TreeMap<Comparable, Serializable> justRemove(Comparable key) {
- TreeMap<Comparable, Serializable> localEntries = this.getEntries();
+ TreeMap<Comparable, ? extends Serializable> localEntries = this.getEntries();
// this test is performed because we need to return a new structure in
// case an update occurs. Value types must be immutable.
@@ -202,7 +210,7 @@ public Serializable getIndex(int index) {
}
if (index < shallowSize()) { // the required position is here
- Iterator<Serializable> values = this.getEntries().values().iterator();
+ Iterator<? extends Serializable> values = this.getEntries().values().iterator();
for (int i = 0; i < index; i++) {
values.next();
}
@@ -311,7 +319,7 @@ private class LeafNodeValuesIterator extends GenericLeafNodeIterator<Serializabl
@Override
protected Iterator<Serializable> getInternalIterator(LeafNode leafNode) {
- return leafNode.getEntries().values().iterator();
+ return (Iterator<Serializable>) leafNode.getEntries().values().iterator();
}
}
@@ -339,7 +347,7 @@ public String dump(int level, boolean dumpKeysOnly, boolean dumpNodeIds) {
str.append("[: ");
}
- for (Map.Entry<Comparable, Serializable> entry : this.getEntries().entrySet()) {
+ for (Map.Entry<Comparable, ? extends Serializable> entry : this.getEntries().entrySet()) {
Comparable key = entry.getKey();
Serializable value = entry.getValue();
str.append("(" + key);
diff --git a/pom.xml b/pom.xml
index 718f77e15..ba3a8d98c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -34,6 +34,7 @@
<version.commons.codec>1.7</version.commons.codec>
<version.commons.io>2.4</version.commons.io>
<version.commons.lang>2.6</version.commons.lang>
+ <version.com.google.code.gson>2.2.3</version.com.google.code.gson>
<version.dap-framework>2.0</version.dap-framework>
<version.hazelcast.api>2.5.1</version.hazelcast.api>
<version.hibernate.ogm.core>${version.hibernate.ogm}</version.hibernate.ogm.core>
@@ -143,7 +144,7 @@
<configuration>
<pushChanges>false</pushChanges>
<tagNameFormat>v@{project.version}</tagNameFormat>
-
+
<!-- Ensure that every module is versioned together -->
<autoVersionSubmodules>true</autoVersionSubmodules>
</configuration>
@@ -313,6 +314,11 @@
<artifactId>hazelcast</artifactId>
<version>${version.hazelcast.api}</version>
</dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>${version.com.google.code.gson}</version>
+ </dependency>
</dependencies>
</dependencyManagement>
|
cb1f286c45ca4c6599580551557a101d0836fe4f
|
intellij-community
|
added "Overloaded varargs method" inspection--
|
a
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties
index 0e84c3412a3f4..bdfce88dcf823 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties
+++ b/plugins/InspectionGadgets/src/com/siyeh/InspectionGadgetsBundle.properties
@@ -285,6 +285,7 @@ increment.decrement.display.name=Value of ++ or -- used
nested.assignment.display.name=Nested assignment
nested.assignment.problem.descriptor=Nested assignment <code>#ref</code> #loc
overloaded.methods.with.same.number.parameters.display.name=Overloaded methods with same number of parameters
+overloaded.vararg.method.display.name=Overloaded varargs method
refused.bequest.display.name=Refused bequest
reuse.of.local.variable.display.name=Reuse of local variable
reuse.of.local.variable.split.quickfix=Split local variable
@@ -1435,6 +1436,8 @@ indexof.replaceable.by.contains.display.name='.indexOf()' expression is replacea
indexof.replaceable.by.contains.problem.descriptor=<code>#ref</code> can be replaced by ''{0}'' #loc
replace.indexof.with.contains.quickfix=Replace '.indexOf()' with '.contains()'
overloaded.methods.with.same.number.parameters.problem.descriptor=Multiple methods named <code>#ref</code> with the same number of parameters
+overloaded.vararg.method.problem.descriptor=Overloaded varargs method <code>#ref</code>
+overloaded.vararg.constructor.problem.descriptor=Overloaded varargs constructor <code>#ref</code>
cached.number.constructor.call.display.name=Number constructor call with primitive argument
cached.number.constructor.call.problem.descriptor=Number constructor call with primitive argument <code>#ref</code> #loc
cached.number.constructor.call.quickfix=Replace with {0}.valueOf() call
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java b/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java
index f1b2ff6dc13b5..e5c92109ae256 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/InspectionGadgetsPlugin.java
@@ -369,6 +369,7 @@ private void registerNamingInspections(){
m_inspectionClasses.add(ConfusingMainMethodInspection.class);
m_inspectionClasses.add(UpperCaseFieldNameNotConstantInspection.class);
m_inspectionClasses.add(DollarSignInNameInspection.class);
+ m_inspectionClasses.add(OverloadedVarargsMethodInspection.class);
}
private void registerControlFlowInspections() {
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java
index 0bf2e4381b38c..b622560fe5eaf 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedMethodsWithSameNumberOfParametersInspection.java
@@ -26,7 +26,8 @@ public class OverloadedMethodsWithSameNumberOfParametersInspection
extends MethodInspection {
public String getDisplayName() {
- return InspectionGadgetsBundle.message("overloaded.methods.with.same.number.parameters.display.name");
+ return InspectionGadgetsBundle.message(
+ "overloaded.methods.with.same.number.parameters.display.name");
}
public String getGroupDisplayName() {
@@ -34,7 +35,8 @@ public String getGroupDisplayName() {
}
public String buildErrorString(PsiElement location) {
- return InspectionGadgetsBundle.message("overloaded.methods.with.same.number.parameters.problem.descriptor");
+ return InspectionGadgetsBundle.message(
+ "overloaded.methods.with.same.number.parameters.problem.descriptor");
}
public BaseInspectionVisitor buildVisitor() {
@@ -48,25 +50,19 @@ public void visitMethod(@NotNull PsiMethod method) {
if (method.isConstructor()) {
return;
}
-
- final String methodName = method.getName();
- if (methodName == null) {
- return;
- }
final int parameterCount = calculateParamCount(method);
-
final PsiClass aClass = method.getContainingClass();
if (aClass == null) {
return;
}
- final PsiMethod[] methods = aClass.getMethods();
- for (PsiMethod method1 : methods) {
- if(!method1.equals(method)) {
- final String testMethName = method1.getName();
-
- final int testParameterCount = calculateParamCount(method1);
- if(testMethName != null && methodName.equals(testMethName)
- && parameterCount == testParameterCount) {
+ final String methodName = method.getName();
+ final PsiMethod[] sameNameMethods =
+ aClass.findMethodsByName(methodName, false);
+ for (PsiMethod sameNameMethod : sameNameMethods) {
+ if(!sameNameMethod.equals(method)) {
+ final int testParameterCount =
+ calculateParamCount(sameNameMethod);
+ if(parameterCount == testParameterCount) {
registerMethodError(method);
}
}
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java
new file mode 100644
index 0000000000000..a64ce1e2149b2
--- /dev/null
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/naming/OverloadedVarargsMethodInspection.java
@@ -0,0 +1,77 @@
+/**
+ * (c) 2004 Carp Technologies BV
+ * Hengelosestraat 705, 7521PA Enschede
+ * Created: Feb 22, 2006, 12:39:10 AM
+ */
+package com.siyeh.ig.naming;
+
+import com.siyeh.ig.MethodInspection;
+import com.siyeh.ig.BaseInspectionVisitor;
+import com.siyeh.InspectionGadgetsBundle;
+import com.intellij.codeInsight.daemon.GroupNames;
+import com.intellij.psi.*;
+import org.jetbrains.annotations.NotNull;
+
+public class OverloadedVarargsMethodInspection extends MethodInspection {
+
+ public String getDisplayName() {
+ return InspectionGadgetsBundle.message(
+ "overloaded.vararg.method.display.name");
+ }
+
+ public String getGroupDisplayName() {
+ return GroupNames.NAMING_CONVENTIONS_GROUP_NAME;
+ }
+
+ public String buildErrorString(PsiElement location) {
+ final PsiMethod element = (PsiMethod)location.getParent();
+ if (element.isConstructor()) {
+ return InspectionGadgetsBundle.message(
+ "overloaded.vararg.constructor.problem.descriptor");
+ } else {
+ return InspectionGadgetsBundle.message(
+ "overloaded.vararg.method.problem.descriptor");
+ }
+ }
+
+ public BaseInspectionVisitor buildVisitor() {
+ return new OverloadedVarargMethodVisitor();
+ }
+
+ private static class OverloadedVarargMethodVisitor
+ extends BaseInspectionVisitor {
+
+ public void visitMethod(@NotNull PsiMethod method) {
+ if (!hasVarargParameter(method)) {
+ return;
+ }
+ final PsiClass aClass = method.getContainingClass();
+ if (aClass == null) {
+ return;
+ }
+ final String methodName = method.getName();
+ final PsiMethod[] sameNameMethods;
+ if (method.isConstructor()) {
+ sameNameMethods = aClass.findMethodsByName(methodName, false);
+ } else {
+ sameNameMethods = aClass.findMethodsByName(methodName, false);
+ }
+ for (PsiMethod sameNameMethod : sameNameMethods) {
+ if(!sameNameMethod.equals(method)) {
+ registerMethodError(method);
+ }
+ }
+ }
+
+ private static boolean hasVarargParameter(PsiMethod method) {
+ final PsiParameterList parameterList = method.getParameterList();
+ final PsiParameter[] parameters = parameterList.getParameters();
+ if (parameters.length == 0) {
+ return false;
+ }
+ final PsiParameter lastParameter =
+ parameters[parameters.length - 1];
+ return lastParameter.isVarArgs();
+ }
+ }
+}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html b/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html
new file mode 100644
index 0000000000000..d6a2e326922af
--- /dev/null
+++ b/plugins/InspectionGadgets/src/inspectionDescriptions/OverloadedVarargsMethod.html
@@ -0,0 +1,8 @@
+<html>
+<body><table> <tr> <td valign="top" height="150">
+<font face="verdana" size="-1">
+This inspection reports vararg methods, when there are one or more other methods with the
+same name present in a class. Overloaded varargs methods can be very confusing,
+as it is often not clear which overloading gets called.
+</font></td> </tr> <tr> <td height="20"> <font face="verdana" size="-2">Powered by InspectionGadgets </font> </td> </tr> </table> </body>
+</html>
\ No newline at end of file
|
55a5c26de8023fa65c0f231666034649f963f93f
|
elasticsearch
|
Fix NPE in RangeAggregator--
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/range/RangeAggregator.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/range/RangeAggregator.java
index 8da74aa133a45..1b27e1c1991b9 100644
--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/range/RangeAggregator.java
+++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/range/RangeAggregator.java
@@ -94,7 +94,7 @@ public RangeAggregator(String name,
AggregationContext aggregationContext,
Aggregator parent) {
- super(name, BucketAggregationMode.MULTI_BUCKETS, factories, ranges.size() * parent.estimatedBucketCount(), aggregationContext, parent);
+ super(name, BucketAggregationMode.MULTI_BUCKETS, factories, ranges.size() * (parent == null ? 1 : parent.estimatedBucketCount()), aggregationContext, parent);
assert valuesSource != null;
this.valuesSource = valuesSource;
this.keyed = keyed;
|
304215665eb630a9c3e722d789e882bf9f59ab21
|
orientdb
|
Fixed issue 800 closing the socket on timeout--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
index adf2bc9ebcf..819195b2761 100644
--- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java
@@ -56,6 +56,10 @@ public void run() {
if (socket == null || socket.isClosed() || socket.isInputShutdown()) {
OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)",
entry.getKey(), socket);
+ try {
+ entry.getValue().close();
+ } catch (Exception e) {
+ }
connections.remove(entry.getKey());
}
}
|
079b856a6c9ca5abbf788c9eb94535139e301cda
|
spring-framework
|
javadoc--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.context/src/main/java/org/springframework/ui/message/DefaultMessageResolver.java b/org.springframework.context/src/main/java/org/springframework/ui/message/DefaultMessageResolver.java
index b79f3d3f2d16..7bf1eb11e1e8 100644
--- a/org.springframework.context/src/main/java/org/springframework/ui/message/DefaultMessageResolver.java
+++ b/org.springframework.context/src/main/java/org/springframework/ui/message/DefaultMessageResolver.java
@@ -95,7 +95,7 @@ public String toString() {
defaultText).toString();
}
- static class TextMessage implements Message {
+ private static class TextMessage implements Message {
private Severity severity;
@@ -116,7 +116,7 @@ public String getText() {
}
- static class MessageSourceResolvableAccessor implements PropertyAccessor {
+ private static class MessageSourceResolvableAccessor implements PropertyAccessor {
private MessageSource messageSource;
@@ -140,12 +140,11 @@ public boolean canWrite(EvaluationContext context, Object target, String name) t
return false;
}
- @SuppressWarnings("unchecked")
public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {
throw new UnsupportedOperationException("Should not be called");
}
- public Class[] getSpecificTargetClasses() {
+ public Class<?>[] getSpecificTargetClasses() {
return new Class[] { MessageSourceResolvable.class };
}
diff --git a/org.springframework.context/src/main/java/org/springframework/ui/message/Message.java b/org.springframework.context/src/main/java/org/springframework/ui/message/Message.java
index 48d5fbb34016..c9edd4aa7716 100644
--- a/org.springframework.context/src/main/java/org/springframework/ui/message/Message.java
+++ b/org.springframework.context/src/main/java/org/springframework/ui/message/Message.java
@@ -16,18 +16,16 @@
package org.springframework.ui.message;
/**
- * Communicates information about an event to the user.
- * For example, a validation message may inform a web application user a business rule was violated.
- * A message is attached to a receiving element, has text providing the basis for communication,
- * and has severity indicating the priority or intensity of the message for its receiver.
- *
+ * Communicates information of interest to the user.
+ * For example, a error message may inform a user of a web application a business rule was violated.
+ * TODO - should we introduce summary/detail fields instead of just text
* @author Keith Donald
*/
public interface Message {
/**
* The severity of this message.
- * The severity indicates the intensity or priority of the communication.
+ * The severity indicates the intensity or priority of the message.
* @return the message severity
*/
public Severity getSeverity();
diff --git a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageBuilder.java b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageBuilder.java
index 2394bddcc01c..d0c4fbeb2b02 100644
--- a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageBuilder.java
+++ b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageBuilder.java
@@ -22,31 +22,33 @@
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
-import org.springframework.context.expression.MapAccessor;
import org.springframework.core.style.ToStringCreator;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
-import org.springframework.expression.spel.support.StandardEvaluationContext;
/**
- * A convenient builder for building {@link MessageResolver} objects programmatically.
- * Often used by model code such as validation logic to conveniently record validation messages.
- * Supports the production of message resolvers that hard-code their message text,
- * as well as message resolvers that retrieve their text from a {@link MessageSource}.
- *
- * Usage example:
+ * A builder for building {@link MessageResolver} objects.
+ * Typically used by Controllers to {@link MessageContext#add(MessageResolver, String) add} messages to display in a user interface.
+ * Supports MessageResolvers that hard-code the message text, as well as MessageResolvers that resolve the message text from a localized {@link MessageSource}.
+ * Also supports named arguments whose values can be inserted into messages using #{eval expressions}.
* <p>
+ * Usage example:
* <pre>
* new MessageBuilder().
* severity(Severity.ERROR).
- * code("invalidFormat").
- * arg("mathForm.decimalField").
- * arg("#,###.##").
- * defaultText("The decimal field must be in format #,###.##").
+ * code("invalidFormat").
+ * resolvableArg("label", "mathForm.decimalField").
+ * arg("format", "#,###.##").
+ * defaultText("The decimal field must be in format #,###.##").
* build();
* </pre>
- * </p>
+ * Example messages.properties loaded by the MessageSource:
+ * <pre>
+ * invalidFormat=The #{label} must be in format #{format}.
+ * mathForm.decimalField=Decimal Field
+ * </pre>
* @author Keith Donald
+ * @see MessageContext#add(MessageResolver, String)
*/
public class MessageBuilder {
@@ -70,9 +72,9 @@ public MessageBuilder severity(Severity severity) {
}
/**
- * Add a message code to use to resolve the message text.
+ * Add a code to use to resolve the template for generating the localized message text.
* Successive calls to this method add additional codes.
- * Codes are applied in the order they are added.
+ * Codes are tried in the order they are added.
* @param code the message code
* @return this, for fluent API usage
*/
@@ -82,8 +84,10 @@ public MessageBuilder code(String code) {
}
/**
- * Add a message argument.
- * Successive calls to this method add additional args.
+ * Add a message argument to insert into the message text.
+ * Named message arguments are inserted by eval expressions denoted within the resolved message template.
+ * For example, the value of the 'format' argument would be inserted where a corresponding #{format} expression is defined in the message template.
+ * Successive calls to this method add additional arguments.
* @param name the argument name
* @param value the argument value
* @return this, for fluent API usage
@@ -94,14 +98,14 @@ public MessageBuilder arg(String name, Object value) {
}
/**
- * Add a message argument whose value is a resolvable message code.
- * Successive calls to this method add additional resolvable arguements.
+ * Add a message argument to insert into the message text, where the actual value to be inserted should be resolved by the {@link MessageSource}.
+ * Successive calls to this method add additional resolvable arguments.
* @param name the argument name
- * @param value the argument value
+ * @param code the code to use to resolve the argument value
* @return this, for fluent API usage
*/
- public MessageBuilder resolvableArg(String name, Object value) {
- args.put(name, new ResolvableArgumentValue(value));
+ public MessageBuilder resolvableArg(String name, Object code) {
+ args.put(name, new ResolvableArgumentValue(code));
return this;
}
@@ -135,12 +139,12 @@ public MessageResolver build() {
return new DefaultMessageResolver(severity, codesArray, args, defaultText, expressionParser);
}
- static class ResolvableArgumentValue implements MessageSourceResolvable {
+ private static class ResolvableArgumentValue implements MessageSourceResolvable {
- private Object value;
+ private Object code;
- public ResolvableArgumentValue(Object value) {
- this.value = value;
+ public ResolvableArgumentValue(Object code) {
+ this.code = code;
}
public Object[] getArguments() {
@@ -148,15 +152,15 @@ public Object[] getArguments() {
}
public String[] getCodes() {
- return new String[] { value.toString() };
+ return new String[] { code.toString() };
}
public String getDefaultMessage() {
- return String.valueOf(value);
+ return String.valueOf(code);
}
public String toString() {
- return new ToStringCreator(this).append("value", value).toString();
+ return new ToStringCreator(this).append("code", code).toString();
}
}
diff --git a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolutionException.java b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolutionException.java
index a8a8d9c09734..39a418575e99 100644
--- a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolutionException.java
+++ b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolutionException.java
@@ -1,7 +1,32 @@
+/*
+ * Copyright 2004-2009 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
package org.springframework.ui.message;
+/**
+ * Runtime exception thrown by a {@link MessageResolver} if a message resolution fails.
+ * @author Keith Donald
+ */
+@SuppressWarnings("serial")
public class MessageResolutionException extends RuntimeException {
+ /**
+ * Creates a new message resolution exception.
+ * @param message a messaging describing the failure
+ * @param cause the cause of the failure
+ */
public MessageResolutionException(String message, Throwable cause) {
super(message, cause);
}
diff --git a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolver.java b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolver.java
index b8113562b9e7..38bebae21258 100644
--- a/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolver.java
+++ b/org.springframework.context/src/main/java/org/springframework/ui/message/MessageResolver.java
@@ -20,9 +20,7 @@
import org.springframework.context.MessageSource;
/**
- * A factory for a Message. Allows a Message to be internationalized and to be resolved from a
- * {@link MessageSource message resource bundle}.
- *
+ * A factory for a localized Message.
* @author Keith Donald
* @see Message
* @see MessageSource
@@ -30,10 +28,11 @@
public interface MessageResolver {
/**
- * Resolve the message from the message source using the current locale.
+ * Resolve the message from the message source for the locale.
* @param messageSource the message source, an abstraction for a resource bundle
- * @param locale the current locale of this request
+ * @param locale the locale of this request
* @return the resolved message
+ * @throws MessageResolutionException if a resolution failure occurs
*/
public Message resolveMessage(MessageSource messageSource, Locale locale);
}
|
b9ab5a6392651b25554ed554c8b262b20e5a40c5
|
drools
|
-testRemovePackage now works.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7100 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/test/java/org/drools/Precondition.java b/drools-compiler/src/test/java/org/drools/Precondition.java
index 508c384227f..4772976fb17 100755
--- a/drools-compiler/src/test/java/org/drools/Precondition.java
+++ b/drools-compiler/src/test/java/org/drools/Precondition.java
@@ -4,6 +4,10 @@ public class Precondition {
private String code;
private String value;
+ public Precondition() {
+
+ }
+
public Precondition(String code, String value) {
super();
this.code = code;
|
28725723398943b2b51cb38d6fe92a3aadf4dee6
|
drools
|
-now works with non DroolsObjectInputStream- serialization.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@13207 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
|
a
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java b/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
index 6bc15ce0bf7..f3eb3560ed7 100644
--- a/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
+++ b/drools-core/src/main/java/org/drools/common/AbstractRuleBase.java
@@ -173,21 +173,27 @@ public void doWriteExternal(final ObjectOutput stream,
public void doReadExternal(final ObjectInput stream,
final Object[] objects) throws IOException,
ClassNotFoundException {
- // PackageCompilationData must be restored before Rules as it has the ClassLoader needed to resolve the generated code references in Rules
- DroolsObjectInputStream parentStream = (DroolsObjectInputStream) stream;
- parentStream.setRuleBase( this );
- this.pkgs = (Map) parentStream.readObject();
-
- this.packageClassLoader = new CompositePackageClassLoader( parentStream.getClassLoader() );
- for ( final Iterator it = this.pkgs.values().iterator(); it.hasNext(); ) {
- this.packageClassLoader.addClassLoader( ((Package) it.next()).getPackageCompilationData().getClassLoader() );
+ // PackageCompilationData must be restored before Rules as it has the ClassLoader needed to resolve the generated code references in Rules
+ this.pkgs = (Map) stream.readObject();
+
+ if ( stream instanceof DroolsObjectInputStream ) {
+ DroolsObjectInputStream parentStream = (DroolsObjectInputStream) stream;
+ parentStream.setRuleBase( this );
+ this.packageClassLoader = new CompositePackageClassLoader( parentStream.getClassLoader() );
+ this.classLoader = new MapBackedClassLoader( parentStream.getClassLoader() );
+ } else {
+ this.packageClassLoader = new CompositePackageClassLoader( Thread.currentThread().getContextClassLoader() );
+ this.classLoader = new MapBackedClassLoader( Thread.currentThread().getContextClassLoader() );
}
-
- this.classLoader = new MapBackedClassLoader( parentStream.getClassLoader() );
+
this.packageClassLoader.addClassLoader( this.classLoader );
+
+ for ( final Iterator it = this.pkgs.values().iterator(); it.hasNext(); ) {
+ this.packageClassLoader.addClassLoader( ((Package) it.next()).getPackageCompilationData().getClassLoader() );
+ }
// Return the rules stored as a byte[]
- final byte[] bytes = (byte[]) parentStream.readObject();
+ final byte[] bytes = (byte[]) stream.readObject();
// Use a custom ObjectInputStream that can resolve against a given classLoader
final DroolsObjectInputStream childStream = new DroolsObjectInputStream( new ByteArrayInputStream( bytes ),
diff --git a/drools-core/src/main/java/org/drools/reteoo/Rete.java b/drools-core/src/main/java/org/drools/reteoo/Rete.java
index 4569c0cf677..fa600fb6555 100644
--- a/drools-core/src/main/java/org/drools/reteoo/Rete.java
+++ b/drools-core/src/main/java/org/drools/reteoo/Rete.java
@@ -92,10 +92,6 @@ public Rete(InternalRuleBase ruleBase) {
this.ruleBase = ruleBase;
}
- public void setRuleBase(InternalRuleBase ruleBase) {
- this.ruleBase = ruleBase;
- }
-
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
index 7abe9b8f180..051d62f1ef1 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java
@@ -97,14 +97,6 @@ private void readObject(ObjectInputStream stream) throws IOException,
this.ruleBase = ((DroolsObjectInputStream) stream).getRuleBase();
}
- /**
- * Allow this to be settable, otherwise we get infinite recursion on serialisation
- * @param ruleBase
- */
- void setRete(final Rete rete) {
-
- }
-
// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
index 13bc46e5613..d6e1bd47778 100644
--- a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
+++ b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java
@@ -155,8 +155,6 @@ public void readExternal(final ObjectInput stream) throws IOException,
this.rete = (Rete) objects[0];
this.reteooBuilder = (ReteooBuilder) objects[1];
-
- this.reteooBuilder.setRete( this.rete );
}
// ------------------------------------------------------------
diff --git a/drools-core/src/main/java/org/drools/rule/Package.java b/drools-core/src/main/java/org/drools/rule/Package.java
index f1692436631..f6b2fa94c78 100644
--- a/drools-core/src/main/java/org/drools/rule/Package.java
+++ b/drools-core/src/main/java/org/drools/rule/Package.java
@@ -126,7 +126,7 @@ public Package(final String name,
this.globals = Collections.EMPTY_MAP;
this.factTemplates = Collections.EMPTY_MAP;
this.functions = Collections.EMPTY_LIST;
-
+
// This classloader test should only be here for unit testing, too much legacy api to want to change by hand at the moment
if ( parentClassLoader == null ) {
parentClassLoader = Thread.currentThread().getContextClassLoader();
@@ -149,7 +149,7 @@ public void writeExternal(final ObjectOutput stream) throws IOException {
stream.writeObject( this.staticImports );
stream.writeObject( this.globals );
stream.writeObject( this.ruleFlows );
-
+
// Rules must be restored by an ObjectInputStream that can resolve using a given ClassLoader to handle seaprately by storing as
// a byte[]
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -173,13 +173,13 @@ public void readExternal(final ObjectInput stream) throws IOException,
this.staticImports = (List) stream.readObject();
this.globals = (Map) stream.readObject();
this.ruleFlows = (Map) stream.readObject();
-
+
// Return the rules stored as a byte[]
final byte[] bytes = (byte[]) stream.readObject();
// Use a custom ObjectInputStream that can resolve against a given classLoader
final DroolsObjectInputStream streamWithLoader = new DroolsObjectInputStream( new ByteArrayInputStream( bytes ),
- this.packageCompilationData.getClassLoader() );
+ this.packageCompilationData.getClassLoader() );
this.rules = (Map) streamWithLoader.readObject();
}
@@ -289,17 +289,18 @@ public void addRule(final Rule rule) {
rule );
rule.setLoadOrder( this.rules.size() );
}
-
+
/**
* Add a rule flow to this package.
*/
public void addRuleFlow(Process process) {
- if (this.ruleFlows == Collections.EMPTY_MAP) {
+ if ( this.ruleFlows == Collections.EMPTY_MAP ) {
this.ruleFlows = new HashMap();
}
- this.ruleFlows.put(process.getId(), process );
+ this.ruleFlows.put( process.getId(),
+ process );
}
-
+
/**
* Get the rule flows for this package. The key is the ruleflow id.
* It will be Collections.EMPTY_MAP if none have been added.
@@ -307,18 +308,16 @@ public void addRuleFlow(Process process) {
public Map getRuleFlows() {
return this.ruleFlows;
}
-
-
+
/**
* Rule flows can be removed by ID.
*/
public void removeRuleFlow(String id) {
- if (!this.ruleFlows.containsKey( id )) {
- throw new IllegalArgumentException("The rule flow with id [" + id + "] is not part of this package.");
+ if ( !this.ruleFlows.containsKey( id ) ) {
+ throw new IllegalArgumentException( "The rule flow with id [" + id + "] is not part of this package." );
}
this.ruleFlows.remove( id );
}
-
public void removeRule(final Rule rule) {
this.rules.remove( rule.getName() );
diff --git a/drools-core/src/main/java/org/drools/rule/PackageCompilationData.java b/drools-core/src/main/java/org/drools/rule/PackageCompilationData.java
index 265f6c16147..dd204704edd 100644
--- a/drools-core/src/main/java/org/drools/rule/PackageCompilationData.java
+++ b/drools-core/src/main/java/org/drools/rule/PackageCompilationData.java
@@ -125,8 +125,12 @@ public void writeExternal(final ObjectOutput stream) throws IOException {
*/
public void readExternal(final ObjectInput stream) throws IOException,
ClassNotFoundException {
- DroolsObjectInputStream droolsStream = ( DroolsObjectInputStream ) stream;
- initClassLoader( droolsStream.getClassLoader() );
+ if ( stream instanceof DroolsObjectInputStream ) {
+ DroolsObjectInputStream droolsStream = ( DroolsObjectInputStream ) stream;
+ initClassLoader( droolsStream.getClassLoader() );
+ } else {
+ initClassLoader( Thread.currentThread().getContextClassLoader() );
+ }
this.store = (Map) stream.readObject();
this.AST = stream.readObject();
|
6a85160cfa4f99167f29a1323d0175703fb57816
|
camel
|
Fixed test--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1407748 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/camel
|
diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
index e4c9658e37864..4625e7cd39ba4 100644
--- a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
+++ b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
@@ -65,10 +65,16 @@ public void testSplitAttachments() throws Exception {
Message second = mock.getReceivedExchanges().get(1).getIn();
assertEquals(1, first.getAttachments().size());
- assertEquals("logo.jpeg", first.getAttachments().keySet().iterator().next());
-
assertEquals(1, second.getAttachments().size());
- assertEquals("license.txt", second.getAttachments().keySet().iterator().next());
+
+ String file1 = first.getAttachments().keySet().iterator().next();
+ String file2 = second.getAttachments().keySet().iterator().next();
+
+ boolean logo = file1.equals("logo.jpeg") || file2.equals("logo.jpeg");
+ boolean license = file1.equals("license.txt") || file2.equals("license.txt");
+
+ assertTrue("Should have logo.jpeg file attachment", logo);
+ assertTrue("Should have license.txt file attachment", license);
}
@Override
|
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;
}
|
cb5df26bf792108e5063e99b4359b33cf7422f22
|
elasticsearch
|
lucene 4: use the proper token stream to return--
|
c
|
https://github.com/elastic/elasticsearch
|
diff --git a/src/main/java/org/elasticsearch/common/lucene/all/AllField.java b/src/main/java/org/elasticsearch/common/lucene/all/AllField.java
index 66d39ef57fefc..3fdff97ca6dfe 100644
--- a/src/main/java/org/elasticsearch/common/lucene/all/AllField.java
+++ b/src/main/java/org/elasticsearch/common/lucene/all/AllField.java
@@ -57,7 +57,7 @@ public Reader readerValue() {
}
@Override
- public TokenStream tokenStreamValue() {
+ public TokenStream tokenStream(Analyzer analyzer) throws IOException {
try {
allEntries.reset(); // reset the all entries, just in case it was read already
return AllTokenStream.allTokenStream(name, allEntries, analyzer);
|
e8585afa032d2aee0593b238c46799cbb884732d
|
hadoop
|
YARN-45. Add protocol for schedulers to request- containers back from ApplicationMasters. Contributed by Carlo Curino and- Chris Douglas.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1479773 13f79535-47bb-0310-9956-ffa450edef68-
|
a
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index a83cc29faaae7..5bd6f8e65b838 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -45,6 +45,9 @@ Release 2.0.5-beta - UNRELEASED
YARN-482. FS: Extend SchedulingMode to intermediate queues.
(kkambatl via tucu)
+ YARN-45. Add protocol for schedulers to request containers back from
+ ApplicationMasters. (Carlo Curino, cdouglas)
+
IMPROVEMENTS
YARN-365. Change NM heartbeat handling to not generate a scheduler event
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/AllocateResponse.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/AllocateResponse.java
index 0426ee359a6bc..8da0d95bb2cdf 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/AllocateResponse.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/AllocateResponse.java
@@ -22,6 +22,7 @@
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.classification.InterfaceStability.Stable;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.AMRMProtocol;
@@ -48,6 +49,7 @@
* </li>
* <li>A list of nodes whose status has been updated.</li>
* <li>The number of available nodes in a cluster.</li>
+ * <li>A description of resources requested back by the cluster</li>
* </ul>
* </p>
*
@@ -152,4 +154,27 @@ public interface AllocateResponse {
@Private
@Unstable
public void setNumClusterNodes(int numNodes);
+
+ /**
+ * Get the description of containers owned by the AM, but requested back by
+ * the cluster. Note that the RM may have an inconsistent view of the
+ * resources owned by the AM. These messages are advisory, and the AM may
+ * elect to ignore them.
+ *
+ * The message is a snapshot of the resources the RM wants back from the AM.
+ * While demand persists, the RM will repeat its request; applications should
+ * not interpret each message as a request for <emph>additional<emph>
+ * resources on top of previous messages. Resources requested consistently
+ * over some duration may be forcibly killed by the RM.
+ *
+ * @return A specification of the resources to reclaim from this AM.
+ */
+ @Public
+ @Evolving
+ public PreemptionMessage getPreemptionMessage();
+
+ @Private
+ @Unstable
+ public void setPreemptionMessage(PreemptionMessage request);
+
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContainer.java
new file mode 100644
index 0000000000000..d51d696854b58
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContainer.java
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+
+/**
+ * Specific container requested back by the <code>ResourceManager</code>.
+ * @see PreemptionContract
+ * @see StrictPreemptionContract
+ */
+public interface PreemptionContainer {
+
+ /**
+ * @return Container referenced by this handle.
+ */
+ @Public
+ @Evolving
+ public ContainerId getId();
+
+ @Private
+ @Unstable
+ public void setId(ContainerId id);
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContract.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContract.java
new file mode 100644
index 0000000000000..8fc64e5085e33
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionContract.java
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords;
+
+import java.util.List;
+import java.util.Set;
+
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+
+/**
+ * Description of resources requested back by the <code>ResourceManager</code>.
+ * The <code>ApplicationMaster</code> (AM) can satisfy this request according
+ * to its own priorities to prevent containers from being forcibly killed by
+ * the platform.
+ * @see PreemptionMessage
+ */
+public interface PreemptionContract {
+
+ /**
+ * If the AM releases resources matching these requests, then the {@link
+ * PreemptionContainer}s enumerated in {@link #getContainers()} should not be
+ * evicted from the cluster. Due to delays in propagating cluster state and
+ * sending these messages, there are conditions where satisfied contracts may
+ * not prevent the platform from killing containers.
+ * @return List of {@link PreemptionResourceRequest} to update the
+ * <code>ApplicationMaster</code> about resources requested back by the
+ * <code>ResourceManager</code>.
+ * @see AllocateRequest#setAskList(List)
+ */
+ @Public
+ @Evolving
+ public List<PreemptionResourceRequest> getResourceRequest();
+
+ @Private
+ @Unstable
+ public void setResourceRequest(List<PreemptionResourceRequest> req);
+
+ /**
+ * Assign the set of {@link PreemptionContainer} specifying which containers
+ * owned by the <code>ApplicationMaster</code> that may be reclaimed by the
+ * <code>ResourceManager</code>. If the AM prefers a different set of
+ * containers, then it may checkpoint or kill containers matching the
+ * description in {@link #getResourceRequest}.
+ * @return Set of containers at risk if the contract is not met.
+ */
+ @Public
+ @Evolving
+ public Set<PreemptionContainer> getContainers();
+
+
+ @Private
+ @Unstable
+ public void setContainers(Set<PreemptionContainer> containers);
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionMessage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionMessage.java
new file mode 100644
index 0000000000000..a7961fead61bc
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionMessage.java
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords;
+
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+
+/**
+ * A {@link PreemptionMessage} is part of the RM-AM protocol, and it is used by
+ * the RM to specify resources that the RM wants to reclaim from this
+ * <code>ApplicationMaster</code> (AM). The AM receives a {@link
+ * StrictPreemptionContract} message encoding which containers the platform may
+ * forcibly kill, granting it an opportunity to checkpoint state or adjust its
+ * execution plan. The message may also include a {@link PreemptionContract}
+ * granting the AM more latitude in selecting which resources to return to the
+ * cluster.
+ *
+ * The AM should decode both parts of the message. The {@link
+ * StrictPreemptionContract} specifies particular allocations that the RM
+ * requires back. The AM can checkpoint containers' state, adjust its execution
+ * plan to move the computation, or take no action and hope that conditions that
+ * caused the RM to ask for the container will change.
+ *
+ * In contrast, the {@link PreemptionContract} also includes a description of
+ * resources with a set of containers. If the AM releases containers matching
+ * that profile, then the containers enumerated in {@link
+ * PreemptionContract#getContainers()} may not be killed.
+ *
+ * Each preemption message reflects the RM's current understanding of the
+ * cluster state, so a request to return <emph>N</emph> containers may not
+ * reflect containers the AM is releasing, recently exited containers the RM has
+ * yet to learn about, or new containers allocated before the message was
+ * generated. Conversely, an RM may request a different profile of containers in
+ * subsequent requests.
+ *
+ * The policy enforced by the RM is part of the scheduler. Generally, only
+ * containers that have been requested consistently should be killed, but the
+ * details are not specified.
+ */
+@Public
+@Evolving
+public interface PreemptionMessage {
+
+ /**
+ * @return Specific resources that may be killed by the
+ * <code>ResourceManager</code>
+ */
+ @Public
+ @Evolving
+ public StrictPreemptionContract getStrictContract();
+
+ @Private
+ @Unstable
+ public void setStrictContract(StrictPreemptionContract set);
+
+ /**
+ * @return Contract describing resources to return to the cluster.
+ */
+ @Public
+ @Evolving
+ public PreemptionContract getContract();
+
+ @Private
+ @Unstable
+ public void setContract(PreemptionContract contract);
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionResourceRequest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionResourceRequest.java
new file mode 100644
index 0000000000000..1187fd8d25f4b
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/PreemptionResourceRequest.java
@@ -0,0 +1,45 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords;
+
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+import org.apache.hadoop.yarn.api.records.ResourceRequest;
+
+/**
+ * Description of resources requested back by the cluster.
+ * @see PreemptionContract
+ * @see AllocateRequest#setAskList(java.util.List)
+ */
+public interface PreemptionResourceRequest {
+
+ /**
+ * @return Resource described in this request, to be matched against running
+ * containers.
+ */
+ @Public
+ @Evolving
+ public ResourceRequest getResourceRequest();
+
+ @Private
+ @Unstable
+ public void setResourceRequest(ResourceRequest req);
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/StrictPreemptionContract.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/StrictPreemptionContract.java
new file mode 100644
index 0000000000000..11d7bb9f68b99
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/StrictPreemptionContract.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords;
+
+import java.util.Set;
+
+import org.apache.hadoop.classification.InterfaceAudience.Private;
+import org.apache.hadoop.classification.InterfaceAudience.Public;
+import org.apache.hadoop.classification.InterfaceStability.Evolving;
+import org.apache.hadoop.classification.InterfaceStability.Unstable;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+
+/**
+ * Enumeration of particular allocations to be reclaimed. The platform will
+ * reclaim exactly these resources, so the <code>ApplicationMaster</code> (AM)
+ * may attempt to checkpoint work or adjust its execution plan to accommodate
+ * it. In contrast to {@link PreemptionContract}, the AM has no flexibility in
+ * selecting which resources to return to the cluster.
+ * @see PreemptionMessage
+ */
+@Public
+@Evolving
+public interface StrictPreemptionContract {
+
+ /**
+ * Get the set of {@link PreemptionContainer} specifying containers owned by
+ * the <code>ApplicationMaster</code> that may be reclaimed by the
+ * <code>ResourceManager</code>.
+ * @return the set of {@link ContainerId} to be preempted.
+ */
+ @Public
+ @Evolving
+ public Set<PreemptionContainer> getContainers();
+
+ @Private
+ @Unstable
+ public void setContainers(Set<PreemptionContainer> containers);
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/AllocateResponsePBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/AllocateResponsePBImpl.java
index 4643e4ed02e19..dac8c73580d07 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/AllocateResponsePBImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/AllocateResponsePBImpl.java
@@ -24,6 +24,7 @@
import java.util.List;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionMessage;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeReport;
@@ -39,7 +40,7 @@
import org.apache.hadoop.yarn.proto.YarnProtos.ResourceProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.AllocateResponseProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.AllocateResponseProtoOrBuilder;
-
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionMessageProto;
public class AllocateResponsePBImpl extends ProtoBase<AllocateResponseProto>
@@ -54,6 +55,7 @@ public class AllocateResponsePBImpl extends ProtoBase<AllocateResponseProto>
private List<ContainerStatus> completedContainersStatuses = null;
private List<NodeReport> updatedNodes = null;
+ private PreemptionMessage preempt;
public AllocateResponsePBImpl() {
@@ -94,6 +96,9 @@ private synchronized void mergeLocalToBuilder() {
if (this.limit != null) {
builder.setLimit(convertToProtoFormat(this.limit));
}
+ if (this.preempt != null) {
+ builder.setPreempt(convertToProtoFormat(this.preempt));
+ }
}
private synchronized void mergeLocalToProto() {
@@ -217,6 +222,28 @@ public synchronized void setNumClusterNodes(int numNodes) {
builder.setNumClusterNodes(numNodes);
}
+ @Override
+ public synchronized PreemptionMessage getPreemptionMessage() {
+ AllocateResponseProtoOrBuilder p = viaProto ? proto : builder;
+ if (this.preempt != null) {
+ return this.preempt;
+ }
+ if (!p.hasPreempt()) {
+ return null;
+ }
+ this.preempt = convertFromProtoFormat(p.getPreempt());
+ return this.preempt;
+ }
+
+ @Override
+ public synchronized void setPreemptionMessage(PreemptionMessage preempt) {
+ maybeInitBuilder();
+ if (null == preempt) {
+ builder.clearPreempt();
+ }
+ this.preempt = preempt;
+ }
+
// Once this is called. updatedNodes will never be null - until a getProto is
// called.
private synchronized void initLocalNewNodeReportList() {
@@ -393,4 +420,11 @@ private synchronized ResourceProto convertToProtoFormat(Resource r) {
return ((ResourcePBImpl) r).getProto();
}
+ private synchronized PreemptionMessagePBImpl convertFromProtoFormat(PreemptionMessageProto p) {
+ return new PreemptionMessagePBImpl(p);
+ }
+
+ private synchronized PreemptionMessageProto convertToProtoFormat(PreemptionMessage r) {
+ return ((PreemptionMessagePBImpl)r).getProto();
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContainerPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContainerPBImpl.java
new file mode 100644
index 0000000000000..624d1270f4b7a
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContainerPBImpl.java
@@ -0,0 +1,103 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;
+
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionContainer;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.api.records.impl.pb.ContainerIdPBImpl;
+import org.apache.hadoop.yarn.proto.YarnProtos.ContainerIdProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContainerProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContainerProtoOrBuilder;
+
+public class PreemptionContainerPBImpl implements PreemptionContainer {
+
+ PreemptionContainerProto proto =
+ PreemptionContainerProto.getDefaultInstance();
+ PreemptionContainerProto.Builder builder = null;
+
+ boolean viaProto = false;
+ private ContainerId id;
+
+ public PreemptionContainerPBImpl() {
+ builder = PreemptionContainerProto.newBuilder();
+ }
+
+ public PreemptionContainerPBImpl(PreemptionContainerProto proto) {
+ this.proto = proto;
+ viaProto = true;
+ }
+
+ public synchronized PreemptionContainerProto getProto() {
+ mergeLocalToProto();
+ proto = viaProto ? proto : builder.build();
+ viaProto = true;
+ return proto;
+ }
+
+ private void mergeLocalToProto() {
+ if (viaProto)
+ maybeInitBuilder();
+ mergeLocalToBuilder();
+ proto = builder.build();
+ viaProto = true;
+ }
+
+ private void mergeLocalToBuilder() {
+ if (id != null) {
+ builder.setId(convertToProtoFormat(id));
+ }
+ }
+
+ private void maybeInitBuilder() {
+ if (viaProto || builder == null) {
+ builder = PreemptionContainerProto.newBuilder(proto);
+ }
+ viaProto = false;
+ }
+
+ @Override
+ public synchronized ContainerId getId() {
+ PreemptionContainerProtoOrBuilder p = viaProto ? proto : builder;
+ if (id != null) {
+ return id;
+ }
+ if (!p.hasId()) {
+ return null;
+ }
+ id = convertFromProtoFormat(p.getId());
+ return id;
+ }
+
+ @Override
+ public synchronized void setId(final ContainerId id) {
+ maybeInitBuilder();
+ if (null == id) {
+ builder.clearId();
+ }
+ this.id = id;
+ }
+
+ private ContainerIdPBImpl convertFromProtoFormat(ContainerIdProto p) {
+ return new ContainerIdPBImpl(p);
+ }
+
+ private ContainerIdProto convertToProtoFormat(ContainerId t) {
+ return ((ContainerIdPBImpl)t).getProto();
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContractPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContractPBImpl.java
new file mode 100644
index 0000000000000..61534365ca0ec
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionContractPBImpl.java
@@ -0,0 +1,228 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionContainer;
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionContract;
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionResourceRequest;
+import org.apache.hadoop.yarn.api.protocolrecords.impl.pb.PreemptionResourceRequestPBImpl;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContainerProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContractProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContractProtoOrBuilder;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionResourceRequestProto;
+
+public class PreemptionContractPBImpl implements PreemptionContract {
+
+ PreemptionContractProto proto = PreemptionContractProto.getDefaultInstance();
+ PreemptionContractProto.Builder builder = null;
+
+ boolean viaProto = false;
+ private Set<PreemptionContainer> containers;
+ private List<PreemptionResourceRequest> resources;
+
+ public PreemptionContractPBImpl() {
+ builder = PreemptionContractProto.newBuilder();
+ }
+
+ public PreemptionContractPBImpl(PreemptionContractProto proto) {
+ this.proto = proto;
+ viaProto = true;
+ }
+
+ public synchronized PreemptionContractProto getProto() {
+ mergeLocalToProto();
+ proto = viaProto ? proto : builder.build();
+ viaProto = true;
+ return proto;
+ }
+
+ private void mergeLocalToProto() {
+ if (viaProto)
+ maybeInitBuilder();
+ mergeLocalToBuilder();
+ proto = builder.build();
+ viaProto = true;
+ }
+
+ private void mergeLocalToBuilder() {
+ if (this.resources != null) {
+ addResourcesToProto();
+ }
+ if (this.containers != null) {
+ addContainersToProto();
+ }
+ }
+
+ private void maybeInitBuilder() {
+ if (viaProto || builder == null) {
+ builder = PreemptionContractProto.newBuilder(proto);
+ }
+ viaProto = false;
+ }
+
+ @Override
+ public synchronized Set<PreemptionContainer> getContainers() {
+ initPreemptionContainers();
+ return containers;
+ }
+
+ @Override
+ public synchronized void setContainers(
+ final Set<PreemptionContainer> containers) {
+ if (null == containers) {
+ builder.clearContainer();
+ }
+ this.containers = containers;
+ }
+
+ @Override
+ public synchronized List<PreemptionResourceRequest> getResourceRequest() {
+ initPreemptionResourceRequests();
+ return resources;
+ }
+
+ @Override
+ public synchronized void setResourceRequest(
+ final List<PreemptionResourceRequest> req) {
+ if (null == resources) {
+ builder.clearResource();
+ }
+ this.resources = req;
+ }
+
+ private void initPreemptionResourceRequests() {
+ if (resources != null) {
+ return;
+ }
+ PreemptionContractProtoOrBuilder p = viaProto ? proto : builder;
+ List<PreemptionResourceRequestProto> list = p.getResourceList();
+ resources = new ArrayList<PreemptionResourceRequest>();
+
+ for (PreemptionResourceRequestProto rr : list) {
+ resources.add(convertFromProtoFormat(rr));
+ }
+ }
+
+ private void addResourcesToProto() {
+ maybeInitBuilder();
+ builder.clearResource();
+ if (null == resources) {
+ return;
+ }
+ Iterable<PreemptionResourceRequestProto> iterable =
+ new Iterable<PreemptionResourceRequestProto>() {
+ @Override
+ public Iterator<PreemptionResourceRequestProto> iterator() {
+ return new Iterator<PreemptionResourceRequestProto>() {
+
+ Iterator<PreemptionResourceRequest> iter = resources.iterator();
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ @Override
+ public PreemptionResourceRequestProto next() {
+ return convertToProtoFormat(iter.next());
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+
+ }
+ };
+
+ }
+ };
+ builder.addAllResource(iterable);
+ }
+
+ private void initPreemptionContainers() {
+ if (containers != null) {
+ return;
+ }
+ PreemptionContractProtoOrBuilder p = viaProto ? proto : builder;
+ List<PreemptionContainerProto> list = p.getContainerList();
+ containers = new HashSet<PreemptionContainer>();
+
+ for (PreemptionContainerProto c : list) {
+ containers.add(convertFromProtoFormat(c));
+ }
+ }
+
+ private void addContainersToProto() {
+ maybeInitBuilder();
+ builder.clearContainer();
+ if (null == containers) {
+ return;
+ }
+ Iterable<PreemptionContainerProto> iterable =
+ new Iterable<PreemptionContainerProto>() {
+ @Override
+ public Iterator<PreemptionContainerProto> iterator() {
+ return new Iterator<PreemptionContainerProto>() {
+
+ Iterator<PreemptionContainer> iter = containers.iterator();
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ @Override
+ public PreemptionContainerProto next() {
+ return convertToProtoFormat(iter.next());
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+
+ }
+ };
+
+ }
+ };
+ builder.addAllContainer(iterable);
+ }
+
+ private PreemptionContainerPBImpl convertFromProtoFormat(PreemptionContainerProto p) {
+ return new PreemptionContainerPBImpl(p);
+ }
+
+ private PreemptionContainerProto convertToProtoFormat(PreemptionContainer t) {
+ return ((PreemptionContainerPBImpl)t).getProto();
+ }
+
+ private PreemptionResourceRequestPBImpl convertFromProtoFormat(PreemptionResourceRequestProto p) {
+ return new PreemptionResourceRequestPBImpl(p);
+ }
+
+ private PreemptionResourceRequestProto convertToProtoFormat(PreemptionResourceRequest t) {
+ return ((PreemptionResourceRequestPBImpl)t).getProto();
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionMessagePBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionMessagePBImpl.java
new file mode 100644
index 0000000000000..72a7eb151ffb3
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionMessagePBImpl.java
@@ -0,0 +1,141 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;
+
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionContract;
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionMessage;
+import org.apache.hadoop.yarn.api.protocolrecords.StrictPreemptionContract;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContractProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionMessageProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionMessageProtoOrBuilder;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.StrictPreemptionContractProto;
+
+public class PreemptionMessagePBImpl implements PreemptionMessage {
+
+ PreemptionMessageProto proto = PreemptionMessageProto.getDefaultInstance();
+ PreemptionMessageProto.Builder builder = null;
+
+ boolean viaProto = false;
+ private StrictPreemptionContract strict;
+ private PreemptionContract contract;
+
+ public PreemptionMessagePBImpl() {
+ builder = PreemptionMessageProto.newBuilder();
+ }
+
+ public PreemptionMessagePBImpl(PreemptionMessageProto proto) {
+ this.proto = proto;
+ viaProto = true;
+ }
+
+ public synchronized PreemptionMessageProto getProto() {
+ mergeLocalToProto();
+ proto = viaProto ? proto : builder.build();
+ viaProto = true;
+ return proto;
+ }
+
+ private void mergeLocalToProto() {
+ if (viaProto)
+ maybeInitBuilder();
+ mergeLocalToBuilder();
+ proto = builder.build();
+ viaProto = true;
+ }
+
+ private void mergeLocalToBuilder() {
+ if (strict != null) {
+ builder.setStrictContract(convertToProtoFormat(strict));
+ }
+ if (contract != null) {
+ builder.setContract(convertToProtoFormat(contract));
+ }
+ }
+
+ private void maybeInitBuilder() {
+ if (viaProto || builder == null) {
+ builder = PreemptionMessageProto.newBuilder(proto);
+ }
+ viaProto = false;
+ }
+
+ @Override
+ public synchronized StrictPreemptionContract getStrictContract() {
+ PreemptionMessageProtoOrBuilder p = viaProto ? proto : builder;
+ if (strict != null) {
+ return strict;
+ }
+ if (!p.hasStrictContract()) {
+ return null;
+ }
+ strict = convertFromProtoFormat(p.getStrictContract());
+ return strict;
+ }
+
+ @Override
+ public synchronized void setStrictContract(StrictPreemptionContract strict) {
+ maybeInitBuilder();
+ if (null == strict) {
+ builder.clearStrictContract();
+ }
+ this.strict = strict;
+ }
+
+ @Override
+ public synchronized PreemptionContract getContract() {
+ PreemptionMessageProtoOrBuilder p = viaProto ? proto : builder;
+ if (contract != null) {
+ return contract;
+ }
+ if (!p.hasContract()) {
+ return null;
+ }
+ contract = convertFromProtoFormat(p.getContract());
+ return contract;
+ }
+
+ @Override
+ public synchronized void setContract(final PreemptionContract c) {
+ maybeInitBuilder();
+ if (null == c) {
+ builder.clearContract();
+ }
+ this.contract = c;
+ }
+
+ private StrictPreemptionContractPBImpl convertFromProtoFormat(
+ StrictPreemptionContractProto p) {
+ return new StrictPreemptionContractPBImpl(p);
+ }
+
+ private StrictPreemptionContractProto convertToProtoFormat(
+ StrictPreemptionContract t) {
+ return ((StrictPreemptionContractPBImpl)t).getProto();
+ }
+
+ private PreemptionContractPBImpl convertFromProtoFormat(
+ PreemptionContractProto p) {
+ return new PreemptionContractPBImpl(p);
+ }
+
+ private PreemptionContractProto convertToProtoFormat(
+ PreemptionContract t) {
+ return ((PreemptionContractPBImpl)t).getProto();
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionResourceRequestPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionResourceRequestPBImpl.java
new file mode 100644
index 0000000000000..8b6ca2d4f6089
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/PreemptionResourceRequestPBImpl.java
@@ -0,0 +1,103 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;
+
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionResourceRequest;
+import org.apache.hadoop.yarn.api.records.ResourceRequest;
+import org.apache.hadoop.yarn.api.records.impl.pb.ResourceRequestPBImpl;
+import org.apache.hadoop.yarn.proto.YarnProtos.ResourceRequestProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionResourceRequestProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionResourceRequestProtoOrBuilder;
+
+public class PreemptionResourceRequestPBImpl implements PreemptionResourceRequest {
+
+ PreemptionResourceRequestProto proto =
+ PreemptionResourceRequestProto.getDefaultInstance();
+ PreemptionResourceRequestProto.Builder builder = null;
+
+ boolean viaProto = false;
+ private ResourceRequest rr;
+
+ public PreemptionResourceRequestPBImpl() {
+ builder = PreemptionResourceRequestProto.newBuilder();
+ }
+
+ public PreemptionResourceRequestPBImpl(PreemptionResourceRequestProto proto) {
+ this.proto = proto;
+ viaProto = true;
+ }
+
+ public synchronized PreemptionResourceRequestProto getProto() {
+ mergeLocalToProto();
+ proto = viaProto ? proto : builder.build();
+ viaProto = true;
+ return proto;
+ }
+
+ private void mergeLocalToProto() {
+ if (viaProto)
+ maybeInitBuilder();
+ mergeLocalToBuilder();
+ proto = builder.build();
+ viaProto = true;
+ }
+
+ private void mergeLocalToBuilder() {
+ if (rr != null) {
+ builder.setResource(convertToProtoFormat(rr));
+ }
+ }
+
+ private void maybeInitBuilder() {
+ if (viaProto || builder == null) {
+ builder = PreemptionResourceRequestProto.newBuilder(proto);
+ }
+ viaProto = false;
+ }
+
+ @Override
+ public synchronized ResourceRequest getResourceRequest() {
+ PreemptionResourceRequestProtoOrBuilder p = viaProto ? proto : builder;
+ if (rr != null) {
+ return rr;
+ }
+ if (!p.hasResource()) {
+ return null;
+ }
+ rr = convertFromProtoFormat(p.getResource());
+ return rr;
+ }
+
+ @Override
+ public synchronized void setResourceRequest(final ResourceRequest rr) {
+ maybeInitBuilder();
+ if (null == rr) {
+ builder.clearResource();
+ }
+ this.rr = rr;
+ }
+
+ private ResourceRequestPBImpl convertFromProtoFormat(ResourceRequestProto p) {
+ return new ResourceRequestPBImpl(p);
+ }
+
+ private ResourceRequestProto convertToProtoFormat(ResourceRequest t) {
+ return ((ResourceRequestPBImpl)t).getProto();
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/StrictPreemptionContractPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/StrictPreemptionContractPBImpl.java
new file mode 100644
index 0000000000000..7759ba22c2ec4
--- /dev/null
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/StrictPreemptionContractPBImpl.java
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionContainer;
+import org.apache.hadoop.yarn.api.protocolrecords.StrictPreemptionContract;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.PreemptionContainerProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.StrictPreemptionContractProto;
+import org.apache.hadoop.yarn.proto.YarnServiceProtos.StrictPreemptionContractProtoOrBuilder;
+
+public class StrictPreemptionContractPBImpl implements StrictPreemptionContract {
+
+ StrictPreemptionContractProto proto =
+ StrictPreemptionContractProto.getDefaultInstance();
+ StrictPreemptionContractProto.Builder builder = null;
+
+ boolean viaProto = false;
+ private Set<PreemptionContainer> containers;
+
+ public StrictPreemptionContractPBImpl() {
+ builder = StrictPreemptionContractProto.newBuilder();
+ }
+
+ public StrictPreemptionContractPBImpl(StrictPreemptionContractProto proto) {
+ this.proto = proto;
+ viaProto = true;
+ }
+
+ public synchronized StrictPreemptionContractProto getProto() {
+ mergeLocalToProto();
+ proto = viaProto ? proto : builder.build();
+ viaProto = true;
+ return proto;
+ }
+
+ private void mergeLocalToProto() {
+ if (viaProto)
+ maybeInitBuilder();
+ mergeLocalToBuilder();
+ proto = builder.build();
+ viaProto = true;
+ }
+
+ private void mergeLocalToBuilder() {
+ if (this.containers != null) {
+ addContainersToProto();
+ }
+ }
+
+ private void maybeInitBuilder() {
+ if (viaProto || builder == null) {
+ builder = StrictPreemptionContractProto.newBuilder(proto);
+ }
+ viaProto = false;
+ }
+
+ @Override
+ public synchronized Set<PreemptionContainer> getContainers() {
+ initIds();
+ return containers;
+ }
+
+ @Override
+ public synchronized void setContainers(
+ final Set<PreemptionContainer> containers) {
+ if (null == containers) {
+ builder.clearContainer();
+ }
+ this.containers = containers;
+ }
+
+ private void initIds() {
+ if (containers != null) {
+ return;
+ }
+ StrictPreemptionContractProtoOrBuilder p = viaProto ? proto : builder;
+ List<PreemptionContainerProto> list = p.getContainerList();
+ containers = new HashSet<PreemptionContainer>();
+
+ for (PreemptionContainerProto c : list) {
+ containers.add(convertFromProtoFormat(c));
+ }
+ }
+
+ private void addContainersToProto() {
+ maybeInitBuilder();
+ builder.clearContainer();
+ if (containers == null) {
+ return;
+ }
+ Iterable<PreemptionContainerProto> iterable = new Iterable<PreemptionContainerProto>() {
+ @Override
+ public Iterator<PreemptionContainerProto> iterator() {
+ return new Iterator<PreemptionContainerProto>() {
+
+ Iterator<PreemptionContainer> iter = containers.iterator();
+
+ @Override
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ @Override
+ public PreemptionContainerProto next() {
+ return convertToProtoFormat(iter.next());
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+
+ }
+ };
+
+ }
+ };
+ builder.addAllContainer(iterable);
+ }
+
+ private PreemptionContainerPBImpl convertFromProtoFormat(PreemptionContainerProto p) {
+ return new PreemptionContainerPBImpl(p);
+ }
+
+ private PreemptionContainerProto convertToProtoFormat(PreemptionContainer t) {
+ return ((PreemptionContainerPBImpl)t).getProto();
+ }
+
+}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/proto/yarn_service_protos.proto b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/proto/yarn_service_protos.proto
index ad3b5f180720f..6ac02741bac15 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/proto/yarn_service_protos.proto
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/proto/yarn_service_protos.proto
@@ -66,9 +66,30 @@ message AllocateResponseProto {
optional ResourceProto limit = 5;
repeated NodeReportProto updated_nodes = 6;
optional int32 num_cluster_nodes = 7;
+ optional PreemptionMessageProto preempt = 8;
}
+message PreemptionMessageProto {
+ optional StrictPreemptionContractProto strictContract = 1;
+ optional PreemptionContractProto contract = 2;
+}
+
+message StrictPreemptionContractProto {
+ repeated PreemptionContainerProto container = 1;
+}
+
+message PreemptionContractProto {
+ repeated PreemptionResourceRequestProto resource = 1;
+ repeated PreemptionContainerProto container = 2;
+}
+
+message PreemptionContainerProto {
+ optional ContainerIdProto id = 1;
+}
+message PreemptionResourceRequestProto {
+ optional ResourceRequestProto resource = 1;
+}
//////////////////////////////////////////////////////
/////// client_RM_Protocol ///////////////////////////
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestAMRMClientAsync.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestAMRMClientAsync.java
index d95ce64f6303b..ff2c0a441a9bf 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestAMRMClientAsync.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestAMRMClientAsync.java
@@ -113,7 +113,7 @@ public AllocateResponse answer(InvocationOnMock invocation)
private AllocateResponse createAllocateResponse(
List<ContainerStatus> completed, List<Container> allocated) {
AllocateResponse response = BuilderUtils.newAllocateResponse(0, completed, allocated,
- new ArrayList<NodeReport>(), null, false, 1);
+ new ArrayList<NodeReport>(), null, false, 1, null);
return response;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/BuilderUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/BuilderUtils.java
index f09046e37126f..e6699f3927896 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/BuilderUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/BuilderUtils.java
@@ -29,6 +29,7 @@
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
+import org.apache.hadoop.yarn.api.protocolrecords.PreemptionMessage;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
@@ -404,7 +405,8 @@ public static AllocateRequest newAllocateRequest(
public static AllocateResponse newAllocateResponse(int responseId,
List<ContainerStatus> completedContainers,
List<Container> allocatedContainers, List<NodeReport> updatedNodes,
- Resource availResources, boolean reboot, int numClusterNodes) {
+ Resource availResources, boolean reboot, int numClusterNodes,
+ PreemptionMessage preempt) {
AllocateResponse response = recordFactory
.newRecordInstance(AllocateResponse.class);
response.setNumClusterNodes(numClusterNodes);
@@ -414,6 +416,7 @@ public static AllocateResponse newAllocateResponse(int responseId,
response.setUpdatedNodes(updatedNodes);
response.setAvailableResources(availResources);
response.setReboot(reboot);
+ response.setPreemptionMessage(preempt);
return response;
}
|
6c476cacc6dfa22e79e7da0b0f9b7a51c965d8d4
|
brandonborkholder$glg2d
|
Moved some polyline/gon code into the shape-drawer support class.
I tried to get text rendering, but it's not correct yet.
|
a
|
https://github.com/brandonborkholder/glg2d
|
diff --git a/src/joglg2d/JOGLG2D.java b/src/joglg2d/JOGLG2D.java
index d9f48e6d..2da29d57 100644
--- a/src/joglg2d/JOGLG2D.java
+++ b/src/joglg2d/JOGLG2D.java
@@ -26,10 +26,15 @@
import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.Map;
+import java.util.WeakHashMap;
import javax.media.opengl.GL;
+import com.sun.opengl.util.j2d.TextRenderer;
+
public class JOGLG2D extends Graphics2D implements Cloneable {
+ private static final Map<Font, TextRenderer> TEXT_RENDER_CACHE = new WeakHashMap<Font, TextRenderer>();
+
private final GL gl;
private final int height;
@@ -59,6 +64,7 @@ public JOGLG2D(GL gl, int height) {
protected void paint(Component component) {
setBackground(component.getBackground());
+ setStroke(new BasicStroke());
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glPushMatrix();
gl.glTranslatef(0, height, 0);
@@ -97,33 +103,41 @@ public void drawRenderableImage(RenderableImage img, AffineTransform xform) {
@Override
public void drawString(String str, int x, int y) {
- // TODO Auto-generated method stub
+ drawString(str, (float) x, (float) y);
}
@Override
public void drawString(String str, float x, float y) {
- // TODO Auto-generated method stub
+ TextRenderer renderer = TEXT_RENDER_CACHE.get(font);
+ if (renderer == null) {
+ renderer = new TextRenderer(font);
+ TEXT_RENDER_CACHE.put(font, renderer);
+ }
+
+ renderer.setColor(color);
+ renderer.begin3DRendering();
+ renderer.draw3D(str, x, y, 0, 1);
+ renderer.end3DRendering();
}
@Override
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
- // TODO Auto-generated method stub
+ assert false : "Operation not supported";
}
@Override
public void drawString(AttributedCharacterIterator iterator, float x, float y) {
- // TODO Auto-generated method stub
+ assert false : "Operation not supported";
}
@Override
public void drawGlyphVector(GlyphVector g, float x, float y) {
- // TODO Auto-generated method stub
-
+ shapeDrawer.fill(g.getOutline(x, y));
}
@Override
public void fill(Shape s) {
- shapeDrawer.fill(s, stroke);
+ shapeDrawer.fill(s);
}
@Override
@@ -422,32 +436,17 @@ public void fillArc(int x, int y, int width, int height, int startAngle, int arc
@Override
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
- gl.glBegin(GL.GL_LINE_STRIP);
- for (int i = 0; i < nPoints; i++) {
- gl.glVertex2i(xPoints[i], yPoints[i]);
- }
-
- gl.glEnd();
+ shapeDrawer.drawPolyline(xPoints, yPoints, nPoints, stroke);
}
@Override
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
- gl.glBegin(GL.GL_LINE_LOOP);
- for (int i = 0; i < nPoints; i++) {
- gl.glVertex2i(xPoints[i], yPoints[i]);
- }
-
- gl.glEnd();
+ shapeDrawer.drawPolygon(xPoints, yPoints, nPoints, false, stroke);
}
@Override
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
- gl.glBegin(GL.GL_POLYGON);
- for (int i = 0; i < nPoints; i++) {
- gl.glVertex2i(xPoints[i], yPoints[i]);
- }
-
- gl.glEnd();
+ shapeDrawer.drawPolygon(xPoints, yPoints, nPoints, true, stroke);
}
@Override
@@ -489,7 +488,12 @@ public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1,
@Override
public void dispose() {
- // TODO Auto-generated method stub
+ // just set everything to null to allow garbage collection
+ color = null;
+ background = null;
+ shapeDrawer = null;
+ transform = null;
+ stroke = null;
}
@Override
diff --git a/src/joglg2d/JOGLPathIterator.java b/src/joglg2d/JOGLPathIterator.java
index 3c848d38..faeae72c 100644
--- a/src/joglg2d/JOGLPathIterator.java
+++ b/src/joglg2d/JOGLPathIterator.java
@@ -5,6 +5,7 @@
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
+import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
@@ -67,19 +68,38 @@ public void drawArc(int x, int y, int width, int height, int startAngle, int arc
draw(ARC, stroke, fill);
}
+ public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints, Stroke stroke) {
+ Path2D.Float path = new Path2D.Float(PathIterator.WIND_NON_ZERO, nPoints);
+ path.moveTo(xPoints[0], yPoints[0]);
+ for (int i = 1; i < nPoints; i++) {
+ path.lineTo(xPoints[i], yPoints[i]);
+ }
+
+ fill(stroke.createStrokedShape(path));
+ }
+
+ public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints, boolean fill, Stroke stroke) {
+ gl.glBegin(fill ? GL.GL_POLYGON : GL.GL_LINE_LOOP);
+ for (int i = 0; i < nPoints; i++) {
+ gl.glVertex2i(xPoints[i], yPoints[i]);
+ }
+
+ gl.glEnd();
+ }
+
private void draw(Shape shape, Stroke stroke, boolean fill) {
if (fill) {
- fill(shape, stroke);
+ fill(shape);
} else {
draw(shape, stroke);
}
}
public void draw(Shape shape, Stroke stroke) {
- fill(stroke.createStrokedShape(shape), stroke);
+ fill(stroke.createStrokedShape(shape));
}
- public void fill(Shape shape, Stroke stroke) {
+ public void fill(Shape shape) {
PathIterator iterator = shape.getPathIterator(null);
final GLU glu = new GLU();
GLUtessellator tesselator = glu.gluNewTess();
diff --git a/test/joglg2d/VisualTest.java b/test/joglg2d/VisualTest.java
index 99ea20dd..788acbd9 100644
--- a/test/joglg2d/VisualTest.java
+++ b/test/joglg2d/VisualTest.java
@@ -117,4 +117,54 @@ public void paint(Graphics2D g2d) {
tester.assertSame();
}
+
+ @Test
+ public void drawPolylineTest() throws Exception {
+ tester.setPainter(new Painter() {
+ @Override
+ public void paint(Graphics2D g2d) {
+ g2d.setStroke(new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND));
+ g2d.drawPolyline(new int[] {8, 43, 94, 16}, new int[] {43, 99, 34, 75}, 4);
+ }
+ });
+
+ tester.assertSame();
+ }
+
+ @Test
+ public void drawPolygonTest() throws Exception {
+ tester.setPainter(new Painter() {
+ @Override
+ public void paint(Graphics2D g2d) {
+ g2d.drawPolygon(new int[] {8, 23, 98, 42}, new int[] {47, 23, 43, 25}, 4);
+ }
+ });
+
+ tester.assertSame();
+ }
+
+ @Test
+ public void fillPolygonTest() throws Exception {
+ tester.setPainter(new Painter() {
+ @Override
+ public void paint(Graphics2D g2d) {
+ g2d.setColor(Color.CYAN);
+ g2d.fillPolygon(new int[] {8, 23, 98, 42}, new int[] {47, 23, 43, 25}, 4);
+ }
+ });
+
+ tester.assertSame();
+ }
+
+ @Test
+ public void drawStringTest() throws Exception {
+ tester.setPainter(new Painter() {
+ @Override
+ public void paint(Graphics2D g2d) {
+ g2d.drawString("Hello JOGL", 90, 32);
+ }
+ });
+
+ tester.assertSame();
+ }
}
|
57cf199d7477ddba4c623960c265f356304f4045
|
drools
|
fix WELD problem caused by having a beans.xml in- drools-compiler--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-compiler/src/main/resources/META-INF/beans.xml b/drools-compiler/src/main/resources/META-INF/beans.xml
deleted file mode 100644
index b87599caa0a..00000000000
--- a/drools-compiler/src/main/resources/META-INF/beans.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
-</beans>
\ No newline at end of file
diff --git a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java
index 2a3de24eb45..b43c20a870e 100644
--- a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java
+++ b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java
@@ -250,6 +250,12 @@ public void testCompileAndCDI() throws IOException,
File fle1 = fld1.getFile( "KProjectTestClassImpl.java" );
fle1.create( new ByteArrayInputStream( generateKProjectTestClassImpl( kproj ).getBytes() ) );
+ Folder fld2 = trgMfs.getFolder( "META-INF" );
+ fld2.create();
+ File fle2 = fld2.getFile( "beans.xml" );
+ fle2.create( new ByteArrayInputStream( generateBeansXML( kproj ).getBytes() ) );
+
+
List<String> inputClasses = new ArrayList<String>();
inputClasses.add( "org/drools/cdi/test/KProjectTestClassImpl.java" );
@@ -445,6 +451,14 @@ public String generateKProjectTestClassImpl(KProject kproject) {
return s;
}
+ public String generateBeansXML(KProject kproject) {
+ String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+ "<beans xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd\">\n" +
+ "</beans>";
+
+ return s;
+ }
+
public static String filenameToClassname(String filename) {
return filename.substring( 0, filename.lastIndexOf( ".java" ) ).replace( '/', '.' ).replace( '\\', '.' );
}
|
a7a67f1a1adc33e6f629bd1aa9aaa92170eda88e
|
intellij-community
|
ChangeUtil-encode/decodeInformation for groovy--
|
a
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyLoader.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyLoader.java
index 55e049e160fdd..b31bd64c0657e 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyLoader.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/GroovyLoader.java
@@ -27,6 +27,8 @@
import com.intellij.openapi.project.ProjectManagerAdapter;
import static com.intellij.patterns.PlatformPatterns.psiElement;
import com.intellij.psi.PsiElement;
+import com.intellij.psi.impl.source.tree.ChangeUtil;
+import org.jetbrains.plugins.groovy.lang.GroovyChangeUtilSupport;
import com.intellij.refactoring.rename.RenameInputValidator;
import com.intellij.refactoring.rename.RenameInputValidatorRegistry;
import com.intellij.util.Function;
@@ -53,6 +55,8 @@ public class GroovyLoader implements ApplicationComponent {
public void initComponent() {
GroovyEditorActionsManager.registerGroovyEditorActions();
+ ChangeUtil.registerCopyHandler(new GroovyChangeUtilSupport());
+
//Register Keyword completion
setupCompletion();
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java
new file mode 100644
index 0000000000000..29cf02a2831c5
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java
@@ -0,0 +1,76 @@
+/*
+ * @author max
+ */
+package org.jetbrains.plugins.groovy.lang;
+
+import com.intellij.lang.ASTNode;
+import com.intellij.openapi.util.Key;
+import com.intellij.psi.*;
+import com.intellij.psi.impl.source.SourceTreeToPsiMap;
+import com.intellij.psi.impl.source.tree.CompositeElement;
+import com.intellij.psi.impl.source.tree.TreeCopyHandler;
+import com.intellij.psi.impl.source.tree.TreeElement;
+import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
+import org.jetbrains.plugins.groovy.lang.parser.GroovyReferenceAdjuster;
+import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement;
+import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
+import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
+
+import java.util.Map;
+
+/**
+ * @author peter
+ */
+public class GroovyChangeUtilSupport implements TreeCopyHandler {
+
+ public TreeElement decodeInformation(TreeElement element, final Map<Object, Object> decodingState) {
+ if (element instanceof CompositeElement) {
+ if (element.getElementType() == GroovyElementTypes.REFERENCE_ELEMENT ||
+ element.getElementType() == GroovyElementTypes.REFERENCE_EXPRESSION) {
+ GrReferenceElement ref = (GrReferenceElement)SourceTreeToPsiMap.treeElementToPsi(element);
+ final PsiMember refMember = element.getCopyableUserData(REFERENCED_MEMBER_KEY);
+ if (refMember != null) {
+ element.putCopyableUserData(REFERENCED_MEMBER_KEY, null);
+ PsiElement refElement1 = ref.resolve();
+ if (!refMember.getManager().areElementsEquivalent(refMember, refElement1)) {
+ try {
+ if (!(refMember instanceof PsiClass) || ref.getQualifier() == null) {
+ // can restore only if short (otherwise qualifier should be already restored)
+ ref = (GrReferenceElement)ref.bindToElement(refMember);
+ }
+ }
+ catch (IncorrectOperationException ignored) {
+ }
+ return (TreeElement)SourceTreeToPsiMap.psiElementToTree(ref);
+ } else {
+ // shorten references to the same package and to inner classes that can be accessed by short name
+ GroovyReferenceAdjuster.INSTANCE.process(element, false, false);
+ }
+ }
+ return element;
+ }
+ }
+ return null;
+ }
+
+ public void encodeInformation(final TreeElement element, final ASTNode original, final Map<Object, Object> encodingState) {
+ if (original instanceof CompositeElement) {
+ if (original.getElementType() == GroovyElementTypes.REFERENCE_ELEMENT || original.getElementType() == GroovyElementTypes.REFERENCE_EXPRESSION) {
+ final GroovyResolveResult result = ((GrReferenceElement)original.getPsi()).advancedResolve();
+ if (result != null) {
+ final PsiElement target = result.getElement();
+
+ if (target instanceof PsiClass ||
+ (target instanceof PsiMethod || target instanceof PsiField) &&
+ ((PsiMember) target).hasModifierProperty(PsiModifier.STATIC) &&
+ result.getCurrentFileResolveContext() instanceof GrImportStatement) {
+ element.putCopyableUserData(REFERENCED_MEMBER_KEY, (PsiMember) target);
+ }
+ }
+ }
+ }
+ }
+
+ private static final Key<PsiMember> REFERENCED_MEMBER_KEY = Key.create("REFERENCED_MEMBER_KEY");
+}
\ No newline at end of file
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java
index 32fd42f5bfdf7..12cea7247ff66 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/PsiUtil.java
@@ -405,9 +405,10 @@ private static void doShorten(PsiElement element) {
}
public static void shortenReference(GrCodeReferenceElement ref) {
- if (ref.getQualifier() != null && mayShorten(ref)) {
+ if (ref.getQualifier() != null && (PsiTreeUtil.getParentOfType(ref, GrDocMemberReference.class) != null ||
+ PsiTreeUtil.getParentOfType(ref, GrDocComment.class) == null)) {
final PsiElement resolved = ref.resolve();
- if (resolved instanceof PsiClass) {
+ if (resolved instanceof PsiClass && mayShorten(ref)) {
ref.setQualifier(null);
try {
ref.bindToElement(resolved);
@@ -419,9 +420,21 @@ public static void shortenReference(GrCodeReferenceElement ref) {
}
}
- private static boolean mayShorten(GrCodeReferenceElement ref) {
- if (PsiTreeUtil.getParentOfType(ref, GrDocMemberReference.class) != null) return true;
- return PsiTreeUtil.getParentOfType(ref, GrDocComment.class) == null;
+ private static boolean mayShorten(@NotNull GrCodeReferenceElement ref) {
+ GrCodeReferenceElement cur = (GrCodeReferenceElement)ref.copy();
+ while (true) {
+ final GrCodeReferenceElement qualifier = cur.getQualifier();
+ if (qualifier == null) {
+ return true;
+ }
+ if (!(qualifier.resolve() instanceof PsiClass)) {
+ final PsiClass correctResolved = (PsiClass)cur.resolve();
+ cur.setQualifier(null);
+ final PsiClass rawResolved = (PsiClass)cur.resolve();
+ return rawResolved == null || cur.getManager().areElementsEquivalent(correctResolved, rawResolved);
+ }
+ cur = qualifier;
+ }
}
@Nullable
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyChangeContextUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyChangeContextUtil.java
index a0a630d449cd9..c194f9225fbfc 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyChangeContextUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/GroovyChangeContextUtil.java
@@ -23,8 +23,6 @@
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrThisReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
-import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClassTypeElement;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
/**
* @author Maxim.Medvedev
@@ -91,6 +89,7 @@ public static void decodeContextInfo(PsiElement element, PsiClass thisClass, GrE
return;
}
}
+ /*
else if (element instanceof GrReferenceExpression) {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
final GrReferenceExpression refExpr = (GrReferenceExpression)element;
@@ -119,8 +118,9 @@ else if (thisAccessExpr instanceof GrReferenceExpression) {
}
}
}
+ */
- PsiClass refClass = element.getCopyableUserData(REF_TO_CLASS);
+ /*PsiClass refClass = element.getCopyableUserData(REF_TO_CLASS);
element.putCopyableUserData(REF_TO_CLASS, null);
if (refClass != null && refClass.isValid()) {
@@ -128,7 +128,7 @@ else if (thisAccessExpr instanceof GrReferenceExpression) {
if (ref != null) {
ref.bindToElement(refClass);
}
- }
+ }*/
}
}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyClassHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyClassHandler.java
index c27e3f2c04728..955dca3e01076 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyClassHandler.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/move/MoveGroovyClassHandler.java
@@ -17,9 +17,11 @@
package org.jetbrains.plugins.groovy.refactoring.move;
import com.intellij.psi.*;
-import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.impl.source.tree.Factory;
+import com.intellij.psi.impl.source.tree.TreeElement;
import com.intellij.psi.javadoc.PsiDocComment;
+import com.intellij.psi.search.LocalSearchScope;
+import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.MoveDestination;
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassHandler;
import com.intellij.util.IncorrectOperationException;
@@ -27,11 +29,9 @@
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.actions.GroovyTemplatesFactory;
import org.jetbrains.plugins.groovy.actions.NewGroovyActionBase;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor;
-import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
+import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
import org.jetbrains.plugins.groovy.refactoring.GroovyChangeContextUtil;
/**
@@ -87,42 +87,24 @@ else if (!newDirectory.equals(file.getContainingDirectory()) && newDirectory.fin
}
private static void correctOldClassReferences(final PsiClass newClass, final PsiClass oldClass) {
- ((GroovyPsiElement)newClass).accept(new GroovyRecursiveElementVisitor() {
- @Override
- public void visitReferenceExpression(GrReferenceExpression reference) {
- if (reference.isReferenceTo(oldClass)) {
- try {
- reference.bindToElement(newClass);
- }
- catch (IncorrectOperationException e) {
- //here is an exception
- }
- }
- super.visitReferenceExpression(reference);
- }
- });
+ for (PsiReference reference : ReferencesSearch.search(oldClass, new LocalSearchScope(newClass)).findAll()) {
+ reference.bindToElement(newClass);
+ }
}
private static void correctSelfReferences(final PsiClass aClass, final PsiPackage newContainingPackage) {
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(aClass.getContainingFile().getContainingDirectory());
- if (aPackage != null) {
- ((GroovyPsiElement)aClass).accept(new GroovyRecursiveElementVisitor() {
- @Override
- public void visitReferenceExpression(GrReferenceExpression reference) {
- if (reference.isQualified() && reference.isReferenceTo(aClass)) {
- final PsiElement qualifier = reference.getQualifier();
- if (qualifier instanceof PsiJavaCodeReferenceElement && ((PsiJavaCodeReferenceElement)qualifier).isReferenceTo(aPackage)) {
- try {
- ((PsiJavaCodeReferenceElement)qualifier).bindToElement(newContainingPackage);
- }
- catch (IncorrectOperationException e) {
- //here is an exception
- }
- }
- }
- super.visitReferenceExpression(reference);
+ if (aPackage == null) {
+ return;
+ }
+
+ for (PsiReference reference : ReferencesSearch.search(aClass, new LocalSearchScope(aClass)).findAll()) {
+ if (reference instanceof GrCodeReferenceElement) {
+ final GrCodeReferenceElement qualifier = ((GrCodeReferenceElement)reference).getQualifier();
+ if (qualifier != null) {
+ qualifier.bindToElement(newContainingPackage);
}
- });
+ }
}
}
diff --git a/plugins/groovy/testdata/refactoring/move/moveClass/ideadev27996/after/pack2/X.groovy b/plugins/groovy/testdata/refactoring/move/moveClass/ideadev27996/after/pack2/X.groovy
index 7fff3ec5d135c..2aaf40c5b6eca 100644
--- a/plugins/groovy/testdata/refactoring/move/moveClass/ideadev27996/after/pack2/X.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveClass/ideadev27996/after/pack2/X.groovy
@@ -1,4 +1,5 @@
package pack2
+
public class X {
public void foo(X x) {}
}
\ No newline at end of file
diff --git a/plugins/groovy/testdata/refactoring/move/moveClass/moveMultiple1/after/pack2/Class1.groovy b/plugins/groovy/testdata/refactoring/move/moveClass/moveMultiple1/after/pack2/Class1.groovy
index 54e4d0eddd4aa..02b02d6239efe 100644
--- a/plugins/groovy/testdata/refactoring/move/moveClass/moveMultiple1/after/pack2/Class1.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveClass/moveMultiple1/after/pack2/Class1.groovy
@@ -1,4 +1,4 @@
-package pack2
+package pack2;
public class Class1 {
Class2 a;
|
43b5767f6213784c7e4cdfce2bebadd87108b33f
|
hbase
|
HBASE-10606 Bad timeout in- RpcRetryingCaller-callWithRetries w/o parameters--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1572124 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
index 8b2df053f67c..bf89fe276bd2 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java
@@ -33,7 +33,6 @@
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -49,7 +48,6 @@
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
-import org.apache.hadoop.hbase.util.Pair;
import org.cloudera.htrace.Trace;
import com.google.common.annotations.VisibleForTesting;
@@ -118,8 +116,6 @@ public static interface AsyncRequestFuture {
public void waitUntilDone() throws InterruptedIOException {}
};
-
- // TODO: many of the fields should be made private
protected final long id;
protected final ClusterConnection hConnection;
@@ -156,6 +152,7 @@ public void waitUntilDone() throws InterruptedIOException {}
protected final long pause;
protected int numTries;
protected int serverTrackerTimeout;
+ protected int operationTimeout;
// End configuration settings.
protected static class BatchErrors {
@@ -206,6 +203,8 @@ public AsyncProcess(ClusterConnection hc, Configuration conf, ExecutorService po
HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
this.numTries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
+ this.operationTimeout = conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
this.maxTotalConcurrentTasks = conf.getInt(HConstants.HBASE_CLIENT_MAX_TOTAL_TASKS,
HConstants.DEFAULT_HBASE_CLIENT_MAX_TOTAL_TASKS);
@@ -303,14 +302,12 @@ public <CResult> AsyncRequestFuture submit(ExecutorService pool, TableName table
Iterator<? extends Row> it = rows.iterator();
while (it.hasNext()) {
Row r = it.next();
- HRegionLocation loc = null;
+ HRegionLocation loc;
try {
loc = findDestLocation(tableName, r);
} catch (IOException ex) {
- if (locationErrors == null) {
- locationErrors = new ArrayList<Exception>();
- locationErrorRows = new ArrayList<Integer>();
- }
+ locationErrors = new ArrayList<Exception>();
+ locationErrorRows = new ArrayList<Integer>();
LOG.error("Failed to get region location ", ex);
// This action failed before creating ars. Add it to retained but do not add to submit list.
// We will then add it to ars in an already-failed state.
@@ -600,7 +597,7 @@ public void run() {
try {
MultiServerCallable<Row> callable = createCallable(server, tableName, multiAction);
try {
- res = createCaller(callable).callWithoutRetries(callable);
+ res = createCaller(callable).callWithoutRetries(callable, operationTimeout);
} catch (IOException e) {
// The service itself failed . It may be an error coming from the communication
// layer, but, as well, a functional error raised by the server.
@@ -1010,7 +1007,7 @@ public boolean hasError() {
* failed operations themselves.
* @param failedRows an optional list into which the rows that failed since the last time
* {@link #waitForAllPreviousOpsAndReset(List)} was called, or AP was created, are saved.
- * @returns all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
+ * @return all the errors since the last time {@link #waitForAllPreviousOpsAndReset(List)}
* was called, or AP was created.
*/
public RetriesExhaustedWithDetailsException waitForAllPreviousOpsAndReset(
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
index 807975eb6c9c..0290dcac922a 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientScanner.java
@@ -39,6 +39,7 @@
import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
import org.apache.hadoop.hbase.regionserver.RegionServerStoppedException;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.ExceptionUtil;
/**
* Implements the scanner interface for the HBase client.
@@ -63,7 +64,7 @@ public class ClientScanner extends AbstractClientScanner {
protected final long maxScannerResultSize;
private final HConnection connection;
private final TableName tableName;
- private final int scannerTimeout;
+ protected final int scannerTimeout;
protected boolean scanMetricsPublished = false;
protected RpcRetryingCaller<Result []> caller;
@@ -224,7 +225,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
// Close the previous scanner if it's open
if (this.callable != null) {
this.callable.setClose();
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.callable = null;
}
@@ -261,7 +262,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
callable = getScannerCallable(localStartKey, nbRows);
// Open a scanner on the region server starting at the
// beginning of the region
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.currentRegion = callable.getHRegionInfo();
if (this.scanMetrics != null) {
this.scanMetrics.countOfRegions.incrementAndGet();
@@ -326,17 +327,17 @@ public Result next() throws IOException {
// Skip only the first row (which was the last row of the last
// already-processed batch).
callable.setCaching(1);
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
callable.setCaching(this.caching);
skipFirst = false;
}
// Server returns a null values if scanning is to stop. Else,
// returns an empty array if scanning is to go on and we've just
// exhausted current region.
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
if (skipFirst && values != null && values.length == 1) {
skipFirst = false; // Already skipped, unset it before scanning again
- values = this.caller.callWithRetries(callable);
+ values = this.caller.callWithRetries(callable, scannerTimeout);
}
retryAfterOutOfOrderException = true;
} catch (DoNotRetryIOException e) {
@@ -428,7 +429,7 @@ public void close() {
if (callable != null) {
callable.setClose();
try {
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
} catch (UnknownScannerException e) {
// We used to catch this error, interpret, and rethrow. However, we
// have since decided that it's not nice for a scanner's close to
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
index 77fd2aa3186a..a980ec968f41 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ClientSmallScanner.java
@@ -200,7 +200,7 @@ && nextScanner(countdown, values == null, currentRegionDone)) {
// Server returns a null values if scanning is to stop. Else,
// returns an empty array if scanning is to go on and we've just
// exhausted current region.
- values = this.caller.callWithRetries(smallScanCallable);
+ values = this.caller.callWithRetries(smallScanCallable, scannerTimeout);
this.currentRegion = smallScanCallable.getHRegionInfo();
long currentTime = System.currentTimeMillis();
if (this.scanMetrics != null) {
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
index 2dc212a76686..27e973ba7af9 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/HBaseAdmin.java
@@ -175,6 +175,7 @@ public class HBaseAdmin implements Abortable, Closeable {
private boolean aborted;
private boolean cleanupConnectionOnClose = false; // close the connection in close()
private boolean closed = false;
+ private int operationTimeout;
private RpcRetryingCallerFactory rpcCallerFactory;
@@ -192,6 +193,11 @@ public HBaseAdmin(Configuration c)
this.cleanupConnectionOnClose = true;
}
+ public int getOperationTimeout() {
+ return operationTimeout;
+ }
+
+
/**
* Constructor for externally managed HConnections.
* The connection to master will be created when required by admin functions.
@@ -217,6 +223,9 @@ public HBaseAdmin(HConnection connection)
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
this.retryLongerMultiplier = this.conf.getInt(
"hbase.client.retries.longer.multiplier", 10);
+ this.operationTimeout = this.conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
+
this.rpcCallerFactory = RpcRetryingCallerFactory.instantiate(this.conf);
}
@@ -3315,7 +3324,7 @@ public long sleep(long pause, int tries) {
private <V> V executeCallable(MasterCallable<V> callable) throws IOException {
RpcRetryingCaller<V> caller = rpcCallerFactory.newCaller();
try {
- return caller.callWithRetries(callable);
+ return caller.callWithRetries(callable, operationTimeout);
} finally {
callable.close();
}
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
index 1a6ee4c59e2e..62fb9ccc73b4 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java
@@ -36,6 +36,7 @@
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hbase.util.ExceptionUtil;
/**
* Scanner class that contains the <code>hbase:meta</code> table scanning logic.
@@ -189,6 +190,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
scanner.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the result scanner", t);
}
}
@@ -196,6 +198,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
visitor.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the meta scanner visitor", t);
}
}
@@ -203,6 +206,7 @@ static void metaScan(Configuration configuration, ClusterConnection connection,
try {
metaTable.close();
} catch (Throwable t) {
+ ExceptionUtil.rethrowIfInterrupt(t);
LOG.debug("Got exception in closing the meta table", t);
}
}
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
index 618b3b38003b..470ffa132fc6 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/ReversedClientScanner.java
@@ -60,7 +60,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
// Close the previous scanner if it's open
if (this.callable != null) {
this.callable.setClose();
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.callable = null;
}
@@ -108,7 +108,7 @@ protected boolean nextScanner(int nbRows, final boolean done)
callable = getScannerCallable(localStartKey, nbRows, locateStartRow);
// Open a scanner on the region server starting at the
// beginning of the region
- this.caller.callWithRetries(callable);
+ this.caller.callWithRetries(callable, scannerTimeout);
this.currentRegion = callable.getHRegionInfo();
if (this.scanMetrics != null) {
this.scanMetrics.countOfRegions.incrementAndGet();
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
index 68faba560ec9..2a9732522079 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/RpcRetryingCaller.java
@@ -42,20 +42,14 @@
* Runs an rpc'ing {@link RetryingCallable}. Sets into rpc client
* threadlocal outstanding timeouts as so we don't persist too much.
* Dynamic rather than static so can set the generic appropriately.
+ *
+ * This object has a state. It should not be used by in parallel by different threads.
+ * Reusing it is possible however, even between multiple threads. However, the user will
+ * have to manage the synchronization on its side: there is no synchronization inside the class.
*/
@InterfaceAudience.Private
[email protected]
- (value = "IS2_INCONSISTENT_SYNC", justification = "na")
public class RpcRetryingCaller<T> {
static final Log LOG = LogFactory.getLog(RpcRetryingCaller.class);
- /**
- * Timeout for the call including retries
- */
- private int callTimeout;
- /**
- * The remaining time, for the call to come. Takes into account the tries already done.
- */
- private int remainingTime;
/**
* When we started making calls.
*/
@@ -70,18 +64,17 @@ public class RpcRetryingCaller<T> {
public RpcRetryingCaller(Configuration conf) {
this.pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
- HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
+ HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
this.retries =
conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
- this.callTimeout = conf.getInt(
- HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
- HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
}
- private void beforeCall() {
- if (callTimeout > 0) {
- remainingTime = (int) (callTimeout -
+ private int getRemainingTime(int callTimeout) {
+ if (callTimeout <= 0) {
+ return 0;
+ } else {
+ int remainingTime = (int) (callTimeout -
(EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime));
if (remainingTime < MIN_RPC_TIMEOUT) {
// If there is no time left, we're trying anyway. It's too late.
@@ -89,17 +82,10 @@ private void beforeCall() {
// resetting to the minimum.
remainingTime = MIN_RPC_TIMEOUT;
}
- } else {
- remainingTime = 0;
+ return remainingTime;
}
}
-
- public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOException,
- RuntimeException {
- return callWithRetries(callable, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
- }
-
/**
* Retries if invocation fails.
* @param callTimeout Timeout for this call
@@ -108,11 +94,8 @@ public synchronized T callWithRetries(RetryingCallable<T> callable) throws IOExc
* @throws IOException if a remote or network exception occurs
* @throws RuntimeException other unspecified error
*/
- @edu.umd.cs.findbugs.annotations.SuppressWarnings
- (value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "na")
- public synchronized T callWithRetries(RetryingCallable<T> callable, int callTimeout)
+ public T callWithRetries(RetryingCallable<T> callable, int callTimeout)
throws IOException, RuntimeException {
- this.callTimeout = callTimeout;
List<RetriesExhaustedException.ThrowableWithExtraContext> exceptions =
new ArrayList<RetriesExhaustedException.ThrowableWithExtraContext>();
this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
@@ -120,8 +103,7 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
long expectedSleep;
try {
callable.prepare(tries != 0); // if called with false, check table status on ZK
- beforeCall();
- return callable.call(remainingTime);
+ return callable.call(getRemainingTime(callTimeout));
} catch (Throwable t) {
ExceptionUtil.rethrowIfInterrupt(t);
if (LOG.isTraceEnabled()) {
@@ -145,8 +127,8 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
// If, after the planned sleep, there won't be enough time left, we stop now.
long duration = singleCallDuration(expectedSleep);
- if (duration > this.callTimeout) {
- String msg = "callTimeout=" + this.callTimeout + ", callDuration=" + duration +
+ if (duration > callTimeout) {
+ String msg = "callTimeout=" + callTimeout + ", callDuration=" + duration +
": " + callable.getExceptionMessageAdditionalDetail();
throw (SocketTimeoutException)(new SocketTimeoutException(msg).initCause(t));
}
@@ -163,8 +145,7 @@ public synchronized T callWithRetries(RetryingCallable<T> callable, int callTime
* @return Calculate how long a single call took
*/
private long singleCallDuration(final long expectedSleep) {
- return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime)
- + MIN_RPC_TIMEOUT + expectedSleep;
+ return (EnvironmentEdgeManager.currentTimeMillis() - this.globalStartTime) + expectedSleep;
}
/**
@@ -176,7 +157,7 @@ private long singleCallDuration(final long expectedSleep) {
* @throws IOException if a remote or network exception occurs
* @throws RuntimeException other unspecified error
*/
- public T callWithoutRetries(RetryingCallable<T> callable)
+ public T callWithoutRetries(RetryingCallable<T> callable, int callTimeout)
throws IOException, RuntimeException {
// The code of this method should be shared with withRetries.
this.globalStartTime = EnvironmentEdgeManager.currentTimeMillis();
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
index f28feac23eb2..e627662c34b2 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/RegionCoprocessorRpcChannel.java
@@ -24,6 +24,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.RegionServerCallable;
@@ -52,6 +53,7 @@ public class RegionCoprocessorRpcChannel extends CoprocessorRpcChannel{
private final TableName table;
private final byte[] row;
private byte[] lastRegion;
+ private int operationTimeout;
private RpcRetryingCallerFactory rpcFactory;
@@ -60,6 +62,9 @@ public RegionCoprocessorRpcChannel(HConnection conn, TableName table, byte[] row
this.table = table;
this.row = row;
this.rpcFactory = RpcRetryingCallerFactory.instantiate(conn.getConfiguration());
+ this.operationTimeout = conn.getConfiguration().getInt(
+ HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
+ HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
}
@Override
@@ -88,7 +93,7 @@ public CoprocessorServiceResponse call(int callTimeout) throws Exception {
}
};
CoprocessorServiceResponse result = rpcFactory.<CoprocessorServiceResponse> newCaller()
- .callWithRetries(callable);
+ .callWithRetries(callable, operationTimeout);
Message response = null;
if (result.getValue().hasValue()) {
response = responsePrototype.newBuilderForType()
diff --git a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
index 66c51721f9a4..1ff1f01dd173 100644
--- a/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
+++ b/hbase-client/src/test/java/org/apache/hadoop/hbase/client/TestAsyncProcess.java
@@ -149,7 +149,8 @@ protected RpcRetryingCaller<MultiResponse> createCaller(MultiServerCallable<Row>
callable.getMulti(), nbMultiResponse, nbActions);
return new RpcRetryingCaller<MultiResponse>(conf) {
@Override
- public MultiResponse callWithoutRetries( RetryingCallable<MultiResponse> callable)
+ public MultiResponse callWithoutRetries(RetryingCallable<MultiResponse> callable,
+ int callTimeout)
throws IOException, RuntimeException {
try {
// sleep one second in order for threadpool to start another thread instead of reusing
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
index 43e167f0aaf1..d49146a6ed45 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.java
@@ -630,7 +630,7 @@ public Boolean call(int callTimeout) throws Exception {
List<LoadQueueItem> toRetry = new ArrayList<LoadQueueItem>();
Configuration conf = getConf();
boolean success = RpcRetryingCallerFactory.instantiate(conf).<Boolean> newCaller()
- .callWithRetries(svrCallable);
+ .callWithRetries(svrCallable, Integer.MAX_VALUE);
if (!success) {
LOG.warn("Attempt to bulk load region containing "
+ Bytes.toStringBinary(first) + " into table "
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
index ea56574f52de..38194f970edd 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/client/TestAdmin.java
@@ -1552,7 +1552,6 @@ private void setUpforLogRolling() {
TEST_UTIL.getConfiguration().setInt(
"hbase.regionserver.logroll.errors.tolerated", 2);
- TEST_UTIL.getConfiguration().setInt("ipc.socket.timeout", 10 * 1000);
TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
// For less frequently updated regions flush after every 2 flushes
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
index 89ce874495fa..c1d93a2e788f 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestHRegionServerBulkLoad.java
@@ -170,7 +170,7 @@ public Void call(int callTimeout) throws Exception {
};
RpcRetryingCallerFactory factory = new RpcRetryingCallerFactory(conf);
RpcRetryingCaller<Void> caller = factory.<Void> newCaller();
- caller.callWithRetries(callable);
+ caller.callWithRetries(callable, Integer.MAX_VALUE);
// Periodically do compaction to reduce the number of open file handles.
if (numBulkLoads.get() % 10 == 0) {
@@ -190,7 +190,7 @@ public Void call(int callTimeout) throws Exception {
return null;
}
};
- caller.callWithRetries(callable);
+ caller.callWithRetries(callable, Integer.MAX_VALUE);
}
}
}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
index 590481f15372..4a1b0f5f625e 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestLogRollAbort.java
@@ -60,7 +60,6 @@ public static void setUpBeforeClass() throws Exception {
// Tweak default timeout values down for faster recovery
TEST_UTIL.getConfiguration().setInt(
"hbase.regionserver.logroll.errors.tolerated", 2);
- TEST_UTIL.getConfiguration().setInt("ipc.socket.timeout", 10 * 1000);
TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
// Increase the amount of time between client retries
|
ed41fede1fc5861998cd375ffee6980be106cb0c
|
orientdb
|
Released 0.9.8 with the fix on partitioning in- Key/Value Server--
|
c
|
https://github.com/orientechnologies/orientdb
|
diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/base/OrientMonoThreadTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/base/OrientMonoThreadTest.java
index b4e33bd210e..305f7124f2d 100644
--- a/tests/src/test/java/com/orientechnologies/orient/test/database/base/OrientMonoThreadTest.java
+++ b/tests/src/test/java/com/orientechnologies/orient/test/database/base/OrientMonoThreadTest.java
@@ -19,7 +19,6 @@
import com.orientechnologies.common.profiler.OProfiler;
import com.orientechnologies.common.test.SpeedTestMonoThread;
-import com.orientechnologies.orient.client.distributed.OEngineDistributed;
import com.orientechnologies.orient.client.remote.OEngineRemote;
import com.orientechnologies.orient.core.Orient;
@@ -28,7 +27,6 @@ public abstract class OrientMonoThreadTest extends SpeedTestMonoThread {
public OrientMonoThreadTest(int iCycles) {
super(iCycles);
Orient.instance().registerEngine(new OEngineRemote());
- Orient.instance().registerEngine(new OEngineDistributed());
}
public void deinit() {
|
ff80712d74ae5da0a66db6098b22a028439146c2
|
Mylyn Reviews
|
Enhanced formatting of dsl
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java
index 81a99589..35f59b67 100644
--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java
+++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java
@@ -3,7 +3,7 @@
*/
package org.eclipse.mylyn.reviews.tasks.dsl.formatting;
-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslPackage;
+import org.eclipse.mylyn.reviews.tasks.dsl.services.ReviewDslGrammarAccess;
import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter;
import org.eclipse.xtext.formatting.impl.FormattingConfig;
@@ -11,22 +11,23 @@
* This class contains custom formatting description.
*
* see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting
- * on how and when to use it
+ * on how and when to use it
*
- * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an example
+ * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an
+ * example
*/
public class ReviewDslFormatter extends AbstractDeclarativeFormatter {
-
+
@Override
protected void configureFormatting(FormattingConfig c) {
- c.setLinewrap(1).after(ReviewDslPackage.eINSTANCE.getReviewScope());
- c.setIndentationIncrement().before(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
- c.setIndentationDecrement().after(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
- c.setLinewrap(1).after(ReviewDslPackage.eINSTANCE.getReviewScopeItem());
-
- // c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getFileComment());
-// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getLineComment());
-// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getResourceDef());
-// c.setLinewrap(1, 1, 2).before(ReviewDslPackage.eINSTANCE.getPatchDef());
+ ReviewDslGrammarAccess grammar = (ReviewDslGrammarAccess) getGrammarAccess();
+ c.setLinewrap().after(grammar.getModelRule());
+ c.setIndentationIncrement().before(grammar.getReviewScopeItemRule());
+ c.setIndentationDecrement().after(grammar.getReviewScopeItemRule());
+ c.setLinewrap().after(grammar.getReviewScopeItemRule());
+ c.setLinewrap().before(
+ grammar.getReviewResultAccess().getCommentKeyword_2_0());
+ c.setLinewrap().after(
+ grammar.getReviewResultAccess().getCommentAssignment_2_1());
}
}
|
1bd79c9c07207723373bde7aa1031285057248ef
|
Delta Spike
|
add tomee build leftovers to .gitignore
|
p
|
https://github.com/apache/deltaspike
|
diff --git a/.gitignore b/.gitignore
index 270513ffb..0960882c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,6 @@ target
atlassian-ide-plugin.xml
.sonar-ide.properties
*.patch
+deltaspike/core/impl/data
+deltaspike/modules/jsf/impl/data
+deltaspike/modules/security/impl/data
|
16bde472f467e8d9d138cb4eea157620a4cfa541
|
brandonborkholder$glg2d
|
Pulled out some common functionality from the GL2 text helper implementation.
|
p
|
https://github.com/brandonborkholder/glg2d
|
diff --git a/src/main/java/glg2d/impl/AbstractTextDrawer.java b/src/main/java/glg2d/impl/AbstractTextDrawer.java
new file mode 100644
index 00000000..d68dc878
--- /dev/null
+++ b/src/main/java/glg2d/impl/AbstractTextDrawer.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2012 Brandon Borkholder
+ *
+ * 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 glg2d.impl;
+
+import glg2d.GLG2DTextHelper;
+import glg2d.GLGraphics2D;
+
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.RenderingHints;
+import java.awt.RenderingHints.Key;
+import java.awt.font.FontRenderContext;
+import java.awt.font.TextLayout;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Deque;
+
+public abstract class AbstractTextDrawer implements GLG2DTextHelper {
+ protected GLGraphics2D g2d;
+
+ protected Deque<FontState> stack = new ArrayDeque<FontState>();
+
+ @Override
+ public void setG2D(GLGraphics2D g2d) {
+ this.g2d = g2d;
+
+ stack.clear();
+ stack.push(new FontState());
+ }
+
+ @Override
+ public void push(GLGraphics2D newG2d) {
+ stack.push(stack.peek().clone());
+ }
+
+ @Override
+ public void pop(GLGraphics2D parentG2d) {
+ stack.pop();
+ }
+
+ @Override
+ public void setHint(Key key, Object value) {
+ if (key == RenderingHints.KEY_TEXT_ANTIALIASING) {
+ stack.peek().antiAlias = value == RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
+ }
+ }
+
+ @Override
+ public void resetHints() {
+ setHint(RenderingHints.KEY_TEXT_ANTIALIASING, null);
+ }
+
+ @Override
+ public void setFont(Font font) {
+ stack.peek().font = font;
+ }
+
+ @Override
+ public Font getFont() {
+ return stack.peek().font;
+ }
+
+ @Override
+ public FontMetrics getFontMetrics(Font font) {
+ return new GLFontMetrics(font, getFontRenderContext());
+ }
+
+ @Override
+ public FontRenderContext getFontRenderContext() {
+ return new FontRenderContext(g2d.getTransform(), stack.peek().antiAlias, false);
+ }
+
+ /**
+ * The default implementation is good enough for now.
+ */
+ public static class GLFontMetrics extends FontMetrics {
+ private static final long serialVersionUID = 3676850359220061793L;
+
+ protected FontRenderContext fontRenderContext;
+
+ protected int[] cachedWidths = new int[255];
+
+ public GLFontMetrics(Font font, FontRenderContext frc) {
+ super(font);
+ fontRenderContext = frc;
+ Arrays.fill(cachedWidths, -1);
+ }
+
+ @Override
+ public FontRenderContext getFontRenderContext() {
+ return fontRenderContext;
+ }
+
+ @Override
+ public int charsWidth(char[] data, int off, int len) {
+ if (len <= 0) {
+ return 0;
+ }
+
+ if (font.hasLayoutAttributes()) {
+ String str = new String(data, off, len);
+ return (int) new TextLayout(str, font, getFontRenderContext()).getAdvance();
+ } else {
+ int width = 0;
+ for (int i = 0; i < len; i++) {
+ width += charWidth(data[off + i]);
+ }
+
+ return width;
+ }
+ }
+
+ @Override
+ public int charWidth(char ch) {
+ int width;
+ if (ch < 255) {
+ width = cachedWidths[ch];
+ if (width < 0) {
+ width = (int) getFont().getStringBounds(new char[] { ch }, 0, 1, getFontRenderContext()).getWidth();
+ cachedWidths[ch] = width;
+ }
+ } else {
+ width = (int) getFont().getStringBounds(new char[] { ch }, 0, 1, getFontRenderContext()).getWidth();
+ }
+
+ return width;
+ }
+ }
+
+ protected static class FontState implements Cloneable {
+ public Font font;
+ public boolean antiAlias;
+
+ @Override
+ public FontState clone() {
+ try {
+ return (FontState) super.clone();
+ } catch (CloneNotSupportedException e) {
+ // can't think of a reason this would happen
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
diff --git a/src/main/java/glg2d/impl/gl2/GL2StringDrawer.java b/src/main/java/glg2d/impl/gl2/GL2StringDrawer.java
index 18c90aa7..af5d3e59 100644
--- a/src/main/java/glg2d/impl/gl2/GL2StringDrawer.java
+++ b/src/main/java/glg2d/impl/gl2/GL2StringDrawer.java
@@ -15,20 +15,12 @@
*/
package glg2d.impl.gl2;
-import glg2d.GLG2DTextHelper;
-import glg2d.GLGraphics2D;
+import glg2d.impl.AbstractTextDrawer;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
-import java.awt.FontMetrics;
-import java.awt.RenderingHints;
-import java.awt.RenderingHints.Key;
-import java.awt.font.FontRenderContext;
-import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
-import java.util.ArrayDeque;
-import java.util.Deque;
import java.util.HashMap;
import javax.media.opengl.GL2;
@@ -39,84 +31,14 @@
/**
* Draws text for the {@code GLGraphics2D} class.
*/
-public class GL2StringDrawer implements GLG2DTextHelper {
+public class GL2StringDrawer extends AbstractTextDrawer {
protected FontRenderCache cache = new FontRenderCache();
- protected Deque<Font> fontStack = new ArrayDeque<Font>(10);
-
- protected Font font;
-
- protected GLGraphics2D g2d;
-
- protected boolean antiAlias;
-
- @Override
- public void setG2D(GLGraphics2D g2d) {
- this.g2d = g2d;
- }
-
- @Override
- public void push(GLGraphics2D newG2d) {
- fontStack.push(font);
- }
-
- @Override
- public void pop(GLGraphics2D parentG2d) {
- setAntiAlias(parentG2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING));
- if (!fontStack.isEmpty()) {
- font = fontStack.pop();
- }
- }
-
- @Override
- public void setHint(Key key, Object value) {
- if (key == RenderingHints.KEY_TEXT_ANTIALIASING) {
- setAntiAlias(value);
- }
- }
-
- @Override
- public void resetHints() {
- setHint(RenderingHints.KEY_TEXT_ANTIALIASING, null);
- }
-
@Override
public void dispose() {
cache.dispose();
}
- @Override
- public void setFont(Font font) {
- this.font = font;
- }
-
- @Override
- public Font getFont() {
- return font;
- }
-
- @Override
- public FontMetrics getFontMetrics(Font font) {
- return new GLFontMetrics(font, getFontRenderContext(), getRenderer(font));
- }
-
- @Override
- public FontRenderContext getFontRenderContext() {
- return new FontRenderContext(g2d.getTransform(), true, false);
- }
-
- public void setAntiAlias(Object value) {
- boolean doAlias = true;
- if (value == null || value == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF || value == RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT) {
- doAlias = false;
- }
- if (antiAlias == doAlias) {
- return;
- }
-
- antiAlias = doAlias;
- }
-
@Override
public void drawString(AttributedCharacterIterator iterator, int x, int y) {
// TODO
@@ -133,7 +55,7 @@ public void drawString(String string, Color color, float x, float y) {
}
protected TextRenderer getRenderer(Font font) {
- return cache.getRenderer(font, antiAlias);
+ return cache.getRenderer(font, stack.peek().antiAlias);
}
/**
@@ -180,65 +102,6 @@ protected void end(TextRenderer renderer) {
gl.glPopMatrix();
}
- /**
- * The default implementation is good enough for now.
- */
- public static class GLFontMetrics extends FontMetrics {
- private static final long serialVersionUID = 3676850359220061793L;
-
- protected TextRenderer renderer;
-
- protected FontRenderContext fontRenderContext;
-
- protected int[] cachedWidths = new int[255];
-
- public GLFontMetrics(Font font, FontRenderContext frc, TextRenderer renderer) {
- super(font);
- this.renderer = renderer;
- fontRenderContext = frc;
- }
-
- @Override
- public FontRenderContext getFontRenderContext() {
- return fontRenderContext;
- }
-
- @Override
- public int charsWidth(char[] data, int off, int len) {
- if (len <= 0) {
- return 0;
- }
-
- if (font.hasLayoutAttributes()) {
- String str = new String(data, off, len);
- return (int) new TextLayout(str, font, getFontRenderContext()).getAdvance();
- } else {
- int width = 0;
- for (int i = 0; i < len; i++) {
- width += charWidth(data[off + i]);
- }
-
- return width;
- }
- }
-
- @Override
- public int charWidth(char ch) {
- int width;
- if (ch < 255) {
- width = cachedWidths[ch];
- if (width == 0) {
- width = (int) renderer.getCharWidth(ch);
- cachedWidths[ch] = width;
- }
- } else {
- width = (int) renderer.getCharWidth(ch);
- }
-
- return width;
- }
- }
-
@SuppressWarnings("serial")
public static class FontRenderCache extends HashMap<Font, TextRenderer[]> {
public TextRenderer getRenderer(Font font, boolean antiAlias) {
|
245f782801254eefc4442c0850acf3eeee468697
|
restlet-framework-java
|
- Bumped versions to 1.0 RC3 - Updated docs -- Removed deprecated methods--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/build/tmpl/changes.txt b/build/tmpl/changes.txt
index 5b0e2cb01b..91e6e98dc0 100644
--- a/build/tmpl/changes.txt
+++ b/build/tmpl/changes.txt
@@ -4,6 +4,11 @@ Changes log
===========
@version-full@ (@release-date@)
+[Bugs fixed]
+[API changes]
+[Enhancements]
+
+1.0 RC2 (2007-01-09)
[Bugs fixed]
- Fixed minor bug with the URI parsing (query sign "?" inside fragment).
Contributed by Thierry Boileau.
diff --git a/build/www/roadmap.html b/build/www/roadmap.html
index 2dffd1f13e..c9fe8f466c 100644
--- a/build/www/roadmap.html
+++ b/build/www/roadmap.html
@@ -10,7 +10,7 @@
<body>
<a target="_top" href="http://www.restlet.org"><img
- src="http://www.restlet.org/images/logo200" /></a>
+ src="http://www.restlet.org/images/logo200" /></a>
<br />
<br />
@@ -28,62 +28,62 @@ <h3><a name="timeline">Timeline</a></h3>
<p>
<ul>
- <li>2007 Q1
- <ul>
- <li><u>[Optional]</u> 1.0 RC2 release</li>
- <li><b>1.0 release.</b> <a
- href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.0+release">List
- of issues</a> must be resolved (documentation, etc.).</li>
- </ul>
- </li>
- <li>2007 Q2
- <ul>
- <li>1.1 beta 1.<a
- href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.1+beta">Open
- issues</a> to resolve.</li>
- </ul>
- <li>2007 Q3
- <ul>
- <li><b>1.1 release.</b> <a
- href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.1+release">Remaining
- issues</a> must be resolved.</li>
- </ul>
- </li>
- <li>2008 Q1
- <ul>
- <li><u>[JSR]</u> Submission of a proposal to standardize a
- Restlet API 2.0 to the <a href="http://www.jcp.org">JCP</a>
- <li><u>[JSR]</u> If submission approved, formation of expert
- group</li>
- <li><u>[JSR]</u> Write first draft</li>
- </ul>
- </li>
- <li>2008 Q2
- <ul>
- <li><u>[JSR]</u> Updates to the draft (optional)</li>
- <li><u>[JSR]</u> Public Review</li>
- </ul>
- </li>
- <li>2008 Q3
- <ul>
- <li><u>[JSR]</u> Drafts updates (optional)</li>
- <li><u>[JSR]</u> Draft Specification approval ballot by EC</li>
- </ul>
- </li>
- <li>2008 Q4
- <ul>
- <li><u>[JSR]</u> Proposed final draft</li>
- <li><u>[JSR]</u> Completion of RI and TCK</li>
- </ul>
- </li>
- <li>2009 Q1
- <ul>
- <li><u>[JSR]</u> Final draft Submission</li>
- <li><u>[JSR]</u> Final approval ballot by EC</li>
- <li><u>[JSR]</u> Final release of Restlet API 2.0</li>
- <li><b>2.0 release</b></li>
- </ul>
- </li>
+ <li>2007 Q1
+ <ul>
+ <li><u>[Optional]</u> 1.0 RC3 release</li>
+ <li><b>1.0 release.</b> <a
+ href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.0+release">List
+ of issues</a> must be resolved (documentation, etc.).</li>
+ </ul>
+ </li>
+ <li>2007 Q2
+ <ul>
+ <li>1.1 beta 1.<a
+ href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.1+beta">Open
+ issues</a> to resolve.</li>
+ </ul>
+ <li>2007 Q3
+ <ul>
+ <li><b>1.1 release.</b> <a
+ href="http://restlet.tigris.org/issues/buglist.cgi?Submit+query=Submit+query&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&target_milestone=1.1+release">Remaining
+ issues</a> must be resolved.</li>
+ </ul>
+ </li>
+ <li>2008 Q1
+ <ul>
+ <li><u>[JSR]</u> Submission of a proposal to standardize a
+ Restlet API 2.0 to the <a href="http://www.jcp.org">JCP</a>
+ <li><u>[JSR]</u> If submission approved, formation of expert
+ group</li>
+ <li><u>[JSR]</u> Write first draft</li>
+ </ul>
+ </li>
+ <li>2008 Q2
+ <ul>
+ <li><u>[JSR]</u> Updates to the draft (optional)</li>
+ <li><u>[JSR]</u> Public Review</li>
+ </ul>
+ </li>
+ <li>2008 Q3
+ <ul>
+ <li><u>[JSR]</u> Drafts updates (optional)</li>
+ <li><u>[JSR]</u> Draft Specification approval ballot by EC</li>
+ </ul>
+ </li>
+ <li>2008 Q4
+ <ul>
+ <li><u>[JSR]</u> Proposed final draft</li>
+ <li><u>[JSR]</u> Completion of RI and TCK</li>
+ </ul>
+ </li>
+ <li>2009 Q1
+ <ul>
+ <li><u>[JSR]</u> Final draft Submission</li>
+ <li><u>[JSR]</u> Final approval ballot by EC</li>
+ <li><u>[JSR]</u> Final release of Restlet API 2.0</li>
+ <li><b>2.0 release</b></li>
+ </ul>
+ </li>
</ul>
</p>
@@ -92,15 +92,15 @@ <h3><a name="conclusion">Conclusion</a></h3>
<p>Due to the open source nature of the Restlet project, the above
timeline is subject to change. However, we will do our best to respect
it and update it as frequently as possible. Please, feel free to <a
- href="mailto:[email protected]">contact us</a> for questions and
+ href="mailto:[email protected]">contact us</a> for questions and
comments.</p>
<br />
-<small> Last modified on 2006-12-26. Copyright © 2005-2007
+<small> Last modified on 2007-01-09. Copyright © 2005-2007
<a href="mailto:[email protected]">Jérôme Louvel</a>.
Restlet is a registered trademark of <a target="_top"
- href="http://www.noelios.com">Noelios Consulting</a>. </small>
+ href="http://www.noelios.com">Noelios Consulting</a>. </small>
</body>
</html>
diff --git a/build/www/tutorial.html b/build/www/tutorial.html
index 2a7b31c6cc..2e64110fbd 100644
--- a/build/www/tutorial.html
+++ b/build/www/tutorial.html
@@ -538,7 +538,7 @@ <h4>Notes</h4>
<br />
-<small> Last modified on 2006-12-26. Copyright © 2005-2007
+<small> Last modified on 2007-01-09. Copyright © 2005-2007
<a href="mailto:[email protected]">Jérôme Louvel</a>.
Restlet is a registered trademark of <a target="_top"
href="http://www.noelios.com">Noelios Consulting</a>. </small>
diff --git a/build/www/tutorial.pdf b/build/www/tutorial.pdf
index 7b6e58a3e1..f788e61873 100644
Binary files a/build/www/tutorial.pdf and b/build/www/tutorial.pdf differ
diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java b/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java
index 77b74d0e5d..0a33f8169b 100644
--- a/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java
+++ b/module/com.noelios.restlet/src/com/noelios/restlet/Factory.java
@@ -651,23 +651,6 @@ public void parse(Logger logger, Form form, Representation webForm) {
}
}
- /**
- * Parses an URL encoded query string into a given form.
- *
- * @param logger
- * The logger to use.
- * @param form
- * The target form.
- * @param queryString
- * Query string.
- * @deprecated Use the parse(Logger,String,CharacterSet) method to specify
- * the encoding. This method uses the UTF-8 character set.
- */
- @Deprecated
- public void parse(Logger logger, Form form, String queryString) {
- parse(logger, form, queryString, CharacterSet.UTF_8);
- }
-
/**
* Parses an URL encoded query string into a given form.
*
diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java
index c69385d022..caf2f93070 100644
--- a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java
+++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormReader.java
@@ -69,24 +69,6 @@ public FormReader(Logger logger, Representation representation)
}
}
- /**
- * Constructor.
- *
- * @param logger
- * The logger.
- * @param query
- * The query string.
- * @deprecated Use the FormReader(Logger,String,CharacterSet) constructor to
- * specify the encoding.
- */
- @Deprecated
- public FormReader(Logger logger, String query) throws IOException {
- this.logger = logger;
- this.stream = new ByteArrayInputStream(query.getBytes());
- this.characterSet = CharacterSet.UTF_8;
-
- }
-
/**
* Constructor.
*
diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java
index 78d4d3df88..4cf06b5261 100644
--- a/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java
+++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/FormUtils.java
@@ -35,24 +35,6 @@
* @author Jerome Louvel ([email protected])
*/
public class FormUtils {
- /**
- * Parses a query into a given form.
- *
- * @param logger
- * The logger.
- * @param form
- * The target form.
- * @param query
- * Query string.
- * @deprecated Use the parseQuery(Logger,Form, String,CharacterSet) method
- * to specify the encoding. This method uses the UTF-8 character
- * set.
- */
- @Deprecated
- public static void parseQuery(Logger logger, Form form, String query) {
- parseQuery(logger, form, query, CharacterSet.UTF_8);
- }
-
/**
* Parses a query into a given form.
*
@@ -112,27 +94,6 @@ public static void parsePost(Logger logger, Form form, Representation post) {
}
}
- /**
- * Reads the parameters whose name is a key in the given map.<br/> If a
- * matching parameter is found, its value is put in the map.<br/> If
- * multiple values are found, a list is created and set in the map.
- *
- * @param logger
- * The logger.
- * @param query
- * The query string.
- * @param parameters
- * The parameters map controlling the reading.
- * @deprecated Use the getParameters(Logger,String,Map<String,
- * Object>,CharacterSet) method to specify the encoding. This
- * method uses the UTF-8 character set.
- */
- @Deprecated
- public static void getParameters(Logger logger, String query,
- Map<String, Object> parameters) throws IOException {
- getParameters(logger, query, parameters, CharacterSet.UTF_8);
- }
-
/**
* Reads the parameters whose name is a key in the given map.<br/> If a
* matching parameter is found, its value is put in the map.<br/> If
@@ -170,27 +131,6 @@ public static void getParameters(Logger logger, Representation post,
new FormReader(logger, post).readParameters(parameters);
}
- /**
- * Reads the first parameter with the given name.
- *
- * @param logger
- * The logger.
- * @param query
- * The query string.
- * @param name
- * The parameter name to match.
- * @return The parameter.
- * @throws IOException
- * @deprecated Use the getFirstParameter(Logger,String,String,CharacterSet)
- * method to specify the encoding. This method uses the UTF-8
- * character set.
- */
- @Deprecated
- public static Parameter getFirstParameter(Logger logger, String query,
- String name) throws IOException {
- return getFirstParameter(logger, query, name, CharacterSet.UTF_8);
- }
-
/**
* Reads the first parameter with the given name.
*
@@ -228,27 +168,6 @@ public static Parameter getFirstParameter(Logger logger,
return new FormReader(logger, post).readFirstParameter(name);
}
- /**
- * Reads the parameters with the given name.<br/> If multiple values are
- * found, a list is returned created.
- *
- * @param logger
- * The logger.
- * @param query
- * The query string.
- * @param name
- * The parameter name to match.
- * @return The parameter value or list of values.
- * @deprecated Use the getParameter(Logger,String,String,CharacterSet)
- * method to specify the encoding. This method uses the UTF-8
- * character set.
- */
- @Deprecated
- public static Object getParameter(Logger logger, String query, String name)
- throws IOException {
- return getParameter(logger, query, name, CharacterSet.UTF_8);
- }
-
/**
* Reads the parameters with the given name.<br/> If multiple values are
* found, a list is returned created.
@@ -314,23 +233,4 @@ public static Parameter create(CharSequence name, CharSequence value,
return result;
}
-
- /**
- * Creates a parameter.
- *
- * @param name
- * The parameter name buffer.
- * @param value
- * The parameter value buffer (can be null).
- * @return The created parameter.
- * @throws IOException
- * @deprecated Use the create(CharSequence,CharSequence,CharacterSet) method
- * instead. This method uses the UTF-8 character set.
- */
- @Deprecated
- public static Parameter create(CharSequence name, CharSequence value)
- throws IOException {
- return create(name, value, CharacterSet.UTF_8);
- }
-
}
diff --git a/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java b/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java
index 60a75b3718..8cda5c5875 100644
--- a/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java
+++ b/module/com.noelios.restlet/src/com/noelios/restlet/util/HeaderUtils.java
@@ -111,25 +111,6 @@ public static Appendable appendQuote(CharSequence source,
return destination;
}
- /**
- * Appends a source string as an URI encoded string.
- *
- * @param source
- * The source string to format.
- * @param destination
- * The appendable destination.
- * @throws IOException
- * @deprecated Use the
- * appendUriEncoded(CharSequence,Appendable,CharacterSet) method
- * to specify the encoding. This method uses the UTF-8 character
- * set.
- */
- @Deprecated
- public static Appendable appendUriEncoded(CharSequence source,
- Appendable destination) throws IOException {
- return appendUriEncoded(source, destination, CharacterSet.UTF_8);
- }
-
/**
* Appends a source string as an URI encoded string.
*
diff --git a/module/org.restlet/src/org/restlet/data/Form.java b/module/org.restlet/src/org/restlet/data/Form.java
index e16175cb07..306efd5bc3 100644
--- a/module/org.restlet/src/org/restlet/data/Form.java
+++ b/module/org.restlet/src/org/restlet/data/Form.java
@@ -73,23 +73,6 @@ public Form(Logger logger, Representation representation) {
Factory.getInstance().parse(logger, this, representation);
}
- /**
- * Constructor.
- *
- * @param logger
- * The logger to use.
- * @param queryString
- * The Web form parameters as a string.
- * @throws IOException
- * @deprecated Use the Form(Logger,String,CharacterSet) constructor to
- * specify the encoding. This method uses the UTF-8 character
- * set.
- */
- @Deprecated
- public Form(Logger logger, String queryString) {
- Factory.getInstance().parse(logger, this, queryString);
- }
-
/**
* Constructor.
*
@@ -125,7 +108,8 @@ public Form(Representation webForm) {
* @throws IOException
*/
public Form(String queryString) {
- this(Logger.getLogger(Form.class.getCanonicalName()), queryString);
+ this(Logger.getLogger(Form.class.getCanonicalName()), queryString,
+ CharacterSet.UTF_8);
}
/**
@@ -204,19 +188,6 @@ public Representation getWebRepresentation(CharacterSet characterSet) {
MediaType.APPLICATION_WWW_FORM, null, characterSet);
}
- /**
- * URL encodes the form.
- *
- * @return The encoded form.
- * @throws IOException
- * @deprecated Use the urlEncode(CharacterSet) method to specify the
- * encoding. This method uses the UTF-8 character set.
- */
- @Deprecated
- public String urlEncode() throws IOException {
- return encode(CharacterSet.UTF_8);
- }
-
/**
* Encodes the form using the standard URI encoding mechanism and the UTF-8
* character set.
diff --git a/module/org.restlet/src/org/restlet/data/Parameter.java b/module/org.restlet/src/org/restlet/data/Parameter.java
index dd812ff6df..ebdbd48d98 100644
--- a/module/org.restlet/src/org/restlet/data/Parameter.java
+++ b/module/org.restlet/src/org/restlet/data/Parameter.java
@@ -145,33 +145,6 @@ public String toString() {
return getName() + ": " + getValue();
}
- /**
- * Encodes the parameter.
- *
- * @return The encoded string.
- * @throws IOException
- * @deprecated Use the urlEncode(CharacterSet) method to specify the
- * encoding. This method uses the UTF-8 character set.
- */
- @Deprecated
- public String urlEncode() throws IOException {
- return encode(CharacterSet.UTF_8);
- }
-
- /**
- * Encodes the parameter and append the result to the given buffer.
- *
- * @param buffer
- * The buffer to append.
- * @throws IOException
- * @deprecated Use the urlEncode(Appendable,CharacterSet) method to specify
- * the encoding. This method uses the UTF-8 character set.
- */
- @Deprecated
- public void urlEncode(Appendable buffer) throws IOException {
- encode(buffer, CharacterSet.UTF_8);
- }
-
/**
* Encodes the parameter using the standard URI encoding mechanism.
*
diff --git a/module/org.restlet/src/org/restlet/resource/DomRepresentation.java b/module/org.restlet/src/org/restlet/resource/DomRepresentation.java
index ba340584a8..d6fa094950 100644
--- a/module/org.restlet/src/org/restlet/resource/DomRepresentation.java
+++ b/module/org.restlet/src/org/restlet/resource/DomRepresentation.java
@@ -94,22 +94,6 @@ public DomRepresentation(MediaType mediaType, Document xmlDocument) {
this.dom = xmlDocument;
}
- /**
- * Constructor.
- *
- * @param mediaType
- * The representation's media type.
- * @param xmlRepresentation
- * A source XML representation to parse.
- * @deprecated Use the other constructor instead.
- */
- @Deprecated
- public DomRepresentation(MediaType mediaType,
- Representation xmlRepresentation) {
- super(mediaType);
- this.xmlRepresentation = xmlRepresentation;
- }
-
/**
* Constructor.
*
diff --git a/module/org.restlet/src/org/restlet/resource/Representation.java b/module/org.restlet/src/org/restlet/resource/Representation.java
index a3fb1de0b3..f96dfb24be 100644
--- a/module/org.restlet/src/org/restlet/resource/Representation.java
+++ b/module/org.restlet/src/org/restlet/resource/Representation.java
@@ -120,19 +120,6 @@ public String getText() throws IOException {
return result;
}
- /**
- * Converts the representation to a string value. Be careful when using this
- * method as the conversion of large content to a string fully stored in
- * memory can result in OutOfMemoryErrors being thrown.
- *
- * @return The representation as a string value.
- * @deprecated Use getText instead.
- */
- @Deprecated
- public String getValue() throws IOException {
- return getText();
- }
-
/**
* Indicates if some fresh content is available, without having to actually
* call one of the content manipulation method like getStream() that would
diff --git a/module/org.restlet/src/org/restlet/resource/Resource.java b/module/org.restlet/src/org/restlet/resource/Resource.java
index 0dd7b041dc..268c5d5b6a 100644
--- a/module/org.restlet/src/org/restlet/resource/Resource.java
+++ b/module/org.restlet/src/org/restlet/resource/Resource.java
@@ -23,7 +23,6 @@
import java.util.logging.Logger;
import org.restlet.data.Reference;
-import org.restlet.data.ReferenceList;
import org.restlet.data.Status;
/**
@@ -58,9 +57,6 @@ public class Resource {
/** The identifier. */
private Reference identifier;
- /** The modifiable list of identifiers. */
- private ReferenceList identifiers;
-
/** The modifiable list of variants. */
private List<Variant> variants;
@@ -80,7 +76,6 @@ public Resource() {
public Resource(Logger logger) {
this.logger = logger;
this.identifier = null;
- this.identifiers = null;
this.variants = null;
}
@@ -142,21 +137,6 @@ public Reference getIdentifier() {
return this.identifier;
}
- /**
- * Returns the list of all the identifiers for the resource. The list is
- * composed of the official identifier followed by all the alias
- * identifiers.
- *
- * @return The list of all the identifiers for the resource.
- * @deprecated No obvious usage. More the role of Handler to map URIs.
- */
- @Deprecated
- public ReferenceList getIdentifiers() {
- if (this.identifiers == null)
- this.identifiers = new ReferenceList();
- return this.identifiers;
- }
-
/**
* Returns the logger to use.
*
@@ -252,18 +232,6 @@ public void setIdentifier(String identifierUri) {
setIdentifier(new Reference(identifierUri));
}
- /**
- * Sets a new list of all the identifiers for the resource.
- *
- * @param identifiers
- * The new list of identifiers.
- * @deprecated No obvious usage. More the role of Handler to map URIs.
- */
- @Deprecated
- public void setIdentifiers(ReferenceList identifiers) {
- this.identifiers = identifiers;
- }
-
/**
* Sets the logger to use.
*
diff --git a/module/org.restlet/src/org/restlet/resource/StringRepresentation.java b/module/org.restlet/src/org/restlet/resource/StringRepresentation.java
index 1d55c4e36d..d92e48f2e9 100644
--- a/module/org.restlet/src/org/restlet/resource/StringRepresentation.java
+++ b/module/org.restlet/src/org/restlet/resource/StringRepresentation.java
@@ -146,18 +146,6 @@ public String getText() {
return (this.text == null) ? null : this.text.toString();
}
- /**
- * Sets the string value.
- *
- * @param text
- * The string value.
- * @deprecated Use setText instead.
- */
- @Deprecated
- public void setValue(String text) {
- setText(text);
- }
-
/**
* Sets the string value.
*
diff --git a/module/org.restlet/src/org/restlet/util/Factory.java b/module/org.restlet/src/org/restlet/util/Factory.java
index b416d27068..ce4b23ce9a 100644
--- a/module/org.restlet/src/org/restlet/util/Factory.java
+++ b/module/org.restlet/src/org/restlet/util/Factory.java
@@ -51,7 +51,7 @@ public abstract class Factory {
.getCanonicalName());
/** Common version info. */
- public static final String MINOR_NUMBER = "2";
+ public static final String MINOR_NUMBER = "3";
public static final String VERSION_LONG = "1.0 RC" + MINOR_NUMBER;
@@ -272,21 +272,6 @@ public abstract Variant getPreferredVariant(ClientInfo client,
public abstract void parse(Logger logger, Form form,
Representation representation);
- /**
- * Parses an URL encoded query string into a given form.
- *
- * @param logger
- * The logger to use.
- * @param form
- * The target form.
- * @param queryString
- * Query string.
- * @deprecated Use the parse(Logger,String,CharacterSet) method to
- * specify the encoding.
- */
- @Deprecated
- public abstract void parse(Logger logger, Form form, String queryString);
-
/**
* Parses an URL encoded query string into a given form.
*
diff --git a/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java b/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java
index 2e5ac4e842..78b6219ece 100644
--- a/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java
+++ b/module/org.restlet/src/org/restlet/util/WrapperRepresentation.java
@@ -32,7 +32,6 @@
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
-import org.restlet.data.ReferenceList;
import org.restlet.data.Tag;
import org.restlet.resource.Representation;
import org.restlet.resource.Result;
@@ -163,19 +162,6 @@ public Reference getIdentifier() {
return getWrappedRepresentation().getIdentifier();
}
- /**
- * Returns the list of all the identifiers for the resource. The list is
- * composed of the official identifier followed by all the alias
- * identifiers.
- *
- * @return The list of all the identifiers for the resource.
- * @deprecated No obvious usage. More the role of Handler to map URIs.
- */
- @Deprecated
- public ReferenceList getIdentifiers() {
- return getWrappedRepresentation().getIdentifiers();
- }
-
/**
* Returns the language or null if not applicable.
*
@@ -258,19 +244,6 @@ public String getText() throws IOException {
return getWrappedRepresentation().getText();
}
- /**
- * Converts the representation to a string value. Be careful when using this
- * method as the conversion of large content to a string fully stored in
- * memory can result in OutOfMemoryErrors being thrown.
- *
- * @return The representation as a string value.
- * @deprecated Use getText instead
- */
- @Deprecated
- public String getValue() throws IOException {
- return getWrappedRepresentation().getValue();
- }
-
/**
* Returns a full representation for a given variant previously returned via
* the getVariants() method. The default implementation directly returns the
@@ -424,18 +397,6 @@ public void setIdentifier(String identifierUri) {
getWrappedRepresentation().setIdentifier(identifierUri);
}
- /**
- * Sets a new list of all the identifiers for the resource.
- *
- * @param identifiers
- * The new list of identifiers.
- * @deprecated No obvious usage. More the role of Handler to map URIs.
- */
- @Deprecated
- public void setIdentifiers(ReferenceList identifiers) {
- getWrappedRepresentation().setIdentifiers(identifiers);
- }
-
/**
* Sets the language or null if not applicable.
*
diff --git a/module/org.restlet/src/org/restlet/util/WrapperResource.java b/module/org.restlet/src/org/restlet/util/WrapperResource.java
index a94ef728d7..fd277788c3 100644
--- a/module/org.restlet/src/org/restlet/util/WrapperResource.java
+++ b/module/org.restlet/src/org/restlet/util/WrapperResource.java
@@ -22,7 +22,6 @@
import java.util.logging.Logger;
import org.restlet.data.Reference;
-import org.restlet.data.ReferenceList;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.Result;
@@ -108,20 +107,6 @@ public Reference getIdentifier() {
return getWrappedResource().getIdentifier();
}
- /**
- * Returns the list of all the identifiers for the resource. The list is
- * composed of the official identifier followed by all the alias
- * identifiers.
- *
- * @return The list of all the identifiers for the resource.
- * @deprecated The URIs should only be managed by the application routers
- * and handlers.
- */
- @Deprecated
- public ReferenceList getIdentifiers() {
- return getWrappedResource().getIdentifiers();
- }
-
/**
* Returns the logger to use.
*
@@ -217,19 +202,6 @@ public void setIdentifier(String identifierUri) {
getWrappedResource().setIdentifier(identifierUri);
}
- /**
- * Sets a new list of all the identifiers for the resource.
- *
- * @param identifiers
- * The new list of identifiers.
- * @deprecated The URIs should only be managed by the application routers
- * and handlers.
- */
- @Deprecated
- public void setIdentifiers(ReferenceList identifiers) {
- getWrappedResource().setIdentifiers(identifiers);
- }
-
/**
* Sets the logger to use.
*
|
adb90c7f52be4c443a1050b2bfcbcb5cdf8542f5
|
hadoop
|
YARN-2821. Fixed a problem that DistributedShell AM- may hang if restarted. Contributed by Varun Vasudev (cherry picked from- commit 7438966586f1896ab3e8b067d47a4af28a894106)--
|
c
|
https://github.com/apache/hadoop
|
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index c97df938c81ad..16cb27b8361f7 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -375,6 +375,9 @@ Release 2.8.0 - UNRELEASED
YARN-3302. TestDockerContainerExecutor should run automatically if it can
detect docker in the usual place (Ravindra Kumar Naik via raviprak)
+ YARN-2821. Fixed a problem that DistributedShell AM may hang if restarted.
+ (Varun Vasudev via jianhe)
+
Release 2.7.1 - UNRELEASED
INCOMPATIBLE CHANGES
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
index 24f8bcc000e6e..6ac8bf134d2f5 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
@@ -116,6 +116,11 @@
<type>test-jar</type>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
index b62c24cbd711f..b28c0c925c3d9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/main/java/org/apache/hadoop/yarn/applications/distributedshell/ApplicationMaster.java
@@ -30,10 +30,12 @@
import java.nio.ByteBuffer;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -277,6 +279,10 @@ public static enum DSEntity {
private final String linux_bash_command = "bash";
private final String windows_command = "cmd /c";
+ @VisibleForTesting
+ protected final Set<ContainerId> launchedContainers =
+ Collections.newSetFromMap(new ConcurrentHashMap<ContainerId, Boolean>());
+
/**
* @param args Command line args
*/
@@ -601,8 +607,12 @@ public void run() throws YarnException, IOException, InterruptedException {
response.getContainersFromPreviousAttempts();
LOG.info(appAttemptID + " received " + previousAMRunningContainers.size()
+ " previous attempts' running containers on AM registration.");
+ for(Container container: previousAMRunningContainers) {
+ launchedContainers.add(container.getId());
+ }
numAllocatedContainers.addAndGet(previousAMRunningContainers.size());
+
int numTotalContainersToRequest =
numTotalContainers - previousAMRunningContainers.size();
// Setup ask for containers from RM
@@ -715,8 +725,9 @@ protected boolean finish() {
return success;
}
-
- private class RMCallbackHandler implements AMRMClientAsync.CallbackHandler {
+
+ @VisibleForTesting
+ class RMCallbackHandler implements AMRMClientAsync.CallbackHandler {
@SuppressWarnings("unchecked")
@Override
public void onContainersCompleted(List<ContainerStatus> completedContainers) {
@@ -731,6 +742,14 @@ public void onContainersCompleted(List<ContainerStatus> completedContainers) {
// non complete containers should not be here
assert (containerStatus.getState() == ContainerState.COMPLETE);
+ // ignore containers we know nothing about - probably from a previous
+ // attempt
+ if (!launchedContainers.contains(containerStatus.getContainerId())) {
+ LOG.info("Ignoring completed status of "
+ + containerStatus.getContainerId()
+ + "; unknown container(probably launched by previous attempt)");
+ continue;
+ }
// increment counters for completed/failed containers
int exitStatus = containerStatus.getExitStatus();
@@ -796,14 +815,13 @@ public void onContainersAllocated(List<Container> allocatedContainers) {
// + ", containerToken"
// +allocatedContainer.getContainerToken().getIdentifier().toString());
- LaunchContainerRunnable runnableLaunchContainer =
- new LaunchContainerRunnable(allocatedContainer, containerListener);
- Thread launchThread = new Thread(runnableLaunchContainer);
+ Thread launchThread = createLaunchContainerThread(allocatedContainer);
// launch and start the container on a separate thread to keep
// the main thread unblocked
// as all containers may not be allocated at one go.
launchThreads.add(launchThread);
+ launchedContainers.add(allocatedContainer.getId());
launchThread.start();
}
}
@@ -1150,4 +1168,30 @@ private static void publishApplicationAttemptEvent(
+ appAttemptId.toString(), e);
}
}
+
+ RMCallbackHandler getRMCallbackHandler() {
+ return new RMCallbackHandler();
+ }
+
+ @VisibleForTesting
+ void setAmRMClient(AMRMClientAsync client) {
+ this.amRMClient = client;
+ }
+
+ @VisibleForTesting
+ int getNumCompletedContainers() {
+ return numCompletedContainers.get();
+ }
+
+ @VisibleForTesting
+ boolean getDone() {
+ return done;
+ }
+
+ @VisibleForTesting
+ Thread createLaunchContainerThread(Container allocatedContainer) {
+ LaunchContainerRunnable runnableLaunchContainer =
+ new LaunchContainerRunnable(allocatedContainer, containerListener);
+ return new Thread(runnableLaunchContainer);
+ }
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
index 11e840a8c90ad..0fed14d02cc00 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSAppMaster.java
@@ -20,13 +20,143 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.yarn.api.records.Container;
+import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.api.records.ContainerState;
+import org.apache.hadoop.yarn.api.records.ContainerStatus;
+import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.Priority;
+import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.client.api.AMRMClient;
+import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
import org.apache.hadoop.yarn.client.api.impl.TimelineClientImpl;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.exceptions.YarnException;
+import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.junit.Assert;
import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A bunch of tests to make sure that the container allocations
+ * and releases occur correctly.
+ */
public class TestDSAppMaster {
+ static class TestAppMaster extends ApplicationMaster {
+ private int threadsLaunched = 0;
+
+ @Override
+ protected Thread createLaunchContainerThread(Container allocatedContainer) {
+ threadsLaunched++;
+ launchedContainers.add(allocatedContainer.getId());
+ return new Thread();
+ }
+
+ void setNumTotalContainers(int numTotalContainers) {
+ this.numTotalContainers = numTotalContainers;
+ }
+
+ int getAllocatedContainers() {
+ return this.numAllocatedContainers.get();
+ }
+
+ @Override
+ void startTimelineClient(final Configuration conf) throws YarnException,
+ IOException, InterruptedException {
+ timelineClient = null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testDSAppMasterAllocateHandler() throws Exception {
+
+ TestAppMaster master = new TestAppMaster();
+ int targetContainers = 2;
+ AMRMClientAsync mockClient = Mockito.mock(AMRMClientAsync.class);
+ master.setAmRMClient(mockClient);
+ master.setNumTotalContainers(targetContainers);
+ Mockito.doNothing().when(mockClient)
+ .addContainerRequest(Matchers.any(AMRMClient.ContainerRequest.class));
+
+ ApplicationMaster.RMCallbackHandler handler = master.getRMCallbackHandler();
+
+ List<Container> containers = new ArrayList<>(1);
+ ContainerId id1 = BuilderUtils.newContainerId(1, 1, 1, 1);
+ containers.add(generateContainer(id1));
+
+ master.numRequestedContainers.set(targetContainers);
+
+ // first allocate a single container, everything should be fine
+ handler.onContainersAllocated(containers);
+ Assert.assertEquals("Wrong container allocation count", 1,
+ master.getAllocatedContainers());
+ Mockito.verifyZeroInteractions(mockClient);
+ Assert.assertEquals("Incorrect number of threads launched", 1,
+ master.threadsLaunched);
+
+ // now send 3 extra containers
+ containers.clear();
+ ContainerId id2 = BuilderUtils.newContainerId(1, 1, 1, 2);
+ containers.add(generateContainer(id2));
+ ContainerId id3 = BuilderUtils.newContainerId(1, 1, 1, 3);
+ containers.add(generateContainer(id3));
+ ContainerId id4 = BuilderUtils.newContainerId(1, 1, 1, 4);
+ containers.add(generateContainer(id4));
+ handler.onContainersAllocated(containers);
+ Assert.assertEquals("Wrong final container allocation count", 4,
+ master.getAllocatedContainers());
+
+ Assert.assertEquals("Incorrect number of threads launched", 4,
+ master.threadsLaunched);
+
+ // make sure we handle completion events correctly
+ List<ContainerStatus> status = new ArrayList<>();
+ status.add(generateContainerStatus(id1, ContainerExitStatus.SUCCESS));
+ status.add(generateContainerStatus(id2, ContainerExitStatus.SUCCESS));
+ status.add(generateContainerStatus(id3, ContainerExitStatus.ABORTED));
+ status.add(generateContainerStatus(id4, ContainerExitStatus.ABORTED));
+ handler.onContainersCompleted(status);
+
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+
+ // test for events from containers we know nothing about
+ // these events should be ignored
+ status = new ArrayList<>();
+ ContainerId id5 = BuilderUtils.newContainerId(1, 1, 1, 5);
+ status.add(generateContainerStatus(id5, ContainerExitStatus.ABORTED));
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+ status.add(generateContainerStatus(id5, ContainerExitStatus.SUCCESS));
+ Assert.assertEquals("Unexpected number of completed containers",
+ targetContainers, master.getNumCompletedContainers());
+ Assert.assertTrue("Master didn't finish containers as expected",
+ master.getDone());
+ }
+
+ private Container generateContainer(ContainerId cid) {
+ return Container.newInstance(cid, NodeId.newInstance("host", 5000),
+ "host:80", Resource.newInstance(1024, 1), Priority.newInstance(0), null);
+ }
+
+ private ContainerStatus
+ generateContainerStatus(ContainerId id, int exitStatus) {
+ return ContainerStatus.newInstance(id, ContainerState.COMPLETE, "",
+ exitStatus);
+ }
+
@Test
public void testTimelineClientInDSAppMaster() throws Exception {
ApplicationMaster appMaster = new ApplicationMaster();
|
f3cc4e1607184a92210cf1b699328860d4ba3809
|
intellij-community
|
EP for upsource added--
|
a
|
https://github.com/JetBrains/intellij-community
|
diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java b/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java
index 3cd75ed07b6eb..185883c1cfcd0 100644
--- a/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java
+++ b/plugins/properties/properties-psi-impl/src/com/intellij/properties/PropertiesCoreEnvironment.java
@@ -17,6 +17,7 @@ public ApplicationEnvironment(CoreApplicationEnvironment appEnvironment) {
appEnvironment.registerFileType(PropertiesFileType.INSTANCE, "properties");
SyntaxHighlighterFactory.LANGUAGE_FACTORY.addExplicitExtension(PropertiesLanguage.INSTANCE, new PropertiesSyntaxHighlighterFactory());
appEnvironment.addExplicitExtension(LanguageParserDefinitions.INSTANCE, PropertiesLanguage.INSTANCE, new PropertiesParserDefinition());
+ SyntaxHighlighterFactory.LANGUAGE_FACTORY.addExplicitExtension(PropertiesLanguage.INSTANCE, new PropertiesSyntaxHighlighterFactory());
}
}
|
9e843df27fc2dd53c12327e9601206a7c677bd1f
|
orientdb
|
Improved auto-recognize of type in JSON reader--
|
p
|
https://github.com/orientechnologies/orientdb
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
index 7876b46308a..1122716eb39 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java
@@ -62,6 +62,8 @@ public class ORecordSerializerJSON extends ORecordSerializerStringAbstract {
public static final char[] PARAMETER_SEPARATOR = new char[] { ':', ',' };
private static final Long MAX_INT = new Long(Integer.MAX_VALUE);
private static final Long MIN_INT = new Long(Integer.MIN_VALUE);
+ private static final Double MAX_FLOAT = new Double(Float.MAX_VALUE);
+ private static final Double MIN_FLOAT = new Double(Float.MIN_VALUE);
private SimpleDateFormat dateFormat = new SimpleDateFormat(DEF_DATE_FORMAT);
@@ -306,10 +308,21 @@ else if (iType == OType.LINKLIST)
// TRY TO AUTODETERMINE THE BEST TYPE
if (iFieldValue.charAt(0) == ORID.PREFIX && iFieldValue.contains(":"))
iType = OType.LINK;
- else if (OStringSerializerHelper.contains(iFieldValue, '.'))
- iType = OType.FLOAT;
- else {
+ else if (OStringSerializerHelper.contains(iFieldValue, '.')) {
+ // DECIMAL FORMAT: DETERMINE IF DOUBLE OR FLOAT
+ final Double v = new Double(OStringSerializerHelper.getStringContent(iFieldValue));
+ if (v.doubleValue() > 0) {
+ // POSITIVE NUMBER
+ if (v.compareTo(MAX_FLOAT) <= 0)
+ return v.floatValue();
+ } else if (v.compareTo(MIN_FLOAT) >= 0)
+ // NEGATIVE NUMBER
+ return v.floatValue();
+
+ return v;
+ } else {
final Long v = new Long(OStringSerializerHelper.getStringContent(iFieldValue));
+ // INTEGER FORMAT: DETERMINE IF DOUBLE OR FLOAT
if (v.longValue() > 0) {
// POSITIVE NUMBER
if (v.compareTo(MAX_INT) <= 0)
|
329f08bbff00f0f8a71123c68a3200804effb045
|
belaban$jgroups
|
- Added INTERNAL flag (https://issues.jboss.org/browse/JGRP-1599)
- Added internal thread pool to TP (https://issues.jboss.org/browse/JGRP-1599)
- Replaced Message.OOB with Message.Flag.OOB
- Replaced Message.DONT_BUNDLE with Message.Flag.DONT_BUNDLE
- Fa
|
p
|
https://github.com/belaban/jgroups
|
diff --git a/src/org/jgroups/Message.java b/src/org/jgroups/Message.java
index 296ad6a6ef1..b9e2b1970f7 100644
--- a/src/org/jgroups/Message.java
+++ b/src/org/jgroups/Message.java
@@ -62,8 +62,9 @@ public static enum Flag {
SCOPED( (short)(1 << 3)), // when a message has a scope
NO_RELIABILITY((short)(1 << 4)), // bypass UNICAST(2) and NAKACK
NO_TOTAL_ORDER((short)(1 << 5)), // bypass total order (e.g. SEQUENCER)
- NO_RELAY((short) (1 << 6)), // bypass relaying (RELAY)
- RSVP((short) (1 << 7)); // ack of a multicast (https://issues.jboss.org/browse/JGRP-1389)
+ NO_RELAY( (short)(1 << 6)), // bypass relaying (RELAY)
+ RSVP( (short)(1 << 7)), // ack of a multicast (https://issues.jboss.org/browse/JGRP-1389)
+ INTERNAL( (short)(1 << 8)); // for internal use by JGroups only, don't use !
final short value;
Flag(short value) {this.value=value;}
@@ -71,14 +72,14 @@ public static enum Flag {
public short value() {return value;}
}
- public static final Flag OOB=Flag.OOB;
- public static final Flag DONT_BUNDLE=Flag.DONT_BUNDLE;
- public static final Flag NO_FC=Flag.NO_FC;
- public static final Flag SCOPED=Flag.SCOPED;
- public static final Flag NO_RELIABILITY=Flag.NO_RELIABILITY;
- public static final Flag NO_TOTAL_ORDER=Flag.NO_TOTAL_ORDER;
- public static final Flag NO_RELAY=Flag.NO_RELAY;
- public static final Flag RSVP=Flag.RSVP;
+ @Deprecated public static final Flag OOB=Flag.OOB;
+ @Deprecated public static final Flag DONT_BUNDLE=Flag.DONT_BUNDLE;
+ @Deprecated public static final Flag NO_FC=Flag.NO_FC;
+ @Deprecated public static final Flag SCOPED=Flag.SCOPED;
+ @Deprecated public static final Flag NO_RELIABILITY=Flag.NO_RELIABILITY;
+ @Deprecated public static final Flag NO_TOTAL_ORDER=Flag.NO_TOTAL_ORDER;
+ @Deprecated public static final Flag NO_RELAY=Flag.NO_RELAY;
+ @Deprecated public static final Flag RSVP=Flag.RSVP;
@@ -91,7 +92,8 @@ public static enum TransientFlag {
public short value() {return value;}
}
-
+
+ @Deprecated
public static final TransientFlag OOB_DELIVERED=TransientFlag.OOB_DELIVERED; // OOB which has already been delivered up the stack
@@ -837,58 +839,16 @@ public long size() {
public static String flagsToString(short flags) {
StringBuilder sb=new StringBuilder();
boolean first=true;
- if(isFlagSet(flags, Flag.OOB)) {
- first=false;
- sb.append("OOB");
- }
- if(isFlagSet(flags, Flag.DONT_BUNDLE)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("DONT_BUNDLE");
- }
- if(isFlagSet(flags, Flag.NO_FC)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("NO_FC");
- }
- if(isFlagSet(flags, Flag.SCOPED)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("SCOPED");
- }
- if(isFlagSet(flags, Flag.NO_RELIABILITY)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("NO_RELIABILITY");
- }
- if(isFlagSet(flags, Flag.NO_TOTAL_ORDER)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("NO_TOTAL_ORDER");
- }
- if(isFlagSet(flags, Flag.NO_RELAY)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("NO_RELAY");
- }
- if(isFlagSet(flags, Flag.RSVP)) {
- if(!first)
- sb.append("|");
- else
- first=false;
- sb.append("RSVP");
+
+ Flag[] all_flags=Flag.values();
+ for(Flag flag: all_flags) {
+ if(isFlagSet(flags, flag)) {
+ if(first)
+ first=false;
+ else
+ sb.append("|");
+ sb.append(flag);
+ }
}
return sb.toString();
}
@@ -896,8 +856,18 @@ public static String flagsToString(short flags) {
public String transientFlagsToString() {
StringBuilder sb=new StringBuilder();
- if(isTransientFlagSet(TransientFlag.OOB_DELIVERED))
- sb.append("OOB_DELIVERED");
+ boolean first=true;
+
+ TransientFlag[] all_flags=TransientFlag.values();
+ for(TransientFlag flag: all_flags) {
+ if(isTransientFlagSet(flag)) {
+ if(first)
+ first=false;
+ else
+ sb.append("|");
+ sb.append(flag);
+ }
+ }
return sb.toString();
}
diff --git a/src/org/jgroups/auth/DemoToken.java b/src/org/jgroups/auth/DemoToken.java
index 02503981a63..94b99d15edb 100644
--- a/src/org/jgroups/auth/DemoToken.java
+++ b/src/org/jgroups/auth/DemoToken.java
@@ -42,7 +42,7 @@ public boolean authenticate(AuthToken token, Message msg) {
Address sender=msg.getSrc();
// 1. send a challenge to the sender
- Message challenge=new Message(sender).setFlag(Message.OOB);
+ Message challenge=new Message(sender).setFlag(Message.Flag.OOB);
byte[] buf=generateRandomBytes();
DemoHeader hdr=new DemoHeader(buf);
challenge.putHeader(ID, hdr);
diff --git a/src/org/jgroups/blocks/RequestOptions.java b/src/org/jgroups/blocks/RequestOptions.java
index 53a7cee5d0c..585637abe49 100644
--- a/src/org/jgroups/blocks/RequestOptions.java
+++ b/src/org/jgroups/blocks/RequestOptions.java
@@ -31,7 +31,7 @@ public class RequestOptions {
protected short scope;
/** The flags set in the message in which a request is sent */
- protected short flags; // Message.OOB, Message.DONT_BUNDLE etc
+ protected short flags; // Message.Flag.OOB, Message.Flag.DONT_BUNDLE etc
/** A list of members which should be excluded from a call */
protected Set<Address> exclusion_list;
diff --git a/src/org/jgroups/protocols/AUTH.java b/src/org/jgroups/protocols/AUTH.java
index 7b2682d2f16..7b08c204281 100644
--- a/src/org/jgroups/protocols/AUTH.java
+++ b/src/org/jgroups/protocols/AUTH.java
@@ -185,17 +185,13 @@ protected void sendJoinRejectionMessage(Address dest, String error_msg) {
if(dest == null)
return;
- Message msg = new Message(dest, null, null);
JoinRsp joinRes=new JoinRsp(error_msg); // specify the error message on the JoinRsp
-
- GMS.GmsHeader gmsHeader=new GMS.GmsHeader(GMS.GmsHeader.JOIN_RSP, joinRes);
- msg.putHeader(gms_id, gmsHeader);
+ Message msg = new Message(dest).putHeader(gms_id, new GMS.GmsHeader(GMS.GmsHeader.JOIN_RSP, joinRes));
down_prot.down(new Event(Event.MSG, msg));
}
protected void sendMergeRejectionMessage(Address dest) {
- Message msg=new Message(dest, null, null);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(dest).setFlag(Message.Flag.OOB);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.setMergeRejected(true);
msg.putHeader(gms_id, hdr);
diff --git a/src/org/jgroups/protocols/COUNTER.java b/src/org/jgroups/protocols/COUNTER.java
index d96fe882aba..a679ea02601 100644
--- a/src/org/jgroups/protocols/COUNTER.java
+++ b/src/org/jgroups/protocols/COUNTER.java
@@ -431,10 +431,9 @@ protected Owner getOwner() {
protected void sendRequest(Address dest, Request req) {
try {
Buffer buffer=requestToBuffer(req);
- Message msg=new Message(dest, null, buffer);
- msg.putHeader(id, new CounterHeader());
+ Message msg=new Message(dest, buffer).putHeader(id, new CounterHeader());
if(bypass_bundling)
- msg.setFlag(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + (dest == null? "ALL" : dest) + "] " + req);
@@ -449,10 +448,9 @@ protected void sendRequest(Address dest, Request req) {
protected void sendResponse(Address dest, Response rsp) {
try {
Buffer buffer=responseToBuffer(rsp);
- Message rsp_msg=new Message(dest, null, buffer);
- rsp_msg.putHeader(id, new CounterHeader());
+ Message rsp_msg=new Message(dest, buffer).putHeader(id, new CounterHeader());
if(bypass_bundling)
- rsp_msg.setFlag(Message.DONT_BUNDLE);
+ rsp_msg.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + dest + "] " + rsp);
@@ -480,10 +478,9 @@ protected void updateBackups(String name, long value, long version) {
protected void send(Address dest, Buffer buffer) {
try {
- Message rsp_msg=new Message(dest, null, buffer);
- rsp_msg.putHeader(id, new CounterHeader());
+ Message rsp_msg=new Message(dest, buffer).putHeader(id, new CounterHeader());
if(bypass_bundling)
- rsp_msg.setFlag(Message.DONT_BUNDLE);
+ rsp_msg.setFlag(Message.Flag.DONT_BUNDLE);
down_prot.down(new Event(Event.MSG, rsp_msg));
}
catch(Exception ex) {
diff --git a/src/org/jgroups/protocols/DAISYCHAIN.java b/src/org/jgroups/protocols/DAISYCHAIN.java
index 42a04d1e94c..e087bb5eec8 100644
--- a/src/org/jgroups/protocols/DAISYCHAIN.java
+++ b/src/org/jgroups/protocols/DAISYCHAIN.java
@@ -101,7 +101,7 @@ public Object down(final Event evt) {
if(msg.getSrc() == null)
msg.setSrc(local_addr);
- Executor pool=msg.isFlagSet(Message.OOB)? oob_pool : default_pool;
+ Executor pool=msg.isFlagSet(Message.Flag.OOB)? oob_pool : default_pool;
pool.execute(new Runnable() {
public void run() {
up_prot.up(evt);
diff --git a/src/org/jgroups/protocols/Discovery.java b/src/org/jgroups/protocols/Discovery.java
index 20ab754bfe5..65426fcc420 100644
--- a/src/org/jgroups/protocols/Discovery.java
+++ b/src/org/jgroups/protocols/Discovery.java
@@ -259,8 +259,10 @@ public void sendDiscoveryRequest(String cluster_name, Promise promise, ViewId vi
Collection<PhysicalAddress> cluster_members=fetchClusterMembers(cluster_name);
if(cluster_members == null) {
- // multicast msg
- Message msg=new Message(null).setFlag(Message.OOB, Message.Flag.DONT_BUNDLE).putHeader(getId(), hdr);
+ // message needs to have DONT_BUNDLE flag: if A sends message M to B, and we need to fetch B's physical
+ // address, then the bundler thread blocks until the discovery request has returned. However, we cannot send
+ // the discovery *request* until the bundler thread has returned from sending M
+ Message msg=new Message(null).setFlag(Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE).putHeader(getId(), hdr);
sendMcastDiscoveryRequest(msg);
}
else {
@@ -281,7 +283,9 @@ public void sendDiscoveryRequest(String cluster_name, Promise promise, ViewId vi
for(final Address addr: cluster_members) {
if(addr.equals(physical_addr)) // no need to send the request to myself
continue;
- final Message msg=new Message(addr).setFlag(Message.OOB, Message.Flag.DONT_BUNDLE).putHeader(this.id, hdr);
+ // the message needs to be DONT_BUNDLE, see explanation above
+ final Message msg=new Message(addr).setFlag(Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE)
+ .putHeader(this.id, hdr);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending discovery request to " + msg.getDest());
if(!sendDiscoveryRequestsInParallel()) {
@@ -634,9 +638,8 @@ protected void sendDiscoveryResponse(Address logical_addr, List<PhysicalAddress>
data=new PingData(logical_addr, null, view_id, is_server, logical_name, physical_addrs);
}
- final Message rsp_msg=new Message(sender).setFlag(Message.OOB);
final PingHeader rsp_hdr=new PingHeader(PingHeader.GET_MBRS_RSP, data);
- rsp_msg.putHeader(this.id, rsp_hdr);
+ final Message rsp_msg=new Message(sender).setFlag(Message.Flag.INTERNAL).putHeader(this.id, rsp_hdr);
if(stagger_timeout > 0) {
int view_size=view != null? view.size() : 10;
diff --git a/src/org/jgroups/protocols/ENCRYPT.java b/src/org/jgroups/protocols/ENCRYPT.java
index d3c212cfc9e..0d389e37036 100644
--- a/src/org/jgroups/protocols/ENCRYPT.java
+++ b/src/org/jgroups/protocols/ENCRYPT.java
@@ -842,9 +842,8 @@ private void sendSecretKey(SecretKey secret, PublicKey pubKey, Address source) t
//encrypt current secret key
byte[] encryptedKey=tmp.doFinal(secret.getEncoded());
- newMsg=new Message(source, local_addr, encryptedKey);
-
- newMsg.putHeader(this.id, new EncryptHeader(EncryptHeader.SECRETKEY, getSymVersion()));
+ newMsg=new Message(source, local_addr, encryptedKey)
+ .putHeader(this.id, new EncryptHeader(EncryptHeader.SECRETKEY, getSymVersion()));
if(log.isDebugEnabled())
log.debug(" Sending version " + getSymVersion() + " encoded key to client");
@@ -860,9 +859,8 @@ private Message sendKeyRequest() {
// send client's public key to server and request
// server's public key
- Message newMsg=new Message(keyServerAddr, local_addr, Kpair.getPublic().getEncoded());
-
- newMsg.putHeader(this.id,new EncryptHeader(EncryptHeader.KEY_REQUEST,getSymVersion()));
+ Message newMsg=new Message(keyServerAddr, local_addr, Kpair.getPublic().getEncoded())
+ .putHeader(this.id,new EncryptHeader(EncryptHeader.KEY_REQUEST,getSymVersion()));
passItDown(new Event(Event.MSG,newMsg));
return newMsg;
}
diff --git a/src/org/jgroups/protocols/Executing.java b/src/org/jgroups/protocols/Executing.java
index 92874bbfedb..68ad844ef04 100644
--- a/src/org/jgroups/protocols/Executing.java
+++ b/src/org/jgroups/protocols/Executing.java
@@ -1,43 +1,6 @@
package org.jgroups.protocols;
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.io.Serializable;
-import java.nio.ByteBuffer;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.CyclicBarrier;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.RunnableFuture;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import org.jgroups.Address;
-import org.jgroups.Event;
-import org.jgroups.Header;
-import org.jgroups.Message;
-import org.jgroups.View;
+import org.jgroups.*;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.Property;
@@ -48,6 +11,16 @@
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.concurrent.*;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
/**
* This is the base protocol used for executions.
* @author wburns
@@ -901,10 +874,9 @@ protected void handleRemoveConsumer(Owner sender) {
protected void sendRequest(Address dest, Type type, long requestId, Object object) {
Request req=new Request(type, object, requestId);
- Message msg=new Message(dest, null, req);
- msg.putHeader(id, new ExecutorHeader());
+ Message msg=new Message(dest, req).putHeader(id, new ExecutorHeader());
if(bypass_bundling)
- msg.setFlag(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + (dest == null? "ALL" : dest) + "] " + req);
try {
@@ -918,10 +890,9 @@ protected void sendRequest(Address dest, Type type, long requestId, Object objec
protected void sendThreadRequest(Address dest, long threadId, Type type, long requestId,
Object object) {
RequestWithThread req=new RequestWithThread(type, object, requestId, threadId);
- Message msg=new Message(dest, null, req);
- msg.putHeader(id, new ExecutorHeader());
+ Message msg=new Message(dest, req).putHeader(id, new ExecutorHeader());
if(bypass_bundling)
- msg.setFlag(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + (dest == null? "ALL" : dest) + "] " + req);
try {
diff --git a/src/org/jgroups/protocols/FC.java b/src/org/jgroups/protocols/FC.java
index c6c5d00412c..49f8d2346bc 100644
--- a/src/org/jgroups/protocols/FC.java
+++ b/src/org/jgroups/protocols/FC.java
@@ -781,7 +781,8 @@ private void sendCredit(Address dest, long credit) {
number=(int)credit;
else
number=credit;
- Message msg=new Message(dest, number).setFlag(Message.OOB, Message.Flag.DONT_BUNDLE).putHeader(this.id,REPLENISH_HDR);
+ Message msg=new Message(dest, number).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE)
+ .putHeader(this.id,REPLENISH_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_responses_sent++;
}
@@ -795,7 +796,8 @@ private void sendCredit(Address dest, long credit) {
private void sendCreditRequest(final Address dest, Long credits_left) {
if(log.isTraceEnabled())
log.trace("sending credit request to " + dest);
- Message msg=new Message(dest, credits_left).setFlag(Message.Flag.DONT_BUNDLE).putHeader(this.id,CREDIT_REQUEST_HDR);
+ Message msg=new Message(dest, credits_left).setFlag(Message.Flag.DONT_BUNDLE, Message.Flag.INTERNAL)
+ .putHeader(this.id,CREDIT_REQUEST_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_requests_sent++;
}
diff --git a/src/org/jgroups/protocols/FD.java b/src/org/jgroups/protocols/FD.java
index f88394cc304..19a723cef54 100644
--- a/src/org/jgroups/protocols/FD.java
+++ b/src/org/jgroups/protocols/FD.java
@@ -309,7 +309,7 @@ else if(!isMonitorRunning())
protected void sendHeartbeatResponse(Address dest) {
- Message hb_ack=new Message(dest).setFlag(Message.OOB);
+ Message hb_ack=new Message(dest).setFlag(Message.Flag.INTERNAL);
FdHeader tmp_hdr=new FdHeader(FdHeader.HEARTBEAT_ACK);
tmp_hdr.from=local_addr;
hb_ack.putHeader(this.id, tmp_hdr);
@@ -437,7 +437,7 @@ public void run() {
}
// 1. send heartbeat request
- Message hb_req=new Message(dest).setFlag(Message.OOB).putHeader(id, new FdHeader(FdHeader.HEARTBEAT));
+ Message hb_req=new Message(dest).setFlag(Message.Flag.INTERNAL).putHeader(id, new FdHeader(FdHeader.HEARTBEAT));
if(log.isDebugEnabled())
log.debug(local_addr + ": sending are-you-alive msg to " + dest);
down_prot.down(new Event(Event.MSG, hb_req));
@@ -599,7 +599,7 @@ public void run() {
hdr.mbrs=new ArrayList<Address>(suspected_members);
hdr.from=local_addr;
}
- Message suspect_msg=new Message().setFlag(Message.OOB).putHeader(id, hdr);
+ Message suspect_msg=new Message().setFlag(Message.Flag.INTERNAL).putHeader(id, hdr);
if(log.isDebugEnabled())
log.debug(local_addr + ": broadcasting SUSPECT message (suspects=" + suspected_members + ")");
down_prot.down(new Event(Event.MSG, suspect_msg));
diff --git a/src/org/jgroups/protocols/FD_ALL.java b/src/org/jgroups/protocols/FD_ALL.java
index cdd8ca31536..1ebb17e8e13 100644
--- a/src/org/jgroups/protocols/FD_ALL.java
+++ b/src/org/jgroups/protocols/FD_ALL.java
@@ -386,7 +386,7 @@ public void readFrom(DataInput in) throws Exception {}
*/
class HeartbeatSender implements Runnable {
public void run() {
- Message heartbeat=new Message().setFlag(Message.OOB).putHeader(id, new HeartbeatHeader());
+ Message heartbeat=new Message().setFlag(Message.Flag.INTERNAL).putHeader(id, new HeartbeatHeader());
down_prot.down(new Event(Event.MSG, heartbeat));
num_heartbeats_sent++;
}
diff --git a/src/org/jgroups/protocols/FD_SOCK.java b/src/org/jgroups/protocols/FD_SOCK.java
index 1358946b956..56487dc536a 100644
--- a/src/org/jgroups/protocols/FD_SOCK.java
+++ b/src/org/jgroups/protocols/FD_SOCK.java
@@ -256,9 +256,7 @@ public Object up(Event evt) {
case FdHeader.GET_CACHE:
Address sender=msg.getSrc(); // guaranteed to be non-null
hdr=new FdHeader(FdHeader.GET_CACHE_RSP,new HashMap<Address,IpAddress>(cache));
- msg=new Message(sender, null, null);
- msg.setFlag(Message.OOB);
- msg.putHeader(this.id, hdr);
+ msg=new Message(sender).setFlag(Message.Flag.INTERNAL).putHeader(this.id, hdr);
down_prot.down(new Event(Event.MSG, msg));
break;
@@ -656,9 +654,7 @@ void getCacheFromCoordinator() {
return;
}
hdr=new FdHeader(FdHeader.GET_CACHE);
- msg=new Message(coord, null, null);
- msg.setFlag(Message.OOB);
- msg.putHeader(this.id, hdr);
+ msg=new Message(coord).setFlag(Message.Flag.INTERNAL).putHeader(this.id, hdr);
down_prot.down(new Event(Event.MSG, msg));
result=get_cache_promise.getResult(get_cache_timeout);
if(result != null) {
@@ -694,9 +690,7 @@ void broadcastSuspectMessage(Address suspected_mbr) {
hdr=new FdHeader(FdHeader.SUSPECT);
hdr.mbrs=new HashSet<Address>(1);
hdr.mbrs.add(suspected_mbr);
- suspect_msg=new Message();
- suspect_msg.setFlag(Message.OOB);
- suspect_msg.putHeader(this.id, hdr);
+ suspect_msg=new Message().setFlag(Message.Flag.INTERNAL).putHeader(this.id, hdr);
down_prot.down(new Event(Event.MSG, suspect_msg));
// 2. Add to broadcast task and start latter (if not yet running). The task will end when
@@ -716,8 +710,7 @@ void broadcastSuspectMessage(Address suspected_mbr) {
it will be unicast back to the requester
*/
void sendIHaveSockMessage(Address dst, Address mbr, IpAddress addr) {
- Message msg=new Message(dst, null, null);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(dst).setFlag(Message.Flag.INTERNAL);
FdHeader hdr=new FdHeader(FdHeader.I_HAVE_SOCK);
hdr.mbr=mbr;
hdr.sock_addr=addr;
@@ -746,8 +739,7 @@ private IpAddress fetchPingAddress(Address mbr) {
// 2. Try to get the server socket address from mbr
ping_addr_promise.reset();
- ping_addr_req=new Message(mbr, null, null); // unicast
- ping_addr_req.setFlag(Message.OOB);
+ ping_addr_req=new Message(mbr).setFlag(Message.Flag.INTERNAL);
hdr=new FdHeader(FdHeader.WHO_HAS_SOCK);
hdr.mbr=mbr;
ping_addr_req.putHeader(this.id, hdr);
@@ -760,8 +752,7 @@ private IpAddress fetchPingAddress(Address mbr) {
if(!isPingerThreadRunning()) return null;
// 3. Try to get the server socket address from all members
- ping_addr_req=new Message(null); // multicast
- ping_addr_req.setFlag(Message.OOB);
+ ping_addr_req=new Message(null).setFlag(Message.Flag.INTERNAL);
hdr=new FdHeader(FdHeader.WHO_HAS_SOCK);
hdr.mbr=mbr;
ping_addr_req.putHeader(this.id, hdr);
@@ -1224,9 +1215,7 @@ public void run() {
hdr=new FdHeader(FdHeader.SUSPECT);
hdr.mbrs=new HashSet<Address>(suspects);
}
- suspect_msg=new Message(); // mcast SUSPECT to all members
- suspect_msg.setFlag(Message.OOB);
- suspect_msg.putHeader(id, hdr);
+ suspect_msg=new Message().setFlag(Message.Flag.INTERNAL).putHeader(id, hdr); // mcast SUSPECT to all members
down_prot.down(new Event(Event.MSG, suspect_msg));
if(log.isTraceEnabled()) log.trace("task done");
}
diff --git a/src/org/jgroups/protocols/FORWARD_TO_COORD.java b/src/org/jgroups/protocols/FORWARD_TO_COORD.java
index e797fc6db14..41b704ab2df 100644
--- a/src/org/jgroups/protocols/FORWARD_TO_COORD.java
+++ b/src/org/jgroups/protocols/FORWARD_TO_COORD.java
@@ -180,10 +180,7 @@ protected void sendNotCoord(Address target, long ack_id) {
}
protected void send(Address target, long ack_id, byte type) {
- Message msg=new Message(target);
- ForwardHeader hdr=new ForwardHeader(type, ack_id);
- msg.putHeader(id, hdr);
- down_prot.down(new Event(Event.MSG, msg));
+ down_prot.down(new Event(Event.MSG, new Message(target).putHeader(id, new ForwardHeader(type, ack_id))));
}
diff --git a/src/org/jgroups/protocols/FlowControl.java b/src/org/jgroups/protocols/FlowControl.java
index 98b67744a38..a36ad2b1c48 100644
--- a/src/org/jgroups/protocols/FlowControl.java
+++ b/src/org/jgroups/protocols/FlowControl.java
@@ -528,15 +528,15 @@ protected void handleCreditRequest(Map<Address,Credit> map, Address sender, long
protected void sendCredit(Address dest, long credits) {
if(log.isTraceEnabled())
if(log.isTraceEnabled()) log.trace("sending " + credits + " credits to " + dest);
- Message msg=new Message(dest, null,credits);
- msg.setFlag(Message.OOB, Message.Flag.DONT_BUNDLE);
- msg.putHeader(this.id, REPLENISH_HDR);
+ Message msg=new Message(dest, credits)
+ .setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id,REPLENISH_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_responses_sent++;
}
/**
- * We cannot send this request as OOB messages, as the credit request needs to queue up behind the regular messages;
+ * We cannot send this request as OOB message, as the credit request needs to queue up behind the regular messages;
* if a receiver cannot process the regular messages, that is a sign that the sender should be throttled !
* @param dest The member to which we send the credit request
* @param credits_needed The number of bytes (of credits) left for dest
@@ -544,8 +544,8 @@ protected void sendCredit(Address dest, long credits) {
protected void sendCreditRequest(final Address dest, Long credits_needed) {
if(log.isTraceEnabled())
log.trace("sending request for " + credits_needed + " credits to " + dest);
- Message msg=new Message(dest, null, credits_needed).setFlag(Message.Flag.DONT_BUNDLE);
- msg.putHeader(this.id, CREDIT_REQUEST_HDR);
+ Message msg=new Message(dest, credits_needed).setFlag(Message.Flag.INTERNAL)
+ .putHeader(this.id, CREDIT_REQUEST_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_requests_sent++;
}
diff --git a/src/org/jgroups/protocols/Locking.java b/src/org/jgroups/protocols/Locking.java
index 325f164d358..38439167156 100644
--- a/src/org/jgroups/protocols/Locking.java
+++ b/src/org/jgroups/protocols/Locking.java
@@ -1,31 +1,6 @@
package org.jgroups.protocols;
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.LockSupport;
-
-import org.jgroups.Address;
-import org.jgroups.Event;
-import org.jgroups.Header;
-import org.jgroups.Message;
-import org.jgroups.View;
+import org.jgroups.*;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
@@ -33,11 +8,22 @@
import org.jgroups.blocks.locking.AwaitInfo;
import org.jgroups.blocks.locking.LockInfo;
import org.jgroups.blocks.locking.LockNotification;
-import org.jgroups.util.Owner;
import org.jgroups.stack.Protocol;
+import org.jgroups.util.Owner;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.util.*;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.LockSupport;
+
/**
@@ -360,10 +346,9 @@ protected Owner getOwner() {
protected void sendRequest(Address dest, Type type, String lock_name, Owner owner, long timeout, boolean is_trylock) {
Request req=new Request(type, lock_name, owner, timeout, is_trylock);
- Message msg=new Message(dest, null, req);
- msg.putHeader(id, new LockingHeader());
+ Message msg=new Message(dest, req).putHeader(id, new LockingHeader());
if(bypass_bundling)
- msg.setFlag(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + (dest == null? "ALL" : dest) + "] " + req);
try {
@@ -377,10 +362,9 @@ protected void sendRequest(Address dest, Type type, String lock_name, Owner owne
protected void sendLockResponse(Type type, Owner dest, String lock_name) {
Request rsp=new Request(type, lock_name, dest, 0);
- Message lock_granted_rsp=new Message(dest.getAddress(), null, rsp);
- lock_granted_rsp.putHeader(id, new LockingHeader());
+ Message lock_granted_rsp=new Message(dest.getAddress(), rsp).putHeader(id, new LockingHeader());
if(bypass_bundling)
- lock_granted_rsp.setFlag(Message.DONT_BUNDLE);
+ lock_granted_rsp.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + dest.getAddress() + "] " + rsp);
@@ -396,10 +380,9 @@ protected void sendLockResponse(Type type, Owner dest, String lock_name) {
protected void sendSignalResponse(Owner dest, String lock_name) {
Request rsp=new Request(Type.SIG_RET, lock_name, dest, 0);
- Message lock_granted_rsp=new Message(dest.getAddress(), null, rsp);
- lock_granted_rsp.putHeader(id, new LockingHeader());
+ Message lock_granted_rsp=new Message(dest.getAddress(), rsp).putHeader(id, new LockingHeader());
if(bypass_bundling)
- lock_granted_rsp.setFlag(Message.DONT_BUNDLE);
+ lock_granted_rsp.setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace("[" + local_addr + "] --> [" + dest.getAddress() + "] " + rsp);
diff --git a/src/org/jgroups/protocols/MERGE3.java b/src/org/jgroups/protocols/MERGE3.java
index 2d35621c7bb..48c19b2a60a 100644
--- a/src/org/jgroups/protocols/MERGE3.java
+++ b/src/org/jgroups/protocols/MERGE3.java
@@ -274,8 +274,7 @@ public Object up(Event evt) {
case VIEW_REQ:
View tmp_view=view != null? view.copy() : null;
Header tmphdr=MergeHeader.createViewResponse(tmp_view);
- Message view_rsp=new Message(sender);
- view_rsp.putHeader(getId(), tmphdr);
+ Message view_rsp=new Message(sender).setFlag(Message.Flag.INTERNAL).putHeader(getId(),tmphdr);
down_prot.down(new Event(Event.MSG, view_rsp));
break;
case VIEW_RSP:
@@ -318,8 +317,7 @@ public void run() {
MergeHeader hdr=MergeHeader.createInfo(view_id, logical_name, Arrays.asList(physical_addr));
if(transport_supports_multicasting) {
- Message msg=new Message();
- msg.putHeader(getId(), hdr);
+ Message msg=new Message().setFlag(Message.Flag.INTERNAL).putHeader(getId(), hdr);
down_prot.down(new Event(Event.MSG, msg));
return;
}
@@ -339,8 +337,7 @@ public void run() {
log.trace("discovery protocol " + discovery_protocol.getName() + " returned " + physical_addrs.size() +
" physical addresses: " + Util.printListWithDelimiter(physical_addrs, ", ", 10));
for(Address addr: physical_addrs) {
- Message info=new Message(addr);
- info.putHeader(getId(), hdr);
+ Message info=new Message(addr).setFlag(Message.Flag.INTERNAL).putHeader(getId(), hdr);
down_prot.down(new Event(Event.MSG, info));
}
}
@@ -428,9 +425,8 @@ protected void _run() {
view_rsps.add(local_addr, view.copy());
continue;
}
- Message view_req=new Message(target);
- Header hdr=MergeHeader.createViewRequest();
- view_req.putHeader(getId(), hdr);
+ Message view_req=new Message(target).setFlag(Message.Flag.INTERNAL)
+ .putHeader(getId(), MergeHeader.createViewRequest());
down_prot.down(new Event(Event.MSG, view_req));
}
view_rsps.waitForAllResponses(check_interval / 10);
diff --git a/src/org/jgroups/protocols/PRIO.java b/src/org/jgroups/protocols/PRIO.java
index c8486b61aa3..ce03985ad85 100644
--- a/src/org/jgroups/protocols/PRIO.java
+++ b/src/org/jgroups/protocols/PRIO.java
@@ -98,7 +98,7 @@ public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message message = (Message)evt.getArg();
- if ( message.isFlagSet( Message.OOB ) ) {
+ if ( message.isFlagSet( Message.Flag.OOB ) ) {
return up_prot.up(evt);
}
else {
@@ -146,7 +146,7 @@ public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message message = (Message)evt.getArg();
- if ( message.isFlagSet( Message.OOB ) ) {
+ if ( message.isFlagSet( Message.Flag.OOB ) ) {
return down_prot.down(evt);
}
else {
diff --git a/src/org/jgroups/protocols/RELAY.java b/src/org/jgroups/protocols/RELAY.java
index 80c0c4a2e9e..873e269d030 100644
--- a/src/org/jgroups/protocols/RELAY.java
+++ b/src/org/jgroups/protocols/RELAY.java
@@ -323,8 +323,7 @@ protected Object installView(byte[] buf, int offset, int length) {
/** Forwards the message across the TCP link to the other local cluster */
protected void forward(byte[] buffer, int offset, int length) {
- Message msg=new Message(null, null, buffer, offset, length);
- msg.putHeader(id, new RelayHeader(RelayHeader.Type.FORWARD));
+ Message msg=new Message(null, null, buffer, offset, length).putHeader(id, new RelayHeader(RelayHeader.Type.FORWARD));
if(bridge != null) {
try {
bridge.send(msg);
@@ -366,8 +365,7 @@ protected void sendViewToRemote(ViewData view_data, boolean use_seperate_thread)
try {
if(bridge != null && bridge.isConnected()) {
byte[] buf=Util.streamableToByteBuffer(view_data);
- final Message msg=new Message(null, null, buf);
- msg.putHeader(id, RelayHeader.create(RelayHeader.Type.VIEW));
+ final Message msg=new Message(null, buf).putHeader(id, RelayHeader.create(RelayHeader.Type.VIEW));
if(use_seperate_thread) {
timer.execute(new Runnable() {
public void run() {
@@ -503,9 +501,7 @@ public void run() {
protected void sendViewOnLocalCluster(final List<Address> destinations, final byte[] buffer) {
for(Address dest: destinations) {
- Message view_msg=new Message(dest, null, buffer);
- RelayHeader hdr=RelayHeader.create(RelayHeader.Type.VIEW);
- view_msg.putHeader(id, hdr);
+ Message view_msg=new Message(dest, buffer).putHeader(id, RelayHeader.create(RelayHeader.Type.VIEW));
down_prot.down(new Event(Event.MSG, view_msg));
}
}
@@ -614,8 +610,7 @@ protected class RemoteViewFetcher implements Runnable {
public void run() {
if(bridge == null || !bridge.isConnected() || remote_view != null)
return;
- Message msg=new Message();
- msg.putHeader(id, RelayHeader.create(RELAY.RelayHeader.Type.BROADCAST_VIEW));
+ Message msg=new Message().putHeader(id, RelayHeader.create(RELAY.RelayHeader.Type.BROADCAST_VIEW));
try {
bridge.send(msg);
}
diff --git a/src/org/jgroups/protocols/RSVP.java b/src/org/jgroups/protocols/RSVP.java
index 7803aae3fea..314b701d624 100644
--- a/src/org/jgroups/protocols/RSVP.java
+++ b/src/org/jgroups/protocols/RSVP.java
@@ -241,10 +241,9 @@ protected void handleResponse(Address member, short id) {
protected void sendResponse(Address dest, short id) {
try {
- Message msg=new Message(dest);
- msg.setFlag(Message.Flag.RSVP, Message.Flag.DONT_BUNDLE);
RsvpHeader hdr=new RsvpHeader(RsvpHeader.RSP,id);
- msg.putHeader(this.id, hdr);
+ Message msg=new Message(dest).setFlag(Message.Flag.RSVP, Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE)
+ .putHeader(this.id, hdr);
if(log.isTraceEnabled())
log.trace(local_addr + ": " + hdr.typeToString() + " --> " + dest);
down_prot.down(new Event(Event.MSG, msg));
@@ -286,9 +285,8 @@ public void run() {
cancelTask();
return;
}
- Message msg=new Message(target).setFlag(Message.Flag.RSVP);
RsvpHeader hdr=new RsvpHeader(RsvpHeader.REQ_ONLY, rsvp_id);
- msg.putHeader(id, hdr);
+ Message msg=new Message(target).setFlag(Message.Flag.RSVP).putHeader(id,hdr);
if(log.isTraceEnabled())
log.trace(local_addr + ": " + hdr.typeToString() + " --> " + target);
down_prot.down(new Event(Event.MSG, msg));
diff --git a/src/org/jgroups/protocols/SCOPE.java b/src/org/jgroups/protocols/SCOPE.java
index db8463ddcca..44e733bc4c1 100644
--- a/src/org/jgroups/protocols/SCOPE.java
+++ b/src/org/jgroups/protocols/SCOPE.java
@@ -217,7 +217,7 @@ public Object up(Event evt) {
Message msg=(Message)evt.getArg();
// we don't handle unscoped or OOB messages
- if(!msg.isFlagSet(Message.SCOPED) || msg.isFlagSet(Message.OOB))
+ if(!msg.isFlagSet(Message.SCOPED) || msg.isFlagSet(Message.Flag.OOB))
break;
ScopeHeader hdr=(ScopeHeader)msg.getHeader(id);
@@ -248,7 +248,7 @@ public Object up(Event evt) {
public void up(MessageBatch batch) {
for(Message msg: batch) {
- if(!msg.isFlagSet(Message.SCOPED) || msg.isFlagSet(Message.OOB)) // we don't handle unscoped or OOB messages
+ if(!msg.isFlagSet(Message.SCOPED) || msg.isFlagSet(Message.Flag.OOB)) // we don't handle unscoped or OOB messages
continue;
ScopeHeader hdr=(ScopeHeader)msg.getHeader(id);
diff --git a/src/org/jgroups/protocols/SEQUENCER.java b/src/org/jgroups/protocols/SEQUENCER.java
index 02e902d82ad..44f08214260 100644
--- a/src/org/jgroups/protocols/SEQUENCER.java
+++ b/src/org/jgroups/protocols/SEQUENCER.java
@@ -144,7 +144,7 @@ public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
- if(msg.getDest() != null || msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.OOB))
+ if(msg.getDest() != null || msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.Flag.OOB))
break;
if(msg.getSrc() == null)
@@ -202,7 +202,7 @@ public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
msg=(Message)evt.getArg();
- if(msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.OOB))
+ if(msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.Flag.OOB))
break;
hdr=(SequencerHeader)msg.getHeader(this.id);
if(hdr == null)
@@ -255,7 +255,7 @@ public Object up(Event evt) {
public void up(MessageBatch batch) {
for(Message msg: batch) {
- if(msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.OOB) || msg.getHeader(id) == null)
+ if(msg.isFlagSet(Message.NO_TOTAL_ORDER) || msg.isFlagSet(Message.Flag.OOB) || msg.getHeader(id) == null)
continue;
batch.remove(msg);
@@ -349,9 +349,8 @@ protected void flushMessagesInForwardTable() {
Long key=entry.getKey();
byte[] val=entry.getValue();
- Message forward_msg=new Message(null, val);
SequencerHeader hdr=new SequencerHeader(SequencerHeader.WRAPPED_BCAST, key);
- forward_msg.putHeader(this.id,hdr);
+ Message forward_msg=new Message(null, val).putHeader(this.id, hdr);
if(log.isTraceEnabled())
log.trace(local_addr + ": flushing (broadcasting) " + local_addr + "::" + key);
down_prot.down(new Event(Event.MSG, forward_msg));
@@ -376,10 +375,8 @@ protected void flushMessagesInForwardTable() {
byte[] val=entry.getValue();
while(flushing && running && !forward_table.isEmpty()) {
- Message forward_msg=new Message(coord, val);
SequencerHeader hdr=new SequencerHeader(SequencerHeader.FLUSH, key);
- forward_msg.putHeader(this.id,hdr);
- forward_msg.setFlag(Message.Flag.DONT_BUNDLE);
+ Message forward_msg=new Message(coord, val).putHeader(this.id,hdr).setFlag(Message.Flag.DONT_BUNDLE);
if(log.isTraceEnabled())
log.trace(local_addr + ": flushing (forwarding) " + local_addr + "::" + key + " to coord " + coord);
ack_promise.reset();
@@ -426,10 +423,9 @@ protected void forward(final byte[] marshalled_msg, long seqno, boolean flush) {
Address target=coord;
if(target == null)
return;
- Message forward_msg=new Message(target, marshalled_msg);
byte type=flush? SequencerHeader.FLUSH : SequencerHeader.FORWARD;
SequencerHeader hdr=new SequencerHeader(type, seqno);
- forward_msg.putHeader(this.id,hdr);
+ Message forward_msg=new Message(target, marshalled_msg).putHeader(this.id,hdr);
down_prot.down(new Event(Event.MSG, forward_msg));
forwarded_msgs++;
}
@@ -441,9 +437,8 @@ protected void broadcast(final Message msg, boolean copy, Address original_sende
bcast_msg=msg; // no need to add a header, message already has one
}
else {
- bcast_msg=new Message(null, msg.getRawBuffer(), msg.getOffset(), msg.getLength());
SequencerHeader new_hdr=new SequencerHeader(SequencerHeader.WRAPPED_BCAST, seqno);
- bcast_msg.putHeader(this.id, new_hdr);
+ bcast_msg=new Message(null, msg.getRawBuffer(), msg.getOffset(), msg.getLength()).putHeader(this.id, new_hdr);
if(resend) {
new_hdr.flush_ack=true;
bcast_msg.setFlag(Message.Flag.DONT_BUNDLE);
diff --git a/src/org/jgroups/protocols/STOMP.java b/src/org/jgroups/protocols/STOMP.java
index 293b8a28d9a..acebac964de 100644
--- a/src/org/jgroups/protocols/STOMP.java
+++ b/src/org/jgroups/protocols/STOMP.java
@@ -342,8 +342,7 @@ protected String getAllEndpoints() {
protected void broadcastEndpoint() {
if(endpoint != null) {
- Message msg=new Message();
- msg.putHeader(id, StompHeader.createHeader(StompHeader.Type.ENDPOINT, "endpoint", endpoint));
+ Message msg=new Message().putHeader(id, StompHeader.createHeader(StompHeader.Type.ENDPOINT, "endpoint", endpoint));
down_prot.down(new Event(Event.MSG, msg));
}
}
@@ -479,7 +478,7 @@ protected void handleFrame(Frame frame) {
headers.put("sender", session_id.toString());
}
- Message msg=new Message(null, null, frame.getBody());
+ Message msg=new Message(null, frame.getBody());
Header hdr=StompHeader.createHeader(StompHeader.Type.MESSAGE, headers);
msg.putHeader(id, hdr);
down_prot.down(new Event(Event.MSG, msg));
diff --git a/src/org/jgroups/protocols/TP.java b/src/org/jgroups/protocols/TP.java
index d1f2c75deb7..46ca3a7314b 100644
--- a/src/org/jgroups/protocols/TP.java
+++ b/src/org/jgroups/protocols/TP.java
@@ -53,7 +53,6 @@ public abstract class TP extends Protocol {
protected static final byte LIST=1; // we have a list of messages rather than a single message when set
protected static final byte MULTICAST=2; // message is a multicast (versus a unicast) message when set
- protected static final byte OOB=4; // message has OOB flag set (Message.OOB)
protected static final boolean can_bind_to_mcast_addr; // are we running on Linux ?
@@ -158,12 +157,12 @@ public abstract class TP extends Protocol {
@Property(name="oob_thread_pool.queue_enabled", description="Use queue to enqueue incoming OOB messages")
protected boolean oob_thread_pool_queue_enabled=true;
- @Property(name="oob_thread_pool.queue_max_size",description="Maximum queue size for incoming OOB messages. Default is 500")
+ @Property(name="oob_thread_pool.queue_max_size",description="Maximum queue size for incoming OOB messages")
protected int oob_thread_pool_queue_max_size=500;
@Property(name="oob_thread_pool.rejection_policy",
- description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run. Default is Discard")
- String oob_thread_pool_rejection_policy="discard";
+ description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run")
+ protected String oob_thread_pool_rejection_policy="discard";
protected int thread_pool_min_threads=2;
@@ -171,20 +170,46 @@ public abstract class TP extends Protocol {
protected long thread_pool_keep_alive_time=30000;
- @Property(name="thread_pool.enabled",description="Switch for enabling thread pool for regular messages. Default true")
+ @Property(name="thread_pool.enabled",description="Switch for enabling thread pool for regular messages")
protected boolean thread_pool_enabled=true;
- @Property(name="thread_pool.queue_enabled", description="Use queue to enqueue incoming regular messages. Default is true")
+ @Property(name="thread_pool.queue_enabled", description="Queue to enqueue incoming regular messages")
protected boolean thread_pool_queue_enabled=true;
- @Property(name="thread_pool.queue_max_size", description="Maximum queue size for incoming OOB messages. Default is 500")
+ @Property(name="thread_pool.queue_max_size", description="Maximum queue size for incoming OOB messages")
protected int thread_pool_queue_max_size=500;
@Property(name="thread_pool.rejection_policy",
description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run")
protected String thread_pool_rejection_policy="Discard";
+
+ @Property(name="internal_thread_pool.enabled",description="Switch for enabling thread pool for internal messages",
+ writable=false)
+ protected boolean internal_thread_pool_enabled=true;
+
+ @Property(name="internal_thread_pool.min_threads",description="Minimum thread pool size for the internal thread pool")
+ protected int internal_thread_pool_min_threads=2;
+
+ @Property(name="internal_thread_pool.max_threads",description="Maximum thread pool size for the internal thread pool")
+ protected int internal_thread_pool_max_threads=4;
+
+ @Property(name="internal_thread_pool.keep_alive_time", description="Timeout in ms to remove idle threads from the internal pool")
+ protected long internal_thread_pool_keep_alive_time=30000;
+
+ @Property(name="internal_thread_pool.queue_enabled", description="Queue to enqueue incoming internal messages")
+ protected boolean internal_thread_pool_queue_enabled=true;
+
+ @Property(name="internal_thread_pool.queue_max_size",description="Maximum queue size for incoming internal messages")
+ protected int internal_thread_pool_queue_max_size=500;
+
+ @Property(name="internal_thread_pool.rejection_policy",
+ description="Thread rejection policy. Possible values are Abort, Discard, DiscardOldest and Run")
+ protected String internal_thread_pool_rejection_policy="discard";
+
+
+
@Property(description="Type of timer to be used. Valid values are \"old\" (DefaultTimeScheduler, used up to 2.10), " +
"\"new\" or \"new2\" (TimeScheduler2), \"new3\" (TimeScheduler3) and \"wheel\". Note that this property " +
"might disappear in future releases, if one of the 3 timers is chosen as default timer")
@@ -443,10 +468,13 @@ public int getTimerQueueSize() {
protected String channel_name=null;
@ManagedAttribute(description="Number of OOB messages received")
- protected long num_oob_msgs_received=0;
+ protected long num_oob_msgs_received;
@ManagedAttribute(description="Number of regular messages received")
- protected long num_incoming_msgs_received=0;
+ protected long num_incoming_msgs_received;
+
+ @ManagedAttribute(description="Number of internal messages received")
+ protected long num_internal_msgs_received;
@ManagedAttribute(description="Class of the timer implementation")
public String getTimerClass() {
@@ -498,10 +526,10 @@ public void clearDifferentVersionCache() {
protected Executor oob_thread_pool;
/** Factory which is used by oob_thread_pool */
- protected ThreadFactory oob_thread_factory=null;
+ protected ThreadFactory oob_thread_factory;
/** Used if oob_thread_pool is a ThreadPoolExecutor and oob_thread_pool_queue_enabled is true */
- protected BlockingQueue<Runnable> oob_thread_pool_queue=null;
+ protected BlockingQueue<Runnable> oob_thread_pool_queue;
// ================================== Regular thread pool ======================
@@ -510,10 +538,18 @@ public void clearDifferentVersionCache() {
protected Executor thread_pool;
/** Factory which is used by oob_thread_pool */
- protected ThreadFactory default_thread_factory=null;
+ protected ThreadFactory default_thread_factory;
+
+ /** Used if thread_pool is a ThreadPoolExecutor and thread_pool_queue_enabled is true */
+ protected BlockingQueue<Runnable> thread_pool_queue;
+
+ // ================================== Internal thread pool ======================
+
+ /** The thread pool which handles JGroups internal messages (Flag.INTERNAL)*/
+ protected Executor internal_thread_pool;
/** Used if thread_pool is a ThreadPoolExecutor and thread_pool_queue_enabled is true */
- protected BlockingQueue<Runnable> thread_pool_queue=null;
+ protected BlockingQueue<Runnable> internal_thread_pool_queue;
// ================================== Timer thread pool =========================
protected TimeScheduler timer;
@@ -608,7 +644,7 @@ public String toString() {
public void resetStats() {
num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=0;
- num_oob_msgs_received=num_incoming_msgs_received=0;
+ num_oob_msgs_received=num_incoming_msgs_received=num_internal_msgs_received=0;
}
public void registerProbeHandler(DiagnosticsHandler.ProbeHandler handler) {
@@ -800,6 +836,26 @@ public int getRegularMaxQueueSize() {
return thread_pool_queue_max_size;
}
+
+ @ManagedAttribute(description="Current number of threads in the internal thread pool")
+ public int getInternalPoolSize() {
+ return internal_thread_pool instanceof ThreadPoolExecutor? ((ThreadPoolExecutor)internal_thread_pool).getPoolSize() : 0;
+ }
+
+ public long getInternalMessages() {
+ return num_internal_msgs_received;
+ }
+
+ @ManagedAttribute(description="Number of messages in the internal thread pool's queue")
+ public int getInternalQueueSize() {
+ return internal_thread_pool_queue != null? internal_thread_pool_queue.size() : 0;
+ }
+
+ public int getInternalMaxQueueSize() {
+ return internal_thread_pool_queue_max_size;
+ }
+
+
@ManagedAttribute(name="timer_tasks",description="Number of timer tasks queued up for execution")
public int getNumTimerTasks() {
return timer != null? timer.size() : -1;
@@ -939,6 +995,7 @@ else if(timer_type.equalsIgnoreCase("wheel")) {
Util.verifyRejectionPolicy(oob_thread_pool_rejection_policy);
Util.verifyRejectionPolicy(thread_pool_rejection_policy);
+ Util.verifyRejectionPolicy(internal_thread_pool_rejection_policy);
// ========================================== OOB thread pool ==============================
@@ -974,6 +1031,23 @@ else if(timer_type.equalsIgnoreCase("wheel")) {
}
}
+
+ // ========================================== Internal thread pool ==============================
+
+ if(internal_thread_pool == null
+ || (internal_thread_pool instanceof ThreadPoolExecutor && ((ThreadPoolExecutor)internal_thread_pool).isShutdown())) {
+ if(internal_thread_pool_enabled) {
+ if(internal_thread_pool_queue_enabled)
+ internal_thread_pool_queue=new LinkedBlockingQueue<Runnable>(internal_thread_pool_queue_max_size);
+ else
+ internal_thread_pool_queue=new SynchronousQueue<Runnable>();
+ internal_thread_pool=createThreadPool(internal_thread_pool_min_threads, internal_thread_pool_max_threads, internal_thread_pool_keep_alive_time,
+ internal_thread_pool_rejection_policy, internal_thread_pool_queue, oob_thread_factory);
+ }
+ // if the internal thread pool is disabled, we won't create it (not even a DirectExecutor)
+ }
+
+
Map<String, Object> m=new HashMap<String, Object>(2);
if(bind_addr != null)
m.put("bind_addr", bind_addr);
@@ -1019,6 +1093,9 @@ public void destroy() {
if(thread_pool instanceof ThreadPoolExecutor)
shutdownThreadPool(thread_pool);
+
+ if(internal_thread_pool instanceof ThreadPoolExecutor)
+ shutdownThreadPool(internal_thread_pool);
}
/**
@@ -1187,7 +1264,9 @@ public Object down(Event evt) {
final String cluster_name=hdr.channel_name;
// changed to fix http://jira.jboss.com/jira/browse/JGRP-506
- Executor pool=msg.isFlagSet(Message.OOB)? oob_thread_pool : thread_pool;
+ boolean internal=msg.isFlagSet(Message.Flag.INTERNAL);
+ Executor pool=internal && internal_thread_pool != null? internal_thread_pool
+ : internal || msg.isFlagSet(Message.Flag.OOB)? oob_thread_pool : thread_pool;
pool.execute(new Runnable() {
public void run() {
passMessageUp(copy, cluster_name, false, multicast, false);
@@ -1336,24 +1415,34 @@ protected void receive(Address sender, byte[] data, int offset, int length) {
if(is_message_list) { // used if message bundling is enabled
final MessageBatch[] batches=readMessageBatch(dis, multicast);
- final MessageBatch batch=batches[0], oob_batch=batches[1];
+ final MessageBatch batch=batches[0], oob_batch=batches[1], internal_batch=batches[2];
if(oob_batch != null) {
num_oob_msgs_received+=oob_batch.size();
oob_thread_pool.execute(new BatchHandler(oob_batch));
}
-
if(batch != null) {
num_incoming_msgs_received+=batch.size();
thread_pool.execute(new BatchHandler(batch));
}
+ if(internal_batch != null) {
+ num_internal_msgs_received+=internal_batch.size();
+ Executor pool=internal_thread_pool != null? internal_thread_pool : oob_thread_pool;
+ pool.execute(new BatchHandler(internal_batch));
+ }
}
else {
Message msg=readMessage(dis);
- boolean is_oob=msg.isFlagSet(Message.Flag.OOB);
- if(is_oob) num_oob_msgs_received++;
- else num_incoming_msgs_received++;
- Executor pool=is_oob? oob_thread_pool : thread_pool;
+ if(msg.isFlagSet(Message.Flag.INTERNAL))
+ num_internal_msgs_received++;
+ else if(msg.isFlagSet(Message.Flag.OOB))
+ num_oob_msgs_received++;
+ else
+ num_incoming_msgs_received++;
+
+ boolean internal=msg.isFlagSet(Message.Flag.INTERNAL); // use internal pool or OOB (if intrenal pool is null)
+ Executor pool=internal && internal_thread_pool != null? internal_thread_pool
+ : internal || msg.isFlagSet(Message.Flag.OOB)? oob_thread_pool : thread_pool;
TpHeader hdr=(TpHeader)msg.getHeader(id);
String cluster_name=hdr.channel_name;
pool.execute(new MyHandler(msg, cluster_name, multicast));
@@ -1442,7 +1531,7 @@ public void run() {
/** Serializes and sends a message. This method is not reentrant */
protected void send(Message msg, Address dest, boolean multicast) throws Exception {
// bundle all messages except when tagged with DONT_BUNDLE
- if(!msg.isFlagSet(Message.DONT_BUNDLE)) {
+ if(!msg.isFlagSet(Message.Flag.DONT_BUNDLE)) {
bundler.send(msg);
return;
}
@@ -1535,8 +1624,6 @@ protected static void writeMessage(Message msg, DataOutputStream dos, boolean mu
dos.writeShort(Version.version); // write the version
if(multicast)
flags+=MULTICAST;
- if(msg.isFlagSet(Message.OOB))
- flags+=OOB;
dos.writeByte(flags);
msg.writeTo(dos);
}
@@ -1617,13 +1704,14 @@ public static List<Message> readMessageList(DataInputStream in, short transport_
}
/**
- * Reads a list of messages into 2 MessageBatches: a regular one and an OOB one
+ * Reads a list of messages into 3 MessageBatches: a regular, an OOB and an internal one
* @param in
- * @return an array of 2 MessageBatches, the regular is at index 0 and the OOB at index 1 (either can be null)
+ * @return an array of 2 MessageBatches, the regular is at index 0 and the OOB at index 1
+ * and the internal at index 2 (either can be null)
* @throws Exception
*/
public static MessageBatch[] readMessageBatch(DataInputStream in, boolean multicast) throws Exception {
- MessageBatch[] mbs=new MessageBatch[2];
+ MessageBatch[] batches=new MessageBatch[3]; // [0]: reg, [1]: OOB, [2]: internal
Address dest=Util.readAddress(in);
Address src=Util.readAddress(in);
String cluster_name=Util.readString(in);
@@ -1635,18 +1723,23 @@ public static MessageBatch[] readMessageBatch(DataInputStream in, boolean multic
msg.setDest(dest);
if(msg.getSrc() == null)
msg.setSrc(src);
- if(msg.isFlagSet(Message.Flag.OOB)) {
- if(mbs[1] == null)
- mbs[1]=new MessageBatch(dest, src, cluster_name, multicast, MessageBatch.Mode.OOB, len);
- mbs[1].add(msg);
+ if(msg.isFlagSet(Message.Flag.INTERNAL)) {
+ if(batches[2] == null)
+ batches[2]=new MessageBatch(dest, src, cluster_name, multicast, MessageBatch.Mode.INTERNAL, len);
+ batches[2].add(msg);
+ }
+ else if(msg.isFlagSet(Message.Flag.OOB)) {
+ if(batches[1] == null)
+ batches[1]=new MessageBatch(dest, src, cluster_name, multicast, MessageBatch.Mode.OOB, len);
+ batches[1].add(msg);
}
else {
- if(mbs[0] == null)
- mbs[0]=new MessageBatch(dest, src, cluster_name, multicast, MessageBatch.Mode.REG, len);
- mbs[0].add(msg);
+ if(batches[0] == null)
+ batches[0]=new MessageBatch(dest, src, cluster_name, multicast, MessageBatch.Mode.REG, len);
+ batches[0].add(msg);
}
}
- return mbs;
+ return batches;
}
diff --git a/src/org/jgroups/protocols/UDP.java b/src/org/jgroups/protocols/UDP.java
index e774f95227d..3acaf17c217 100644
--- a/src/org/jgroups/protocols/UDP.java
+++ b/src/org/jgroups/protocols/UDP.java
@@ -603,12 +603,12 @@ protected void handleConfigEvent(Map<String,Object> map) {
if(map == null) return;
if(map.containsKey("send_buf_size")) {
- mcast_send_buf_size=((Integer)map.get("send_buf_size")).intValue();
+ mcast_send_buf_size=(Integer)map.get("send_buf_size");
ucast_send_buf_size=mcast_send_buf_size;
set_buffers=true;
}
if(map.containsKey("recv_buf_size")) {
- mcast_recv_buf_size=((Integer)map.get("recv_buf_size")).intValue();
+ mcast_recv_buf_size=(Integer)map.get("recv_buf_size");
ucast_recv_buf_size=mcast_recv_buf_size;
set_buffers=true;
}
diff --git a/src/org/jgroups/protocols/UNICAST.java b/src/org/jgroups/protocols/UNICAST.java
index 7832be5931d..f7632604e76 100644
--- a/src/org/jgroups/protocols/UNICAST.java
+++ b/src/org/jgroups/protocols/UNICAST.java
@@ -626,7 +626,7 @@ protected void handleDataReceived(Address sender, long seqno, short conn_id, bo
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && added) {
try {
up_prot.up(evt);
}
@@ -678,7 +678,7 @@ protected void handleBatchReceived(Address sender, Map<Short,List<Message>> map)
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && msg_added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && msg_added) {
try {
up_prot.up(new Event(Event.MSG, msg));
}
@@ -725,7 +725,7 @@ protected int removeAndDeliver(final AtomicBoolean processing, Table<Message> wi
MessageBatch batch=new MessageBatch(local_addr, sender, null, false, list);
for(Message msg_to_deliver: batch) {
// discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377)
- if(msg_to_deliver.isFlagSet(Message.OOB))
+ if(msg_to_deliver.isFlagSet(Message.Flag.OOB))
batch.remove(msg_to_deliver);
}
@@ -887,8 +887,8 @@ protected void stopRetransmitTask() {
protected void sendAck(Address dst, long seqno, short conn_id) {
if(!running) // if we are disconnected, then don't send any acks which throw exceptions on shutdown
return;
- Message ack=new Message(dst);
- ack.putHeader(this.id, UnicastHeader.createAckHeader(seqno, conn_id));
+ Message ack=new Message(dst).setFlag(Message.Flag.INTERNAL)
+ .putHeader(this.id, UnicastHeader.createAckHeader(seqno, conn_id));
if(log.isTraceEnabled())
log.trace(new StringBuilder().append(local_addr).append(" --> ACK(").append(dst).
append(": #").append(seqno).append(')'));
@@ -922,8 +922,7 @@ protected synchronized short getNewConnectionId() {
protected void sendRequestForFirstSeqno(Address dest, long seqno_received) {
- Message msg=new Message(dest);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(dest).setFlag(Message.Flag.OOB);
UnicastHeader hdr=UnicastHeader.createSendFirstSeqnoHeader(seqno_received);
msg.putHeader(this.id, hdr);
if(log.isTraceEnabled())
diff --git a/src/org/jgroups/protocols/UNICAST2.java b/src/org/jgroups/protocols/UNICAST2.java
index f4811605251..4397446e030 100644
--- a/src/org/jgroups/protocols/UNICAST2.java
+++ b/src/org/jgroups/protocols/UNICAST2.java
@@ -633,10 +633,9 @@ public void sendStableMessages() {
}
protected void sendStableMessage(Address dest, short conn_id, long hd, long hr) {
- Message stable_msg=new Message(dest, null, null);
- Unicast2Header hdr=Unicast2Header.createStableHeader(conn_id, hd, hr);
- stable_msg.putHeader(this.id, hdr);
- stable_msg.setFlag(Message.OOB);
+ Message stable_msg=new Message(dest).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id, Unicast2Header.createStableHeader(conn_id, hd, hr));
+
if(log.isTraceEnabled()) {
StringBuilder sb=new StringBuilder();
sb.append(local_addr).append(" --> STABLE(").append(dest).append(": ")
@@ -728,8 +727,8 @@ public void removeAllConnections() {
public void retransmit(SeqnoList missing, Address sender) {
Unicast2Header hdr=Unicast2Header.createXmitReqHeader();
- Message retransmit_msg=new Message(sender, null, missing);
- retransmit_msg.setFlag(Message.OOB);
+ Message retransmit_msg=new Message(sender, missing);
+ retransmit_msg.setFlag(Message.Flag.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ (" + missing + ") to " + sender);
retransmit_msg.putHeader(this.id, hdr);
@@ -786,7 +785,7 @@ protected boolean handleDataReceived(Address sender, long seqno, short conn_id,
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && added) {
try {
up_prot.up(evt);
}
@@ -830,7 +829,7 @@ protected void handleBatchReceived(Address sender, Map<Short,List<Message>> map)
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && msg_added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && msg_added) {
try {
up_prot.up(new Event(Event.MSG, msg));
}
@@ -899,7 +898,7 @@ protected void removeAndPassUp(Table<Message> win, Address sender) {
MessageBatch batch=new MessageBatch(local_addr, sender, null, false, msgs);
for(Message msg_to_deliver: batch) {
// discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377)
- if(msg_to_deliver.isFlagSet(Message.OOB))
+ if(msg_to_deliver.isFlagSet(Message.Flag.OOB))
batch.remove(msg_to_deliver);
}
@@ -919,20 +918,6 @@ protected void removeAndPassUp(Table<Message> win, Address sender) {
catch(Throwable t) {
log.error("failed to deliver batch " + batch, t);
}
-
-
-
- /*for(Message m: msgs) {
- // discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377)
- if(m.isFlagSet(Message.OOB))
- continue;
- try {
- up_prot.up(new Event(Event.MSG, m));
- }
- catch(Throwable t) {
- log.error("couldn't deliver message " + m, t);
- }
- }*/
}
}
finally {
@@ -1091,7 +1076,7 @@ protected synchronized short getNewConnectionId() {
protected void sendRequestForFirstSeqno(Address dest, long seqno_received) {
Message msg=new Message(dest);
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
Unicast2Header hdr=Unicast2Header.createSendFirstSeqnoHeader(seqno_received);
msg.putHeader(this.id, hdr);
if(log.isTraceEnabled())
@@ -1100,7 +1085,8 @@ protected void sendRequestForFirstSeqno(Address dest, long seqno_received) {
}
protected void sendAck(Address dest, long seqno, short conn_id) {
- Message msg=new Message(dest).setFlag(Message.OOB).putHeader(this.id, Unicast2Header.createAckHeader(seqno, conn_id));
+ Message msg=new Message(dest).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id, Unicast2Header.createAckHeader(seqno, conn_id));
if(log.isTraceEnabled())
log.trace(local_addr + " --> ACK(" + dest + "," + seqno + " [conn_id=" + conn_id + "])");
down_prot.down(new Event(Event.MSG, msg));
diff --git a/src/org/jgroups/protocols/UNICAST3.java b/src/org/jgroups/protocols/UNICAST3.java
index 6e62406c37c..30583a904b5 100644
--- a/src/org/jgroups/protocols/UNICAST3.java
+++ b/src/org/jgroups/protocols/UNICAST3.java
@@ -565,7 +565,7 @@ public void removeAllConnections() {
/** Sends a retransmit request to the given sender */
protected void retransmit(SeqnoList missing, Address sender) {
- Message xmit_msg=new Message(sender, missing).setFlag(Message.OOB).putHeader(id, Header.createXmitReqHeader());
+ Message xmit_msg=new Message(sender, missing).setFlag(Message.Flag.OOB).putHeader(id, Header.createXmitReqHeader());
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ (" + missing + ") to " + sender);
down_prot.down(new Event(Event.MSG, xmit_msg));
@@ -623,7 +623,7 @@ protected void handleDataReceived(Address sender, long seqno, short conn_id, bo
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && added) {
try {
up_prot.up(evt);
}
@@ -666,7 +666,7 @@ protected void handleBatchReceived(Address sender, Map<Short,List<Message>> map)
// An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering !
// http://jira.jboss.com/jira/browse/JGRP-377
- if(msg.isFlagSet(Message.OOB) && msg_added) {
+ if(msg.isFlagSet(Message.Flag.OOB) && msg_added) {
try {
up_prot.up(new Event(Event.MSG, msg));
}
@@ -719,7 +719,7 @@ protected int removeAndDeliver(final AtomicBoolean processing, Table<Message> wi
MessageBatch batch=new MessageBatch(local_addr, sender, null, false, list);
for(Message msg_to_deliver: batch) {
// discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377)
- if(msg_to_deliver.isFlagSet(Message.OOB))
+ if(msg_to_deliver.isFlagSet(Message.Flag.OOB))
batch.remove(msg_to_deliver);
}
if(batch.isEmpty())
@@ -933,7 +933,7 @@ protected void stopRetransmitTask() {
protected void sendAck(Address dst, long seqno, short conn_id) {
if(!running) // if we are disconnected, then don't send any acks which throw exceptions on shutdown
return;
- Message ack=new Message(dst).putHeader(this.id, Header.createAckHeader(seqno, conn_id));
+ Message ack=new Message(dst).setFlag(Message.Flag.INTERNAL).putHeader(this.id, Header.createAckHeader(seqno, conn_id));
if(log.isTraceEnabled())
log.trace(new StringBuilder().append(local_addr).append(" --> ACK(").append(dst).
append(": #").append(seqno).append(')'));
@@ -967,10 +967,9 @@ protected synchronized short getNewConnectionId() {
protected void sendRequestForFirstSeqno(Address dest, long seqno_received) {
- Message msg=new Message(dest);
- msg.setFlag(Message.OOB);
- Header hdr=Header.createSendFirstSeqnoHeader(seqno_received);
- msg.putHeader(this.id, hdr);
+ Message msg=new Message(dest).setFlag(Message.Flag.OOB)
+ .putHeader(this.id, Header.createSendFirstSeqnoHeader(seqno_received));
+
if(log.isTraceEnabled())
log.trace(local_addr + " --> SEND_FIRST_SEQNO(" + dest + "," + seqno_received + ")");
down_prot.down(new Event(Event.MSG, msg));
diff --git a/src/org/jgroups/protocols/VERIFY_SUSPECT.java b/src/org/jgroups/protocols/VERIFY_SUSPECT.java
index aa46f9c2009..d7653b515b8 100644
--- a/src/org/jgroups/protocols/VERIFY_SUSPECT.java
+++ b/src/org/jgroups/protocols/VERIFY_SUSPECT.java
@@ -121,7 +121,7 @@ public Object up(Event evt) {
Message rsp;
Address target=use_mcast_rsps? null : hdr.from;
for(int i=0; i < num_msgs; i++) {
- rsp=new Message(target).setFlag(Message.OOB)
+ rsp=new Message(target).setFlag(Message.Flag.INTERNAL)
.putHeader(this.id, new VerifyHeader(VerifyHeader.I_AM_NOT_DEAD, local_addr));
down_prot.down(new Event(Event.MSG, rsp));
}
@@ -201,9 +201,8 @@ void verifySuspect(Address mbr) {
if(log.isTraceEnabled()) log.trace("verifying that " + mbr + " is dead");
for(int i=0; i < num_msgs; i++) {
- msg=new Message(mbr, null, null);
- msg.setFlag(Message.OOB);
- msg.putHeader(this.id, new VerifyHeader(VerifyHeader.ARE_YOU_DEAD, local_addr));
+ msg=new Message(mbr).setFlag(Message.Flag.INTERNAL)
+ .putHeader(this.id, new VerifyHeader(VerifyHeader.ARE_YOU_DEAD, local_addr));
down_prot.down(new Event(Event.MSG, msg));
}
}
diff --git a/src/org/jgroups/protocols/pbcast/ClientGmsImpl.java b/src/org/jgroups/protocols/pbcast/ClientGmsImpl.java
index 7215cef9fed..630cac7f338 100644
--- a/src/org/jgroups/protocols/pbcast/ClientGmsImpl.java
+++ b/src/org/jgroups/protocols/pbcast/ClientGmsImpl.java
@@ -186,7 +186,7 @@ private void joinInternal(Address mbr, boolean joinWithStateTransfer,boolean use
}
// send VIEW_ACK to sender of view
- Message view_ack=new Message(coord).setFlag(Message.OOB)
+ Message view_ack=new Message(coord).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
.putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.VIEW_ACK));
gms.getDownProtocol().down(new Event(Event.MSG, view_ack));
return;
@@ -250,8 +250,7 @@ void sendJoinMessage(Address coord, Address mbr,boolean joinWithTransfer, boolea
Message msg;
GMS.GmsHeader hdr;
- msg=new Message(coord, null, null);
- msg.setFlag(Message.OOB);
+ msg=new Message(coord).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL);
if(joinWithTransfer)
hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER, mbr,useFlushIfPresent);
else
diff --git a/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java b/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java
index f97cf2e5807..4f89da12898 100644
--- a/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java
+++ b/src/org/jgroups/protocols/pbcast/CoordGmsImpl.java
@@ -261,10 +261,8 @@ public void stop() {
private void sendLeaveResponses(Collection<Address> leaving_members) {
for(Address address: leaving_members){
- Message msg=new Message(address, null, null); // send an ack to the leaving member
- msg.setFlag(Message.OOB);
- GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.LEAVE_RSP);
- msg.putHeader(gms.getId(), hdr);
+ Message msg=new Message(address).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.LEAVE_RSP));
gms.getDownProtocol().down(new Event(Event.MSG, msg));
}
}
diff --git a/src/org/jgroups/protocols/pbcast/FLUSH.java b/src/org/jgroups/protocols/pbcast/FLUSH.java
index 53de1c97d6f..b6711e7b9da 100644
--- a/src/org/jgroups/protocols/pbcast/FLUSH.java
+++ b/src/org/jgroups/protocols/pbcast/FLUSH.java
@@ -548,9 +548,8 @@ private void handleFlushReconcile(Message msg, FlushHeader fh) {
log.debug(localAddress + ": returned from FLUSH_RECONCILE, "
+ " sending RECONCILE_OK to " + requester);
- Message reconcileOk = new Message(requester);
- reconcileOk.setFlag(Message.OOB);
- reconcileOk.putHeader(this.id, new FlushHeader(FlushHeader.FLUSH_RECONCILE_OK));
+ Message reconcileOk = new Message(requester).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id,new FlushHeader(FlushHeader.FLUSH_RECONCILE_OK));
down_prot.down(new Event(Event.MSG, reconcileOk));
}
@@ -564,10 +563,8 @@ private void handleStartFlush(Message msg, FlushHeader fh) {
}
onStartFlush(flushRequester, fh);
} else {
- FlushHeader fhr = new FlushHeader(FlushHeader.FLUSH_NOT_COMPLETED, fh.viewID,
- fh.flushParticipants);
- Message response = new Message(flushRequester);
- response.putHeader(this.id, fhr);
+ FlushHeader fhr = new FlushHeader(FlushHeader.FLUSH_NOT_COMPLETED, fh.viewID, fh.flushParticipants);
+ Message response = new Message(flushRequester).putHeader(this.id, fhr);
down_prot.down(new Event(Event.MSG, response));
if (log.isDebugEnabled())
log.debug(localAddress + ": received START_FLUSH, responded with FLUSH_NOT_COMPLETED to " + flushRequester);
@@ -580,9 +577,8 @@ private void rejectFlush(Collection<? extends Address> participants, long viewId
for (Address flushMember : participants) {
if(flushMember == null)
continue;
- Message reject = new Message(flushMember, localAddress, null);
- reject.setFlag(Message.OOB);
- reject.putHeader(this.id, new FlushHeader(FlushHeader.ABORT_FLUSH, viewId,participants));
+ Message reject = new Message(flushMember, localAddress, null).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id, new FlushHeader(FlushHeader.ABORT_FLUSH, viewId,participants));
down_prot.down(new Event(Event.MSG, reject));
}
}
@@ -693,9 +689,8 @@ private void onSuspend(final List<Address> members) {
flushMembers.addAll(participantsInFlush);
flushMembers.removeAll(suspected);
- msg = new Message(null, localAddress, null);
- msg.putHeader(this.id, new FlushHeader(FlushHeader.START_FLUSH, currentViewId(),
- participantsInFlush));
+ msg = new Message(null, localAddress, null)
+ .putHeader(this.id, new FlushHeader(FlushHeader.START_FLUSH, currentViewId(), participantsInFlush));
}
if (participantsInFlush.isEmpty()) {
flush_promise.setResult(SUCCESS_START_FLUSH);
@@ -778,8 +773,7 @@ private void onStartFlush(Address flushStarter, FlushHeader fh) {
FlushHeader fhr = new FlushHeader(FlushHeader.FLUSH_COMPLETED, fh.viewID,fh.flushParticipants);
fhr.addDigest(digest);
- Message msg = new Message(flushStarter);
- msg.putHeader(this.id, fhr);
+ Message msg = new Message(flushStarter).putHeader(this.id, fhr);
down_prot.down(new Event(Event.MSG, msg));
if (log.isDebugEnabled())
log.debug(localAddress + ": received START_FLUSH, responded with FLUSH_COMPLETED to " + flushStarter);
@@ -807,8 +801,7 @@ private void onFlushCompleted(Address address, final FlushHeader header) {
needsReconciliationPhase = enable_reconciliation && flushCompleted && hasVirtualSynchronyGaps();
if (needsReconciliationPhase) {
Digest d = findHighestSequences();
- msg = new Message();
- msg.setFlag(Message.OOB);
+ msg = new Message().setFlag(Message.Flag.OOB);
FlushHeader fh = new FlushHeader(FlushHeader.FLUSH_RECONCILE, currentViewId(),flushMembers);
reconcileOks.clear();
fh.addDigest(d);
diff --git a/src/org/jgroups/protocols/pbcast/GMS.java b/src/org/jgroups/protocols/pbcast/GMS.java
index 729dce91927..e800a2aec49 100644
--- a/src/org/jgroups/protocols/pbcast/GMS.java
+++ b/src/org/jgroups/protocols/pbcast/GMS.java
@@ -545,9 +545,7 @@ public void castViewChange(View new_view, Digest digest, JoinRsp jr, Collection<
}
public void sendJoinResponse(JoinRsp rsp, Address dest) {
- Message m=new Message(dest, null, null);
- GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.JOIN_RSP, rsp);
- m.putHeader(this.id, hdr);
+ Message m=new Message(dest).putHeader(this.id, new GMS.GmsHeader(GMS.GmsHeader.JOIN_RSP, rsp));
getDownProtocol().down(new Event(Event.MSG, m));
}
@@ -857,9 +855,8 @@ public Object up(Event evt) {
if(digest != null) {
GmsHeader rsp_hdr=new GmsHeader(GmsHeader.GET_DIGEST_RSP);
rsp_hdr.my_digest=digest;
- Message get_digest_rsp=new Message(msg.getSrc(), null, null);
- get_digest_rsp.setFlag(Message.OOB);
- get_digest_rsp.putHeader(this.id, rsp_hdr);
+ Message get_digest_rsp=new Message(msg.getSrc()).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id,rsp_hdr);
down_prot.down(new Event(Event.MSG, get_digest_rsp));
}
break;
@@ -984,10 +981,8 @@ final void initState() {
private void sendViewAck(Address dest) {
- Message view_ack=new Message(dest, null, null);
- view_ack.setFlag(Message.OOB);
- GmsHeader tmphdr=new GmsHeader(GmsHeader.VIEW_ACK);
- view_ack.putHeader(this.id, tmphdr);
+ Message view_ack=new Message(dest).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .putHeader(this.id, new GmsHeader(GmsHeader.VIEW_ACK));
down_prot.down(new Event(Event.MSG,view_ack));
}
diff --git a/src/org/jgroups/protocols/pbcast/GmsImpl.java b/src/org/jgroups/protocols/pbcast/GmsImpl.java
index 1fdc6498004..3a78b493e4b 100644
--- a/src/org/jgroups/protocols/pbcast/GmsImpl.java
+++ b/src/org/jgroups/protocols/pbcast/GmsImpl.java
@@ -55,7 +55,7 @@ public void handleViewChange(View new_view, Digest digest)
protected void sendMergeRejectedResponse(Address sender, MergeId merge_id) {
Message msg=new Message(sender, null, null);
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.merge_rejected=true;
hdr.merge_id=merge_id;
diff --git a/src/org/jgroups/protocols/pbcast/Merger.java b/src/org/jgroups/protocols/pbcast/Merger.java
index 5ea4f2e6e80..571b08c935f 100644
--- a/src/org/jgroups/protocols/pbcast/Merger.java
+++ b/src/org/jgroups/protocols/pbcast/Merger.java
@@ -180,8 +180,7 @@ public void handleMergeView(final MergeData data, final MergeId merge_id) {
gms.castViewChange(data.view,data.digest,null,newViewMembers);
// if we have flush in stack send ack back to merge coordinator
if(gms.flushProtocolInStack) { //[JGRP-700] - FLUSH: flushing should span merge
- Message ack=new Message(data.getSender(), null, null);
- ack.setFlag(Message.OOB);
+ Message ack=new Message(data.getSender()).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL);
GMS.GmsHeader ack_hdr=new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW_OK);
ack.putHeader(gms.getId(), ack_hdr);
gms.getDownProtocol().down(new Event(Event.MSG, ack));
@@ -254,8 +253,7 @@ public static void sanitizeViews(Map<Address,View> map) {
/** Send back a response containing view and digest to sender */
private void sendMergeResponse(Address sender, View view, Digest digest, MergeId merge_id) {
- Message msg=new Message(sender, null, null);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(sender).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.merge_id=merge_id;
hdr.view=view;
@@ -291,7 +289,7 @@ private void sendMergeView(Collection<Address> coords, MergeData combined_merge_
long start=System.currentTimeMillis();
for(Address coord: coords) {
- Message msg=new Message(coord, null, null);
+ Message msg=new Message(coord);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW);
hdr.view=view;
hdr.my_digest=digest;
@@ -318,8 +316,7 @@ private void sendMergeView(Collection<Address> coords, MergeData combined_merge_
}
protected void sendMergeRejectedResponse(Address sender, MergeId merge_id) {
- Message msg=new Message(sender, null, null);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(sender).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_RSP);
hdr.merge_rejected=true;
hdr.merge_id=merge_id;
@@ -332,8 +329,8 @@ private void sendMergeCancelledMessage(Collection<Address> coords, MergeId merge
return;
for(Address coord: coords) {
- Message msg=new Message(coord, null, null);
- // msg.setFlag(Message.OOB);
+ Message msg=new Message(coord);
+ // msg.setFlag(Message.Flag.OOB);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.CANCEL_MERGE);
hdr.merge_id=merge_id;
msg.putHeader(gms.getId(), hdr);
@@ -356,9 +353,7 @@ private Digest fetchDigestsFromAllMembersInSubPartition(List<Address> current_mb
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.GET_DIGEST_REQ);
hdr.merge_id=merge_id;
- Message get_digest_req=new Message();
- get_digest_req.setFlag(Message.OOB);
- get_digest_req.putHeader(gms.getId(), hdr);
+ Message get_digest_req=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL).putHeader(gms.getId(), hdr);
long max_wait_time=gms.merge_timeout / 2; // gms.merge_timeout is guaranteed to be > 0, verified in init()
digest_collector.reset(current_mbrs);
@@ -681,8 +676,7 @@ protected boolean getMergeDataFromSubgroupCoordinators(Map<Address,Collection<Ad
for(Map.Entry<Address,Collection<Address>> entry: coords.entrySet()) {
Address coord=entry.getKey();
Collection<Address> mbrs=entry.getValue();
- Message msg=new Message(coord, null, null);
- msg.setFlag(Message.OOB);
+ Message msg=new Message(coord).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL);
GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.MERGE_REQ, mbrs);
hdr.mbr=gms.local_addr;
hdr.merge_id=new_merge_id;
diff --git a/src/org/jgroups/protocols/pbcast/NAKACK.java b/src/org/jgroups/protocols/pbcast/NAKACK.java
index f7983924e05..c07f47d644c 100644
--- a/src/org/jgroups/protocols/pbcast/NAKACK.java
+++ b/src/org/jgroups/protocols/pbcast/NAKACK.java
@@ -581,7 +581,7 @@ public Object up(Event evt) {
case Event.MSG:
Message msg=(Message)evt.getArg();
- if(msg.isFlagSet(Message.NO_RELIABILITY))
+ if(msg.isFlagSet(Message.Flag.NO_RELIABILITY))
break;
NakAckHeader hdr=(NakAckHeader)msg.getHeader(this.id);
if(hdr == null)
@@ -740,10 +740,10 @@ private void handleMessage(Message msg, NakAckHeader hdr) {
// OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379
- if(added && msg.isFlagSet(Message.OOB)) {
+ if(added && msg.isFlagSet(Message.Flag.OOB)) {
if(loopback)
msg=win.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win !
- if(msg != null && msg.isFlagSet(Message.OOB)) {
+ if(msg != null && msg.isFlagSet(Message.Flag.OOB)) {
if(msg.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) {
if(log.isTraceEnabled())
log.trace(new StringBuilder().append(local_addr).append(": delivering ").append(sender).append('#').append(hdr.seqno));
@@ -781,7 +781,7 @@ private void handleMessage(Message msg, NakAckHeader hdr) {
for(final Message msg_to_deliver: msgs) {
// discard OOB msg if it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-379)
- if(msg_to_deliver.isFlagSet(Message.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.OOB_DELIVERED))
+ if(msg_to_deliver.isFlagSet(Message.Flag.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.OOB_DELIVERED))
continue;
//msg_to_deliver.removeHeader(getName()); // Changed by bela Jan 29 2003: not needed (see above)
@@ -1313,8 +1313,6 @@ public void retransmit(long first_seqno, long last_seqno, Address sender) {
protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) {
- NakAckHeader hdr;
- Message retransmit_msg;
Address dest=sender; // to whom do we send the XMIT request ?
if(multicast_xmit_request || this.use_mcast_xmit_req) {
@@ -1331,9 +1329,8 @@ protected void retransmit(long first_seqno, long last_seqno, final Address sende
}
}
- hdr=NakAckHeader.createXmitRequestHeader(first_seqno, last_seqno, sender);
- retransmit_msg=new Message(dest, null, null);
- retransmit_msg.setFlag(Message.OOB);
+ NakAckHeader hdr=NakAckHeader.createXmitRequestHeader(first_seqno, last_seqno, sender);
+ Message retransmit_msg=new Message(dest).setFlag(Message.Flag.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ ([" + first_seqno + ", " + last_seqno + "]) to " + dest);
retransmit_msg.putHeader(this.id, hdr);
diff --git a/src/org/jgroups/protocols/pbcast/NAKACK2.java b/src/org/jgroups/protocols/pbcast/NAKACK2.java
index caa53b94248..ff415e03402 100644
--- a/src/org/jgroups/protocols/pbcast/NAKACK2.java
+++ b/src/org/jgroups/protocols/pbcast/NAKACK2.java
@@ -777,10 +777,10 @@ protected void handleMessage(Message msg, NakAckHeader2 hdr) {
// OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379
- if(added && msg.isFlagSet(Message.OOB)) {
+ if(added && msg.isFlagSet(Message.Flag.OOB)) {
if(loopback)
msg=buf.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win !
- if(msg != null && msg.isFlagSet(Message.OOB)) {
+ if(msg != null && msg.isFlagSet(Message.Flag.OOB)) {
if(msg.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) {
if(log.isTraceEnabled())
log.trace(new StringBuilder().append(local_addr).append(": delivering ").append(sender).append('#').append(hdr.seqno));
@@ -828,7 +828,7 @@ protected void handleMessages(Address sender, List<Tuple<Long,Message>> msgs, bo
for(Tuple<Long,Message> tuple: msgs) {
long seq=tuple.getVal1();
Message msg=loopback? buf.get(seq) : tuple.getVal2(); // we *have* to get the message, because loopback means we didn't add it to win !
- if(msg != null && msg.isFlagSet(Message.OOB)) {
+ if(msg != null && msg.isFlagSet(Message.Flag.OOB)) {
if(msg.setTransientFlagIfAbsent(Message.OOB_DELIVERED)) {
if(log.isTraceEnabled())
log.trace(new StringBuilder().append(local_addr).append(": delivering ")
@@ -872,7 +872,7 @@ protected void removeAndPassUp(Table<Message> buf, Address sender, boolean loopb
MessageBatch batch=new MessageBatch(null, sender, cluster_name, true, msgs);
for(Message msg_to_deliver: batch) {
// discard OOB msg if it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-379)
- if(msg_to_deliver.isFlagSet(Message.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.OOB_DELIVERED))
+ if(msg_to_deliver.isFlagSet(Message.Flag.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED))
batch.remove(msg_to_deliver);
}
if(batch.isEmpty())
@@ -1406,7 +1406,7 @@ protected void retransmit(SeqnoList missing_msgs, final Address sender, boolean
NakAckHeader2 hdr=NakAckHeader2.createXmitRequestHeader(sender);
Message retransmit_msg=new Message(dest, null, missing_msgs);
- retransmit_msg.setFlag(Message.OOB);
+ retransmit_msg.setFlag(Message.Flag.OOB);
if(log.isTraceEnabled())
log.trace(local_addr + ": sending XMIT_REQ (" + missing_msgs + ") to " + dest);
retransmit_msg.putHeader(this.id, hdr);
diff --git a/src/org/jgroups/protocols/pbcast/ParticipantGmsImpl.java b/src/org/jgroups/protocols/pbcast/ParticipantGmsImpl.java
index c33177554e4..eac2d14cced 100644
--- a/src/org/jgroups/protocols/pbcast/ParticipantGmsImpl.java
+++ b/src/org/jgroups/protocols/pbcast/ParticipantGmsImpl.java
@@ -172,11 +172,8 @@ boolean wouldIBeCoordinator() {
void sendLeaveMessage(Address coord, Address mbr) {
- Message msg=new Message(coord, null, null);
- msg.setFlag(Message.OOB);
- GMS.GmsHeader hdr=new GMS.GmsHeader(GMS.GmsHeader.LEAVE_REQ, mbr);
-
- msg.putHeader(gms.getId(), hdr);
+ Message msg=new Message(coord).setFlag(Message.Flag.OOB)
+ .putHeader(gms.getId(), new GMS.GmsHeader(GMS.GmsHeader.LEAVE_REQ, mbr));
gms.getDownProtocol().down(new Event(Event.MSG, msg));
}
diff --git a/src/org/jgroups/protocols/pbcast/STABLE.java b/src/org/jgroups/protocols/pbcast/STABLE.java
index ad15f6160d6..ff21d42e26e 100644
--- a/src/org/jgroups/protocols/pbcast/STABLE.java
+++ b/src/org/jgroups/protocols/pbcast/STABLE.java
@@ -690,10 +690,8 @@ protected void sendStableMessage(Digest d) {
if(log.isTraceEnabled())
log.trace(local_addr + ": sending stable msg " + d.printHighestDeliveredSeqnos());
num_stable_msgs_sent++;
- final Message msg=new Message(); // mcast message
- msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
- StableHeader hdr=new StableHeader(StableHeader.STABLE_GOSSIP, d);
- msg.putHeader(this.id, hdr);
+ final Message msg=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY)
+ .putHeader(this.id,new StableHeader(StableHeader.STABLE_GOSSIP,d));
Runnable r=new Runnable() {
public void run() {
@@ -877,8 +875,7 @@ public void run() {
}
if(stability_digest != null) {
- Message msg=new Message();
- msg.setFlag(Message.OOB, Message.Flag.NO_RELIABILITY);
+ Message msg=new Message().setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.NO_RELIABILITY);
StableHeader hdr=new StableHeader(StableHeader.STABILITY, stability_digest);
msg.putHeader(id, hdr);
if(log.isTraceEnabled()) log.trace(local_addr + ": sending stability msg " + stability_digest.printHighestDeliveredSeqnos());
diff --git a/src/org/jgroups/protocols/pbcast/STATE.java b/src/org/jgroups/protocols/pbcast/STATE.java
index e048dd9ef97..4a895fd2426 100644
--- a/src/org/jgroups/protocols/pbcast/STATE.java
+++ b/src/org/jgroups/protocols/pbcast/STATE.java
@@ -147,8 +147,7 @@ public void write(int b) throws IOException {
protected void sendMessage(byte[] b, int off, int len) throws IOException {
- Message m=new Message(stateRequester);
- m.putHeader(id, new StateHeader(StateHeader.STATE_PART));
+ Message m=new Message(stateRequester).putHeader(id, new StateHeader(StateHeader.STATE_PART));
// we're copying the buffer passed from the state provider here: if a BufferedOutputStream is used, the
// buffer (b) will always be the same and can be modified after it has been set in the message !
diff --git a/src/org/jgroups/protocols/pbcast/STATE_TRANSFER.java b/src/org/jgroups/protocols/pbcast/STATE_TRANSFER.java
index dd25d1958e7..88042a83af8 100644
--- a/src/org/jgroups/protocols/pbcast/STATE_TRANSFER.java
+++ b/src/org/jgroups/protocols/pbcast/STATE_TRANSFER.java
@@ -207,8 +207,7 @@ public Object down(Event evt) {
up_prot.up(new Event(Event.GET_STATE_OK, new StateTransferInfo()));
}
else {
- Message state_req=new Message(target, null, null);
- state_req.putHeader(this.id, new StateHeader(StateHeader.STATE_REQ));
+ Message state_req=new Message(target).putHeader(this.id, new StateHeader(StateHeader.STATE_REQ));
if(log.isDebugEnabled())
log.debug(local_addr + ": asking " + target + " for state");
@@ -349,8 +348,7 @@ protected void getStateFromApplication(Address requester, Digest digest) {
avg_state_size=num_bytes_sent.doubleValue() / num_state_reqs.doubleValue();
}
- Message state_rsp=new Message(requester, null, state);
- state_rsp.putHeader(this.id, new StateHeader(StateHeader.STATE_RSP, digest));
+ Message state_rsp=new Message(requester, state).putHeader(this.id, new StateHeader(StateHeader.STATE_RSP, digest));
if(log.isTraceEnabled()) {
int length=state != null? state.length : 0;
if(log.isTraceEnabled())
@@ -362,8 +360,7 @@ protected void getStateFromApplication(Address requester, Digest digest) {
protected void sendException(Address requester, Throwable exception) {
try {
- Message ex_msg=new Message(requester, null, exception);
- ex_msg.putHeader(getId(), new StateHeader(StateHeader.STATE_EX));
+ Message ex_msg=new Message(requester, exception).putHeader(getId(), new StateHeader(StateHeader.STATE_EX));
down(new Event(Event.MSG, ex_msg));
}
catch(Throwable t) {
diff --git a/src/org/jgroups/protocols/pbcast/StreamingStateTransfer.java b/src/org/jgroups/protocols/pbcast/StreamingStateTransfer.java
index d164dfbd384..c3b24a1a286 100644
--- a/src/org/jgroups/protocols/pbcast/StreamingStateTransfer.java
+++ b/src/org/jgroups/protocols/pbcast/StreamingStateTransfer.java
@@ -191,8 +191,7 @@ public Object down(Event evt) {
}
else {
state_provider=target;
- Message state_req=new Message(target, null, null);
- state_req.putHeader(this.id, new StateHeader(StateHeader.STATE_REQ));
+ Message state_req=new Message(target).putHeader(this.id, new StateHeader(StateHeader.STATE_REQ));
if(log.isDebugEnabled())
log.debug(local_addr + ": asking " + target + " for state");
down_prot.down(new Event(Event.MSG, state_req));
@@ -376,8 +375,7 @@ public void openBarrierAndResumeStable() {
protected void sendEof(Address requester) {
try {
- Message eof_msg=new Message(requester);
- eof_msg.putHeader(getId(), new StateHeader(StateHeader.STATE_EOF));
+ Message eof_msg=new Message(requester).putHeader(getId(), new StateHeader(StateHeader.STATE_EOF));
if(log.isTraceEnabled())
log.trace(local_addr + " --> EOF --> " + requester);
down(new Event(Event.MSG, eof_msg));
@@ -389,8 +387,7 @@ protected void sendEof(Address requester) {
protected void sendException(Address requester, Throwable exception) {
try {
- Message ex_msg=new Message(requester, null, exception);
- ex_msg.putHeader(getId(), new StateHeader(StateHeader.STATE_EX));
+ Message ex_msg=new Message(requester, null, exception).putHeader(getId(), new StateHeader(StateHeader.STATE_EX));
down(new Event(Event.MSG, ex_msg));
}
catch(Throwable t) {
diff --git a/src/org/jgroups/protocols/relay/RELAY2.java b/src/org/jgroups/protocols/relay/RELAY2.java
index 3b8efea5f7c..07b6b185f4b 100644
--- a/src/org/jgroups/protocols/relay/RELAY2.java
+++ b/src/org/jgroups/protocols/relay/RELAY2.java
@@ -551,10 +551,9 @@ protected void sendToBridges(Address sender, final Message msg, short ... exclud
* @param target_site
*/
protected void sendSiteUnreachableTo(Address dest, short target_site) {
- Message msg=new Message(dest).setFlag(Message.Flag.OOB);
- msg.setSrc(new SiteUUID((UUID)local_addr, UUID.get(local_addr), site_id));
- Relay2Header hdr=new Relay2Header(Relay2Header.SITE_UNREACHABLE, new SiteMaster(target_site), null);
- msg.putHeader(id, hdr);
+ Message msg=new Message(dest).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL)
+ .src(new SiteUUID((UUID)local_addr, UUID.get(local_addr), site_id))
+ .putHeader(id, new Relay2Header(Relay2Header.SITE_UNREACHABLE, new SiteMaster(target_site), null));
down_prot.down(new Event(Event.MSG, msg));
}
diff --git a/src/org/jgroups/protocols/tom/TOA.java b/src/org/jgroups/protocols/tom/TOA.java
index 50c76917633..35f39ac7f0c 100644
--- a/src/org/jgroups/protocols/tom/TOA.java
+++ b/src/org/jgroups/protocols/tom/TOA.java
@@ -152,16 +152,10 @@ private void handleViewChange(View view) {
for (MessageID messageID : pendingSentMessages) {
long finalSequenceNumber = senderManager.removeLeavers(messageID, leavers);
if (finalSequenceNumber != SenderManager.NOT_READY) {
- Message finalMessage = new Message();
- finalMessage.setSrc(localAddress);
-
- ToaHeader finalHeader = ToaHeader.createNewHeader(
- ToaHeader.FINAL_MESSAGE,messageID);
-
+ ToaHeader finalHeader = ToaHeader.createNewHeader(ToaHeader.FINAL_MESSAGE,messageID);
finalHeader.setSequencerNumber(finalSequenceNumber);
- finalMessage.putHeader(this.id, finalHeader);
- finalMessage.setFlag(Message.Flag.OOB);
- finalMessage.setFlag(Message.Flag.DONT_BUNDLE);
+ Message finalMessage = new Message().src(localAddress).putHeader(this.id,finalHeader)
+ .setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE);
Set<Address> destinations = senderManager.getDestination(messageID);
if (destinations.contains(localAddress)) {
@@ -293,17 +287,11 @@ private void handleDataMessage(Message message, ToaHeader header) {
}
//create a new message and send it back
- Message proposeMessage = new Message();
- proposeMessage.setSrc(localAddress);
- proposeMessage.setDest(messageID.getAddress());
-
- ToaHeader newHeader = ToaHeader.createNewHeader(
- ToaHeader.PROPOSE_MESSAGE,messageID);
-
+ ToaHeader newHeader = ToaHeader.createNewHeader(ToaHeader.PROPOSE_MESSAGE,messageID);
newHeader.setSequencerNumber(myProposeSequenceNumber);
- proposeMessage.putHeader(this.id, newHeader);
- proposeMessage.setFlag(Message.Flag.OOB);
- proposeMessage.setFlag(Message.Flag.DONT_BUNDLE);
+
+ Message proposeMessage = new Message().src(localAddress).dest(messageID.getAddress())
+ .putHeader(this.id, newHeader).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE);
//multicastSenderThread.addUnicastMessage(proposeMessage);
down_prot.down(new Event(Event.MSG, proposeMessage));
@@ -334,16 +322,12 @@ private void handleSequenceNumberPropose(Address from, ToaHeader header) {
if (finalSequenceNumber != SenderManager.NOT_READY) {
lastProposeReceived = true;
- Message finalMessage = new Message();
- finalMessage.setSrc(localAddress);
-
- ToaHeader finalHeader = ToaHeader.createNewHeader(
- ToaHeader.FINAL_MESSAGE,messageID);
+ ToaHeader finalHeader = ToaHeader.createNewHeader(ToaHeader.FINAL_MESSAGE,messageID);
finalHeader.setSequencerNumber(finalSequenceNumber);
- finalMessage.putHeader(this.id, finalHeader);
- finalMessage.setFlag(Message.Flag.OOB);
- finalMessage.setFlag(Message.Flag.DONT_BUNDLE);
+
+ Message finalMessage = new Message().src(localAddress).putHeader(this.id, finalHeader)
+ .setFlag(Message.Flag.OOB, Message.Flag.INTERNAL, Message.Flag.DONT_BUNDLE);
Set<Address> destinations = senderManager.getDestination(messageID);
if (destinations.contains(localAddress)) {
diff --git a/src/org/jgroups/util/MessageBatch.java b/src/org/jgroups/util/MessageBatch.java
index 87fce18af02..89f878c2bff 100644
--- a/src/org/jgroups/util/MessageBatch.java
+++ b/src/org/jgroups/util/MessageBatch.java
@@ -45,15 +45,24 @@ public MessageBatch(int capacity) {
public MessageBatch(Collection<Message> msgs) {
messages=new Message[msgs.size()];
- int num_reg=0, num_oob=0;
+ int num_reg=0, num_oob=0, num_internal=0;
for(Message msg: msgs) {
messages[index++]=msg;
if(msg.isFlagSet(Message.Flag.OOB))
num_oob++;
+ else if(msg.isFlagSet(Message.Flag.INTERNAL))
+ num_internal++;
else
num_reg++;
}
- mode=num_oob == 0? Mode.REG : num_reg == 0? Mode.OOB : Mode.MIXED;
+ if(num_internal > 0 && num_oob == 0 && num_reg == 0)
+ mode=Mode.INTERNAL;
+ else if(num_oob > 0 && num_internal == 0 && num_reg == 0)
+ mode=Mode.OOB;
+ else if(num_reg > 0 && num_oob == 0 && num_internal == 0)
+ mode=Mode.REG;
+ else
+ mode=Mode.MIXED;
}
public MessageBatch(Address dest, Address sender, String cluster_name, boolean multicast, Collection<Message> msgs) {
@@ -259,7 +268,7 @@ public interface Visitor<T> {
T visit(final Message msg, final MessageBatch batch);
}
- public enum Mode {OOB, REG, MIXED}
+ public enum Mode {OOB, REG, INTERNAL, MIXED}
/** Iterates over <em>non-null</em> elements of a batch, skipping null elements */
diff --git a/tests/junit-functional/org/jgroups/blocks/RpcDispatcherTest.java b/tests/junit-functional/org/jgroups/blocks/RpcDispatcherTest.java
index a255cc09bf6..c53449ac844 100644
--- a/tests/junit-functional/org/jgroups/blocks/RpcDispatcherTest.java
+++ b/tests/junit-functional/org/jgroups/blocks/RpcDispatcherTest.java
@@ -299,7 +299,12 @@ public void testNotifyingFuture() throws Exception {
assert !future.isDone();
assert !future.isCancelled();
assert !listener.isDone();
- Util.sleep(2000);
+ for(int i=0; i < 10; i++) {
+ if(listener.isDone())
+ break;
+ else
+ Util.sleep(1000);
+ }
assert listener.isDone();
RspList<Long> result=future.get(1L, TimeUnit.MILLISECONDS);
System.out.println("result:\n" + result);
diff --git a/tests/junit-functional/org/jgroups/protocols/NAKACK_Delivery_Test.java b/tests/junit-functional/org/jgroups/protocols/NAKACK_Delivery_Test.java
index 9bed658d036..d06f1c3e508 100644
--- a/tests/junit-functional/org/jgroups/protocols/NAKACK_Delivery_Test.java
+++ b/tests/junit-functional/org/jgroups/protocols/NAKACK_Delivery_Test.java
@@ -155,7 +155,7 @@ private void send(Address sender, long seqno, int number, boolean oob) {
private static Message msg(Address sender, long seqno, int number, boolean oob) {
Message msg=new Message(null, sender, number);
if(oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
if(seqno != -1)
msg.putHeader(NAKACK_ID, NakAckHeader2.createMessageHeader(seqno));
return msg;
diff --git a/tests/junit-functional/org/jgroups/protocols/NAKACK_StressTest.java b/tests/junit-functional/org/jgroups/protocols/NAKACK_StressTest.java
index f825fc45497..3fe3662763c 100644
--- a/tests/junit-functional/org/jgroups/protocols/NAKACK_StressTest.java
+++ b/tests/junit-functional/org/jgroups/protocols/NAKACK_StressTest.java
@@ -169,7 +169,7 @@ private static Message createMessage(Address dest, Address src, long seqno, bool
NakAckHeader2 hdr=NakAckHeader2.createMessageHeader(seqno) ;
msg.putHeader(NAKACK_ID, hdr);
if(oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
return msg;
}
diff --git a/tests/junit-functional/org/jgroups/protocols/UNICAST_OOB_Test.java b/tests/junit-functional/org/jgroups/protocols/UNICAST_OOB_Test.java
index 2bb0709b5da..d3a61e3839f 100644
--- a/tests/junit-functional/org/jgroups/protocols/UNICAST_OOB_Test.java
+++ b/tests/junit-functional/org/jgroups/protocols/UNICAST_OOB_Test.java
@@ -78,7 +78,7 @@ private void sendMessages(boolean oob) throws Exception {
for(int i=1; i <=5; i++) {
Message msg=new Message(dest, null,(long)i);
if(i == 4 && oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
System.out.println("-- sending message #" + i);
a.send(msg);
Util.sleep(100);
diff --git a/tests/junit-functional/org/jgroups/tests/DynamicDiscardTest.java b/tests/junit-functional/org/jgroups/tests/DynamicDiscardTest.java
index 4094e3b94ba..d1c159f5e56 100644
--- a/tests/junit-functional/org/jgroups/tests/DynamicDiscardTest.java
+++ b/tests/junit-functional/org/jgroups/tests/DynamicDiscardTest.java
@@ -78,7 +78,7 @@ public void testLeaveDuringSend() throws Exception {
// send a RSVP message
Message msg = new Message(null, "message2");
- msg.setFlag(Message.RSVP, Message.OOB);
+ msg.setFlag(Message.RSVP, Message.Flag.OOB);
RspList<Object> rsps = dispatchers[0].castMessage(null, msg, RequestOptions.SYNC().setTimeout(5000));
Rsp<Object> objectRsp = rsps.get(channels[1].getAddress());
diff --git a/tests/junit-functional/org/jgroups/tests/MessageTest.java b/tests/junit-functional/org/jgroups/tests/MessageTest.java
index e51f809535b..8a65e70b43a 100644
--- a/tests/junit-functional/org/jgroups/tests/MessageTest.java
+++ b/tests/junit-functional/org/jgroups/tests/MessageTest.java
@@ -30,12 +30,12 @@ public class MessageTest {
public static void testFlags() {
Message m1=new Message();
- assert !(m1.isFlagSet(Message.OOB));
+ assert !(m1.isFlagSet(Message.Flag.OOB));
assert m1.getFlags() == 0;
m1.setFlag((Message.Flag[])null);
- assert !m1.isFlagSet(Message.OOB);
+ assert !m1.isFlagSet(Message.Flag.OOB);
assert !m1.isFlagSet(null);
}
@@ -45,72 +45,72 @@ public static void testSettingMultipleFlags() {
msg.setFlag((Message.Flag[])null);
assert msg.getFlags() == 0;
- msg.setFlag(Message.OOB, Message.NO_FC, null, Message.DONT_BUNDLE);
- assert msg.isFlagSet(Message.OOB);
+ msg.setFlag(Message.Flag.OOB, Message.NO_FC, null, Message.Flag.DONT_BUNDLE);
+ assert msg.isFlagSet(Message.Flag.OOB);
assert msg.isFlagSet(Message.NO_FC);
- assert msg.isFlagSet(Message.DONT_BUNDLE);
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE);
}
public static void testFlags2() {
Message m1=new Message();
- m1.setFlag(Message.OOB);
- assert m1.isFlagSet(Message.OOB);
- assert Message.isFlagSet(m1.getFlags(), Message.OOB);
- assert !(m1.isFlagSet(Message.DONT_BUNDLE));
- assert !Message.isFlagSet(m1.getFlags(), Message.DONT_BUNDLE);
+ m1.setFlag(Message.Flag.OOB);
+ assert m1.isFlagSet(Message.Flag.OOB);
+ assert Message.isFlagSet(m1.getFlags(), Message.Flag.OOB);
+ assert !(m1.isFlagSet(Message.Flag.DONT_BUNDLE));
+ assert !Message.isFlagSet(m1.getFlags(), Message.Flag.DONT_BUNDLE);
}
public static void testFlags3() {
Message msg=new Message();
- assert msg.isFlagSet(Message.OOB) == false;
- msg.setFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB);
- msg.setFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB) == false;
+ msg.setFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB);
+ msg.setFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB);
}
public static void testClearFlags() {
Message msg=new Message();
- msg.setFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB);
- msg.clearFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB) == false;
- msg.clearFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB) == false;
- msg.setFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB);
+ msg.clearFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB) == false;
+ msg.clearFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB) == false;
+ msg.setFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB);
}
public static void testClearFlags2() {
Message msg=new Message();
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
msg.setFlag(Message.NO_FC);
- assert msg.isFlagSet(Message.DONT_BUNDLE) == false;
- assert msg.isFlagSet(Message.OOB);
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE) == false;
+ assert msg.isFlagSet(Message.Flag.OOB);
assert msg.isFlagSet(Message.NO_FC);
- msg.clearFlag(Message.OOB);
- assert msg.isFlagSet(Message.OOB) == false;
- msg.setFlag(Message.DONT_BUNDLE);
- assert msg.isFlagSet(Message.DONT_BUNDLE);
+ msg.clearFlag(Message.Flag.OOB);
+ assert msg.isFlagSet(Message.Flag.OOB) == false;
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE);
assert msg.isFlagSet(Message.NO_FC);
msg.clearFlag(Message.NO_FC);
assert msg.isFlagSet(Message.NO_FC) == false;
msg.clearFlag(Message.NO_FC);
assert msg.isFlagSet(Message.NO_FC) == false;
- msg.clearFlag(Message.DONT_BUNDLE);
- msg.clearFlag(Message.OOB);
+ msg.clearFlag(Message.Flag.DONT_BUNDLE);
+ msg.clearFlag(Message.Flag.OOB);
assert msg.getFlags() == 0;
- assert msg.isFlagSet(Message.OOB) == false;
- assert msg.isFlagSet(Message.DONT_BUNDLE) == false;
+ assert msg.isFlagSet(Message.Flag.OOB) == false;
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE) == false;
assert msg.isFlagSet(Message.NO_FC) == false;
- msg.setFlag(Message.DONT_BUNDLE);
- assert msg.isFlagSet(Message.DONT_BUNDLE);
- msg.setFlag(Message.DONT_BUNDLE);
- assert msg.isFlagSet(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
+ assert msg.isFlagSet(Message.Flag.DONT_BUNDLE);
}
@@ -359,8 +359,8 @@ public static void testSizeMessageWithDestAndSrc() throws Exception {
public static void testSizeMessageWithDestAndSrcAndFlags() throws Exception {
Message msg=new Message(UUID.randomUUID(), UUID.randomUUID(), null);
- msg.setFlag(Message.OOB);
- msg.setFlag(Message.DONT_BUNDLE);
+ msg.setFlag(Message.Flag.OOB);
+ msg.setFlag(Message.Flag.DONT_BUNDLE);
_testSize(msg);
}
diff --git a/tests/junit-functional/org/jgroups/tests/NakReceiverWindowTest.java b/tests/junit-functional/org/jgroups/tests/NakReceiverWindowTest.java
index e756760c509..5edb41f2415 100644
--- a/tests/junit-functional/org/jgroups/tests/NakReceiverWindowTest.java
+++ b/tests/junit-functional/org/jgroups/tests/NakReceiverWindowTest.java
@@ -756,7 +756,7 @@ private static void add(int num_msgs, TimeScheduler timer) {
private static Message oob() {
Message retval=new Message();
- retval.setFlag(Message.OOB);
+ retval.setFlag(Message.Flag.OOB);
return retval;
}
diff --git a/tests/junit/org/jgroups/blocks/executor/ExecutingServiceTest.java b/tests/junit/org/jgroups/blocks/executor/ExecutingServiceTest.java
index abe78d66d95..ff55aef0e79 100644
--- a/tests/junit/org/jgroups/blocks/executor/ExecutingServiceTest.java
+++ b/tests/junit/org/jgroups/blocks/executor/ExecutingServiceTest.java
@@ -290,7 +290,7 @@ public void readFrom(DataInput in) throws Exception {
@Test
public void testSimpleSerializableCallableSubmit()
throws InterruptedException, ExecutionException, TimeoutException {
- Long value = Long.valueOf(100);
+ long value =100;
Callable<Long> callable = new SimpleStreamableCallable<Long>(value);
Thread consumer = new Thread(er2);
consumer.start();
@@ -483,7 +483,7 @@ public void testNonSerializableCallable() throws SecurityException,
Thread consumer = new Thread(er2);
consumer.start();
- Long value = Long.valueOf(100);
+ long value =100;
@SuppressWarnings("rawtypes")
Constructor<SimpleCallable> constructor =
diff --git a/tests/junit/org/jgroups/tests/ConnectStressTest.java b/tests/junit/org/jgroups/tests/ConnectStressTest.java
index 54acb078c0d..d279e584239 100755
--- a/tests/junit/org/jgroups/tests/ConnectStressTest.java
+++ b/tests/junit/org/jgroups/tests/ConnectStressTest.java
@@ -86,8 +86,8 @@ public void testConcurrentJoining() throws Exception {
for(MyThread thread: threads) {
View view=thread.getChannel().getView();
- int size=view.size();
- assert size == NUM : "view doesn't have size of " + NUM + " (has " + size + "): " + view;
+ int size=view != null? view.size() : 0;
+ assert view != null && size == NUM : "view doesn't have size of " + NUM + " (has " + size + "): " + view;
}
}
diff --git a/tests/junit/org/jgroups/tests/Deadlock2Test.java b/tests/junit/org/jgroups/tests/Deadlock2Test.java
index 23179f96e74..c048a78750f 100644
--- a/tests/junit/org/jgroups/tests/Deadlock2Test.java
+++ b/tests/junit/org/jgroups/tests/Deadlock2Test.java
@@ -165,7 +165,7 @@ public String outerMethod() throws Exception {
MethodCall call = new MethodCall("innerMethod", new Object[0], new Class[0]);
// RspList rspList = disp.callRemoteMethods(null, call, GroupResponseMode.GET_ALL, 5000);
RequestOptions opts=new RequestOptions(ResponseMode.GET_ALL, 0, false, null, (Message.Flag[])null);
- opts.setFlags(Message.OOB);
+ opts.setFlags(Message.Flag.OOB);
RspList<String> rspList = disp.callRemoteMethods(null, call, opts);
List<String> results = rspList.getResults();
log("results of calling innerMethod():\n" + rspList);
diff --git a/tests/junit/org/jgroups/tests/DuplicateTest.java b/tests/junit/org/jgroups/tests/DuplicateTest.java
index aa27828c2d3..b446e88202e 100644
--- a/tests/junit/org/jgroups/tests/DuplicateTest.java
+++ b/tests/junit/org/jgroups/tests/DuplicateTest.java
@@ -146,10 +146,10 @@ private static void send(Channel sender_channel, Address dest, boolean oob, bool
Message msg=new Message(dest, null, seqno++);
if(mixed) {
if(i % 2 == 0)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
}
else if(oob) {
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
}
sender_channel.send(msg);
diff --git a/tests/junit/org/jgroups/tests/NAKACK_Test.java b/tests/junit/org/jgroups/tests/NAKACK_Test.java
index ff54800c640..792d7077d3e 100644
--- a/tests/junit/org/jgroups/tests/NAKACK_Test.java
+++ b/tests/junit/org/jgroups/tests/NAKACK_Test.java
@@ -66,7 +66,7 @@ public void testOutOfBandMessages() throws Exception {
for(int i=1; i <=5; i++) {
Message msg=new Message(null, null,(long)i);
if(i == 4)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
System.out.println("-- sending message #" + i);
c1.send(msg);
Util.sleep(100);
diff --git a/tests/junit/org/jgroups/tests/OOBTest.java b/tests/junit/org/jgroups/tests/OOBTest.java
index 57133b8923a..7a6fa5a3d73 100644
--- a/tests/junit/org/jgroups/tests/OOBTest.java
+++ b/tests/junit/org/jgroups/tests/OOBTest.java
@@ -67,7 +67,7 @@ public void testRegularAndOOBUnicasts() throws Exception {
Address dest=b.getAddress();
Message m1=new Message(dest, 1);
- Message m2=new Message(dest, 2).setFlag(Message.OOB);
+ Message m2=new Message(dest, 2).setFlag(Message.Flag.OOB);
Message m3=new Message(dest, 3);
MyReceiver receiver=new MyReceiver("B");
@@ -95,8 +95,8 @@ public void testRegularAndOOBUnicasts2() throws Exception {
Address dest=b.getAddress();
Message m1=new Message(dest, 1);
- Message m2=new Message(dest, 2).setFlag(Message.OOB);
- Message m3=new Message(dest, 3).setFlag(Message.OOB);
+ Message m2=new Message(dest, 2).setFlag(Message.Flag.OOB);
+ Message m3=new Message(dest, 3).setFlag(Message.Flag.OOB);
Message m4=new Message(dest, 4);
MyReceiver receiver=new MyReceiver("B");
@@ -127,7 +127,7 @@ public void testRegularAndOOBMulticasts() throws Exception {
Address dest=null; // send to all
Message m1=new Message(dest, 1);
- Message m2=new Message(dest, 2).setFlag(Message.OOB);
+ Message m2=new Message(dest, 2).setFlag(Message.Flag.OOB);
Message m3=new Message(dest, 3);
MyReceiver receiver=new MyReceiver("B");
@@ -198,7 +198,7 @@ public void testOOBMessageLoss() throws Exception {
final int NUM=10;
for(int i=1; i <= NUM; i++)
- a.send(new Message(null, i).setFlag(Message.OOB));
+ a.send(new Message(null, i).setFlag(Message.Flag.OOB));
STABLE stable=(STABLE)a.getProtocolStack().findProtocol(STABLE.class);
if(stable != null)
@@ -230,7 +230,7 @@ public void testOOBUnicastMessageLoss() throws Exception {
final int NUM=10;
final Address dest=b.getAddress();
for(int i=1; i <= NUM; i++)
- a.send(new Message(dest, i).setFlag(Message.OOB));
+ a.send(new Message(dest, i).setFlag(Message.Flag.OOB));
Collection<Integer> msgs=receiver.getMsgs();
for(int i=0; i < 20; i++) {
@@ -267,7 +267,7 @@ public void run() {
int num=counter.incrementAndGet();
Message msg=new Message(dest, num);
if(oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
try {
sender.send(msg);
}
@@ -291,7 +291,7 @@ public void run() {
boolean oob=Util.tossWeightedCoin(oob_prob);
Message msg=new Message(dest, null, i);
if(oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
sender.send(msg);
}
}
@@ -305,7 +305,7 @@ private void send(Address dest) throws Exception {
a.send(dest, 1); // the only regular message
for(int i=2; i <= NUM; i++)
- a.send(new Message(dest, i).setFlag(Message.OOB));
+ a.send(new Message(dest, i).setFlag(Message.Flag.OOB));
sendStableMessages(a,b);
List<Integer> list=receiver.getMsgs();
@@ -393,7 +393,7 @@ private static class BlockingReceiver extends ReceiverAdapter {
public List<Integer> getMsgs() {return msgs;}
public void receive(Message msg) {
- if(!msg.isFlagSet(Message.OOB)) {
+ if(!msg.isFlagSet(Message.Flag.OOB)) {
try {
System.out.println(Thread.currentThread() + ": waiting on latch");
latch.await(25000,TimeUnit.MILLISECONDS);
diff --git a/tests/junit/org/jgroups/tests/UUIDCacheClearTest.java b/tests/junit/org/jgroups/tests/UUIDCacheClearTest.java
index 737b52e242a..579a0f5b3b4 100644
--- a/tests/junit/org/jgroups/tests/UUIDCacheClearTest.java
+++ b/tests/junit/org/jgroups/tests/UUIDCacheClearTest.java
@@ -24,12 +24,12 @@ public void testCacheClear() throws Exception {
try {
a=createChannel(true, 2, "A");
a.setReceiver(r1);
- a.connect("testCacheClear");
+ a.connect("UUIDCacheClearTest");
b=createChannel(a, "B");
b.setReceiver(r2);
- b.connect("testCacheClear");
+ b.connect("UUIDCacheClearTest");
- Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b);
+ Util.waitUntilAllChannelsHaveSameSize(10000, 1000, a, b);
// send one unicast message from a to b and vice versa
@@ -53,7 +53,6 @@ public void testCacheClear() throws Exception {
clearCache(a,b);
printCaches(a,b);
-
r1.clear();
r2.clear();
@@ -103,10 +102,8 @@ protected static void stable(JChannel... channels) {
private static void printCaches(JChannel ... channels) {
System.out.println("caches:\n");
- for(JChannel ch: channels) {
- System.out.println(ch.getAddress() + ":\n" +
- ch.getProtocolStack().getTransport().printLogicalAddressCache());
- }
+ for(JChannel ch: channels)
+ System.out.println(ch.getAddress() + ":\n" + ch.getProtocolStack().getTransport().printLogicalAddressCache());
}
private static class MyReceiver extends ReceiverAdapter {
diff --git a/tests/other/org/jgroups/tests/MessageDispatcherSpeedTest.java b/tests/other/org/jgroups/tests/MessageDispatcherSpeedTest.java
index cb41fb595e2..d869ededa14 100644
--- a/tests/other/org/jgroups/tests/MessageDispatcherSpeedTest.java
+++ b/tests/other/org/jgroups/tests/MessageDispatcherSpeedTest.java
@@ -67,7 +67,7 @@ void sendMessages(int num) throws Exception {
if(show <=0) show=1;
start=System.currentTimeMillis();
- RequestOptions opts=new RequestOptions(ResponseMode.GET_ALL, TIMEOUT).setFlags(Message.DONT_BUNDLE, Message.NO_FC);
+ RequestOptions opts=new RequestOptions(ResponseMode.GET_ALL, TIMEOUT).setFlags(Message.Flag.DONT_BUNDLE, Message.NO_FC);
System.out.println("-- sending " + num + " messages");
for(int i=1; i <= num; i++) {
diff --git a/tests/other/org/jgroups/tests/PingPong.java b/tests/other/org/jgroups/tests/PingPong.java
index 7948f6af2a0..4d6e2275799 100644
--- a/tests/other/org/jgroups/tests/PingPong.java
+++ b/tests/other/org/jgroups/tests/PingPong.java
@@ -41,7 +41,7 @@ public void start(String props, String name, boolean unicast) throws Exception {
dest=(Address)Util.pickRandomElement(members);
Message msg=new Message(dest, null, PING_REQ);
- msg.setFlag(Message.DONT_BUNDLE, Message.NO_FC);
+ msg.setFlag(Message.Flag.DONT_BUNDLE, Message.NO_FC);
start=System.nanoTime();
ch.send(msg);
}
@@ -58,7 +58,7 @@ public void receive(Message msg) {
switch(type) {
case PING:
final Message rsp=new Message(msg.getSrc(), null, PONG_RSP);
- rsp.setFlag(Message.DONT_BUNDLE, Message.NO_FC);
+ rsp.setFlag(Message.Flag.DONT_BUNDLE, Message.NO_FC);
try {
ch.send(rsp);
}
diff --git a/tests/other/org/jgroups/tests/RpcDispatcherSpeedTest.java b/tests/other/org/jgroups/tests/RpcDispatcherSpeedTest.java
index c16349670da..08609dbc2b2 100644
--- a/tests/other/org/jgroups/tests/RpcDispatcherSpeedTest.java
+++ b/tests/other/org/jgroups/tests/RpcDispatcherSpeedTest.java
@@ -114,9 +114,9 @@ void invokeRpcs(int num, int num_threads, boolean async, boolean oob) throws Exc
measure_method_call=new MethodCall((short)0);
RequestOptions opts=new RequestOptions(request_type, TIMEOUT, false, null,
- Message.DONT_BUNDLE, Message.NO_FC);
+ Message.Flag.DONT_BUNDLE, Message.NO_FC);
if(oob)
- opts.setFlags(Message.OOB);
+ opts.setFlags(Message.Flag.OOB);
final AtomicInteger sent=new AtomicInteger(0);
final CountDownLatch latch=new CountDownLatch(1);
diff --git a/tests/other/org/jgroups/tests/UnicastTest.java b/tests/other/org/jgroups/tests/UnicastTest.java
index 9f9cf1c77be..daf1a79f9af 100644
--- a/tests/other/org/jgroups/tests/UnicastTest.java
+++ b/tests/other/org/jgroups/tests/UnicastTest.java
@@ -346,7 +346,7 @@ public void run() {
buf=Util.objectToByteBuffer(val);
Message msg=new Message(destination, null, buf);
if(oob)
- msg.setFlag(Message.OOB);
+ msg.setFlag(Message.Flag.OOB);
if(i > 0 && print > 0 && i % print == 0)
System.out.println("-- sent " + i);
channel.send(msg);
diff --git a/tests/other/org/jgroups/tests/UnicastTestRpc.java b/tests/other/org/jgroups/tests/UnicastTestRpc.java
index 9b7ab32acf8..60607eb29d7 100644
--- a/tests/other/org/jgroups/tests/UnicastTestRpc.java
+++ b/tests/other/org/jgroups/tests/UnicastTestRpc.java
@@ -176,8 +176,8 @@ void invokeRpcs() throws Throwable {
// The first call needs to be synchronous with OOB !
RequestOptions options=new RequestOptions(ResponseMode.GET_ALL, 15000, anycasting, null);
- if(sync) options.setFlags(Message.DONT_BUNDLE);
- if(oob) options.setFlags(Message.OOB);
+ if(sync) options.setFlags(Message.Flag.DONT_BUNDLE);
+ if(oob) options.setFlags(Message.Flag.OOB);
options.setMode(sync? ResponseMode.GET_ALL : ResponseMode.GET_NONE);
diff --git a/tests/perf/org/jgroups/tests/perf/UPerf.java b/tests/perf/org/jgroups/tests/perf/UPerf.java
index e3bb501db47..79b27f433af 100644
--- a/tests/perf/org/jgroups/tests/perf/UPerf.java
+++ b/tests/perf/org/jgroups/tests/perf/UPerf.java
@@ -364,7 +364,7 @@ else if(prot instanceof UNICAST2)
/** Kicks off the benchmark on all cluster nodes */
void startBenchmark() throws Throwable {
RequestOptions options=new RequestOptions(ResponseMode.GET_ALL, 0);
- options.setFlags(Message.OOB, Message.DONT_BUNDLE, Message.NO_FC);
+ options.setFlags(Message.Flag.OOB, Message.Flag.DONT_BUNDLE, Message.NO_FC);
RspList<Object> responses=disp.callRemoteMethods(null, new MethodCall(START), options);
long total_reqs=0;
@@ -481,16 +481,16 @@ public void run() {
RequestOptions put_options=new RequestOptions(sync ? ResponseMode.GET_ALL : ResponseMode.GET_NONE, 40000, true, null);
// Don't use bundling as we have sync requests (e.g. GETs) regardless of whether we set sync=true or false
- get_options.setFlags(Message.DONT_BUNDLE);
- put_options.setFlags(Message.DONT_BUNDLE);
+ get_options.setFlags(Message.Flag.DONT_BUNDLE);
+ put_options.setFlags(Message.Flag.DONT_BUNDLE);
if(oob) {
- get_options.setFlags(Message.OOB);
- put_options.setFlags(Message.OOB);
+ get_options.setFlags(Message.Flag.OOB);
+ put_options.setFlags(Message.Flag.OOB);
}
if(sync) {
- get_options.setFlags(Message.DONT_BUNDLE, Message.NO_FC);
- put_options.setFlags(Message.DONT_BUNDLE, Message.NO_FC);
+ get_options.setFlags(Message.Flag.DONT_BUNDLE, Message.NO_FC);
+ put_options.setFlags(Message.Flag.DONT_BUNDLE, Message.NO_FC);
}
if(use_anycast_addrs) {
put_options.useAnycastAddresses(true);
diff --git a/tests/perf/org/jgroups/tests/perf/UUPerf.java b/tests/perf/org/jgroups/tests/perf/UUPerf.java
index dadbb662642..e866c9844be 100644
--- a/tests/perf/org/jgroups/tests/perf/UUPerf.java
+++ b/tests/perf/org/jgroups/tests/perf/UUPerf.java
@@ -292,7 +292,7 @@ else if(prot instanceof UNICAST2)
*/
void startBenchmark() throws Throwable {
RequestOptions options=new RequestOptions(ResponseMode.GET_ALL,0);
- options.setFlags(Message.OOB,Message.DONT_BUNDLE);
+ options.setFlags(Message.Flag.OOB,Message.Flag.DONT_BUNDLE);
RspList<Object> responses=disp.callRemoteMethods(null,new MethodCall(START),options);
long total_reqs=0;
@@ -382,11 +382,11 @@ public void run() {
RequestOptions apply_state_options=new RequestOptions(sync? ResponseMode.GET_ALL : ResponseMode.GET_NONE,400000,true,null);
if(oob) {
- apply_state_options.setFlags(Message.OOB);
+ apply_state_options.setFlags(Message.Flag.OOB);
}
if(sync) {
- // apply_state_options.setFlags(Message.DONT_BUNDLE,Message.NO_FC);
- apply_state_options.setFlags(Message.DONT_BUNDLE);
+ // apply_state_options.setFlags(Message.Flag.DONT_BUNDLE,Message.NO_FC);
+ apply_state_options.setFlags(Message.Flag.DONT_BUNDLE);
}
apply_state_options.setFlags(Message.Flag.RSVP);
|
9128e0560ea140c7f9375f047d53040117a77e91
|
Vala
|
gconf-2.0: add several missing type arguments, some ownership fixes
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/gconf-2.0.vapi b/vapi/gconf-2.0.vapi
index 88f50732f5..77f919bc37 100644
--- a/vapi/gconf-2.0.vapi
+++ b/vapi/gconf-2.0.vapi
@@ -88,8 +88,8 @@ namespace GConf {
[Compact]
[CCode (ref_function = "gconf_engine_ref", ref_function_void = true, unref_function = "gconf_engine_unref", cheader_filename = "gconf/gconf.h")]
public class Engine {
- public unowned GLib.SList all_dirs (string dir) throws GLib.Error;
- public unowned GLib.SList all_entries (string dir) throws GLib.Error;
+ public GLib.SList<string> all_dirs (string dir) throws GLib.Error;
+ public GLib.SList<GConf.Entry> all_entries (string dir) throws GLib.Error;
public bool associate_schema (string key, string schema_key) throws GLib.Error;
public unowned GConf.ChangeSet change_set_from_current (...) throws GLib.Error;
public unowned GConf.ChangeSet change_set_from_currentv (string keys) throws GLib.Error;
@@ -102,9 +102,9 @@ namespace GConf {
public unowned GConf.Entry get_entry (string key, string locale, bool use_schema_default) throws GLib.Error;
public double get_float (string key) throws GLib.Error;
public static unowned GConf.Engine get_for_address (string address) throws GLib.Error;
- public static unowned GConf.Engine get_for_addresses (GLib.SList addresses) throws GLib.Error;
+ public static unowned GConf.Engine get_for_addresses (GLib.SList<string> addresses) throws GLib.Error;
public int get_int (string key) throws GLib.Error;
- public unowned GLib.SList get_list (string key, GConf.ValueType list_type) throws GLib.Error;
+ public GLib.SList get_list (string key, GConf.ValueType list_type) throws GLib.Error;
public bool get_pair (string key, GConf.ValueType car_type, GConf.ValueType cdr_type, void* car_retloc, void* cdr_retloc) throws GLib.Error;
public unowned GConf.Schema get_schema (string key) throws GLib.Error;
public unowned string get_string (string key) throws GLib.Error;
@@ -226,7 +226,7 @@ namespace GConf {
public unowned GConf.Value get_cdr ();
public double get_float ();
public int get_int ();
- public unowned GLib.SList get_list ();
+ public unowned GLib.SList<GConf.Value> get_list ();
public GConf.ValueType get_list_type ();
public unowned GConf.Schema get_schema ();
public unowned string get_string ();
@@ -237,8 +237,8 @@ namespace GConf {
public void set_cdr_nocopy (GConf.Value cdr);
public void set_float (double the_float);
public void set_int (int the_int);
- public void set_list (GLib.SList list);
- public void set_list_nocopy (GLib.SList list);
+ public void set_list (GLib.SList<GConf.Value> list);
+ public void set_list_nocopy (owned GLib.SList<GConf.Value> list);
public void set_list_type (GConf.ValueType type);
public void set_schema (GConf.Schema sc);
public void set_schema_nocopy (GConf.Schema sc);
diff --git a/vapi/packages/gconf-2.0/gconf-2.0.metadata b/vapi/packages/gconf-2.0/gconf-2.0.metadata
index d1dcc29a82..b29e219bbf 100644
--- a/vapi/packages/gconf-2.0/gconf-2.0.metadata
+++ b/vapi/packages/gconf-2.0/gconf-2.0.metadata
@@ -16,9 +16,16 @@ gconf_client_get_string transfer_ownership="1" nullable="1"
gconf_client_notify_add.func transfer_ownership="1"
gconf_client_notify_add.destroy_notify hidden="1"
gconf_client_get_without_default transfer_ownership="1" nullable="1"
+gconf_engine_all_dirs transfer_ownership="1" type_arguments="string"
+gconf_engine_all_entries transfer_ownership="1" type_arguments="Entry"
+gconf_engine_get_for_addresses.addresses type_arguments="string"
+gconf_engine_get_list transfer_ownership="1"
gconf_entry_copy transfer_ownership="1"
gconf_schema_copy transfer_ownership="1"
gconf_value_copy transfer_ownership="1"
+gconf_value_get_list type_arguments="Value"
+gconf_value_set_list.list type_arguments="Value"
+gconf_value_set_list_nocopy.list transfer_ownership="1" type_arguments="Value"
# deprecated and useless
gconf_init hidden="1"
gconf_meta_info_mod_time name="get_mod_time"
|
d008929c8439edf66bd9bb428201217304eacfea
|
Vala
|
libxml-2.0: Fix instance position in several methods
Fixes bug 609814.
|
c
|
https://github.com/GNOME/vala/
|
diff --git a/vapi/libxml-2.0.vapi b/vapi/libxml-2.0.vapi
index d6c10c5830..d434ed5322 100644
--- a/vapi/libxml-2.0.vapi
+++ b/vapi/libxml-2.0.vapi
@@ -367,7 +367,7 @@ namespace Xml {
[CCode (cname = "xmlDocDumpMemoryEnc")]
public void dump_memory_enc (out string mem, out int len = null, string enc = "UTF-8");
- [CCode (cname = "xmlDocFormatDump", instance_pos = 2)]
+ [CCode (cname = "xmlDocFormatDump", instance_pos = 1.1)]
#if POSIX
public int dump_format (Posix.FILE f, bool format = true);
#else
@@ -380,11 +380,11 @@ namespace Xml {
[CCode (cname = "xmlDocSetRootElement")]
public Node* set_root_element(Node* root);
- [CCode (cname = "xmlElemDump", instance_pos = 2)]
+ [CCode (cname = "xmlElemDump", instance_pos = 1.1)]
#if POSIX
public void elem_dump (Posix.FILE f, Node* cur);
#else
- public void elem_dump (GLib.FileStream f, Node* cur);
+ public void elem_dump (GLib.FileStream f, Node* cur);
#endif
[CCode (cname = "xmlGetDocCompressMode")]
@@ -438,13 +438,13 @@ namespace Xml {
[CCode (cname = "xmlSaveFile", instance_pos = -1)]
public int save_file (string filename);
- [CCode (cname = "xmlSaveFileEnc", instance_pos = 2)]
+ [CCode (cname = "xmlSaveFileEnc", instance_pos = 1.1)]
public void save_file_enc (string filename, string enc = "UTF-8");
- [CCode (cname = "xmlSaveFormatFile", instance_pos = 2)]
+ [CCode (cname = "xmlSaveFormatFile", instance_pos = 1.1)]
public void save_format_file (string filename, int format);
- [CCode (cname = "xmlSaveFormatFileEnc", instance_pos = 2)]
+ [CCode (cname = "xmlSaveFormatFileEnc", instance_pos = 1.1)]
public void save_format_file_enc (string filename, string enc = "UTf-8", bool format = true);
[CCode (cname = "xmlSetDocCompressMode")]
@@ -890,7 +890,7 @@ namespace Xml {
ERROR
}
- [CCode (cname = "xmlReaderTypes", cheader_filename = "libxml/xmlreader.h")]
+ [CCode (cname = "xmlReaderTypes", cheader_filename = "libxml/xmlreader.h")]
public enum ReaderType {
NONE,
ELEMENT,
@@ -1399,7 +1399,7 @@ namespace Xml {
public warningSAXFunc warning;
public errorSAXFunc error;
[CCode (cname = "fatalError")]
- public fatalErrorSAXFunc fatalError;
+ public fatalErrorSAXFunc fatalError;
[CCode (cname = "getParameterEntity")]
public getParameterEntitySAXFunc getParameterEntity;
[CCode (cname = "cdataBlock")]
@@ -1545,24 +1545,24 @@ namespace Html {
[CCode (cname = "htmlSaveFile", instance_pos = -1)]
public int save_file (string filename);
- [CCode (cname = "htmlNodeDumpFile", instance_pos = 2)]
+ [CCode (cname = "htmlNodeDumpFile", instance_pos = 1.1)]
#if POSIX
public int node_dump_file (Posix.FILE file, Xml.Node* node);
#else
public int node_dump_file (GLib.FileStream file, Xml.Node* node);
#endif
- [CCode (cname = "htmlNodeDumpFileFormat", instance_pos = 2)]
+ [CCode (cname = "htmlNodeDumpFileFormat", instance_pos = 1.1)]
#if POSIX
public int node_dump_file_format (Posix.FILE file, string enc = "UTF-8", bool format = true);
#else
public int node_dump_file_format (GLib.FileStream file, string enc = "UTF-8", bool format = true);
#endif
- [CCode (cname = "htmlSaveFileEnc", instance_pos = 2)]
+ [CCode (cname = "htmlSaveFileEnc", instance_pos = 1.1)]
public int save_file_enc (string filename, string enc = "UTF-8");
- [CCode (cname = "htmlSaveFileFormat", instance_pos = 2)]
+ [CCode (cname = "htmlSaveFileFormat", instance_pos = 1.1)]
public int save_file_format (string filename, string enc = "UTF-8", bool format = true);
[CCode (cname = "htmlIsAutoClosed")]
|
c059f5382365930c7b87ff1dbaab0eae5452808a
|
spring-framework
|
SPR-7305 -- o.s.http.client.SimpleClientHttpRequestFactory does not allow to specify a- java.net.Proxy--
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java b/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java
index d41a06949989..cf864fcfc077 100644
--- a/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java
+++ b/org.springframework.web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,9 @@
import java.io.IOException;
import java.net.HttpURLConnection;
+import java.net.Proxy;
import java.net.URI;
+import java.net.URL;
import java.net.URLConnection;
import org.springframework.http.HttpMethod;
@@ -34,17 +36,40 @@
*/
public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory {
+ private Proxy proxy;
+
+ /**
+ * Sets the {@link Proxy} to use for this request factory.
+ */
+ public void setProxy(Proxy proxy) {
+ this.proxy = proxy;
+ }
+
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
- URLConnection urlConnection = uri.toURL().openConnection();
- Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
- HttpURLConnection connection = (HttpURLConnection) urlConnection;
+ HttpURLConnection connection = openConnection(uri.toURL(), proxy);
prepareConnection(connection, httpMethod.name());
return new SimpleClientHttpRequest(connection);
}
/**
- * Template method for preparing the given {@link HttpURLConnection}. <p>The default implementation prepares the
- * connection for input and output, and sets the HTTP method.
+ * Opens and returns a connection to the given URL.
+ * <p>The default implementation uses the given {@linkplain #setProxy(java.net.Proxy) proxy} - if any - to open a
+ * connection.
+ *
+ * @param url the URL to open a connection to
+ * @param proxy the proxy to use, may be {@code null}
+ * @return the opened connection
+ * @throws IOException in case of I/O errors
+ */
+ protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
+ URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
+ Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
+ return (HttpURLConnection) urlConnection;
+ }
+
+ /**
+ * Template method for preparing the given {@link HttpURLConnection}.
+ * <p>The default implementation prepares the connection for input and output, and sets the HTTP method.
*
* @param connection the connection to prepare
* @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
diff --git a/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java b/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java
new file mode 100644
index 000000000000..0ba4e8154163
--- /dev/null
+++ b/org.springframework.web/src/main/java/org/springframework/http/client/support/ProxyFactoryBean.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2002-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.http.client.support;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.SocketAddress;
+
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.util.Assert;
+
+/**
+ * {@link FactoryBean} that creates a {@link Proxy java.net.Proxy}.
+ *
+ * @author Arjen Poutsma
+ * @since 3.0.4
+ * @see FactoryBean
+ * @see Proxy
+ */
+public class ProxyFactoryBean implements FactoryBean<Proxy>, InitializingBean {
+
+ private Proxy.Type type = Proxy.Type.HTTP;
+
+ private String hostname;
+
+ private int port = -1;
+
+ private Proxy proxy;
+
+ /**
+ * Sets the proxy type. Defaults to {@link Proxy.Type#HTTP}.
+ */
+ public void setType(Proxy.Type type) {
+ this.type = type;
+ }
+
+ /**
+ * Sets the proxy host name.
+ */
+ public void setHostname(String hostname) {
+ this.hostname = hostname;
+ }
+
+ /**
+ * Sets the proxy port.
+ */
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public void afterPropertiesSet() throws IllegalArgumentException {
+ Assert.notNull(type, "'type' must not be null");
+ Assert.hasLength(hostname, "'hostname' must not be empty");
+ Assert.isTrue(port >= 0 && port <= 65535, "'port' out of range: " + port);
+
+ SocketAddress socketAddress = new InetSocketAddress(hostname, port);
+ this.proxy = new Proxy(type, socketAddress);
+
+ }
+
+ public Proxy getObject() {
+ return proxy;
+ }
+
+ public Class<?> getObjectType() {
+ return Proxy.class;
+ }
+
+ public boolean isSingleton() {
+ return true;
+ }
+}
diff --git a/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java b/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java
new file mode 100644
index 000000000000..1bb2e0e52426
--- /dev/null
+++ b/org.springframework.web/src/test/java/org/springframework/http/client/support/ProxyFactoryBeanTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2002-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.http.client.support;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+
+import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author Arjen Poutsma
+ */
+public class ProxyFactoryBeanTest {
+
+ ProxyFactoryBean factoryBean;
+
+ @Before
+ public void setUp() {
+ factoryBean = new ProxyFactoryBean();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noType() {
+ factoryBean.setType(null);
+ factoryBean.afterPropertiesSet();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noHostname() {
+ factoryBean.setHostname("");
+ factoryBean.afterPropertiesSet();
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void noPort() {
+ factoryBean.setHostname("example.com");
+ factoryBean.afterPropertiesSet();
+ }
+
+ @Test
+ public void normal() {
+ Proxy.Type type = Proxy.Type.HTTP;
+ factoryBean.setType(type);
+ String hostname = "example.com";
+ factoryBean.setHostname(hostname);
+ int port = 8080;
+ factoryBean.setPort(port);
+ factoryBean.afterPropertiesSet();
+
+ Proxy result = factoryBean.getObject();
+
+ assertEquals(type, result.type());
+ InetSocketAddress address = (InetSocketAddress) result.address();
+ assertEquals(hostname, address.getHostName());
+ assertEquals(port, address.getPort());
+ }
+
+}
|
1d24d71821f0163977a4d625263c9dcfaabe7bcb
|
hbase
|
HBASE-5549 HBASE-5572 Master can fail if- ZooKeeper session expires (N Keywal)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1301775 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java b/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java
index 4f3fbc70d086..0ac1a334ca6d 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/ActiveMasterManager.java
@@ -124,97 +124,96 @@ private void handleMasterNodeChange() {
*
* This also makes sure that we are watching the master znode so will be
* notified if another master dies.
- * @param startupStatus
+ * @param startupStatus
* @return True if no issue becoming active master else false if another
* master was running or if some other problem (zookeeper, stop flag has been
* set on this Master)
*/
boolean blockUntilBecomingActiveMaster(MonitoredTask startupStatus,
- ClusterStatusTracker clusterStatusTracker) {
- startupStatus.setStatus("Trying to register in ZK as active master");
- boolean cleanSetOfActiveMaster = true;
- // Try to become the active master, watch if there is another master.
- // Write out our ServerName as versioned bytes.
- try {
- String backupZNode = ZKUtil.joinZNode(
+ ClusterStatusTracker clusterStatusTracker) {
+ while (true) {
+ startupStatus.setStatus("Trying to register in ZK as active master");
+ // Try to become the active master, watch if there is another master.
+ // Write out our ServerName as versioned bytes.
+ try {
+ String backupZNode = ZKUtil.joinZNode(
this.watcher.backupMasterAddressesZNode, this.sn.toString());
- if (ZKUtil.createEphemeralNodeAndWatch(this.watcher,
+ if (ZKUtil.createEphemeralNodeAndWatch(this.watcher,
this.watcher.masterAddressZNode, this.sn.getVersionedBytes())) {
- // If we were a backup master before, delete our ZNode from the backup
- // master directory since we are the active now
- LOG.info("Deleting ZNode for " + backupZNode +
- " from backup master directory");
- ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode);
-
- // We are the master, return
- startupStatus.setStatus("Successfully registered as active master.");
+ // If we were a backup master before, delete our ZNode from the backup
+ // master directory since we are the active now
+ LOG.info("Deleting ZNode for " + backupZNode +
+ " from backup master directory");
+ ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode);
+
+ // We are the master, return
+ startupStatus.setStatus("Successfully registered as active master.");
+ this.clusterHasActiveMaster.set(true);
+ LOG.info("Master=" + this.sn);
+ return true;
+ }
+
+ // There is another active master running elsewhere or this is a restart
+ // and the master ephemeral node has not expired yet.
this.clusterHasActiveMaster.set(true);
- LOG.info("Master=" + this.sn);
- return cleanSetOfActiveMaster;
- }
- cleanSetOfActiveMaster = false;
-
- // There is another active master running elsewhere or this is a restart
- // and the master ephemeral node has not expired yet.
- this.clusterHasActiveMaster.set(true);
-
- /*
- * Add a ZNode for ourselves in the backup master directory since we are
- * not the active master.
- *
- * If we become the active master later, ActiveMasterManager will delete
- * this node explicitly. If we crash before then, ZooKeeper will delete
- * this node for us since it is ephemeral.
- */
- LOG.info("Adding ZNode for " + backupZNode +
- " in backup master directory");
- ZKUtil.createEphemeralNodeAndWatch(this.watcher, backupZNode,
+
+ /*
+ * Add a ZNode for ourselves in the backup master directory since we are
+ * not the active master.
+ *
+ * If we become the active master later, ActiveMasterManager will delete
+ * this node explicitly. If we crash before then, ZooKeeper will delete
+ * this node for us since it is ephemeral.
+ */
+ LOG.info("Adding ZNode for " + backupZNode +
+ " in backup master directory");
+ ZKUtil.createEphemeralNodeAndWatch(this.watcher, backupZNode,
HConstants.EMPTY_BYTE_ARRAY);
- String msg;
- byte [] bytes =
- ZKUtil.getDataAndWatch(this.watcher, this.watcher.masterAddressZNode);
- if (bytes == null) {
- msg = ("A master was detected, but went down before its address " +
- "could be read. Attempting to become the next active master");
- } else {
- ServerName currentMaster = ServerName.parseVersionedServerName(bytes);
- if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) {
- msg = ("Current master has this master's address, " +
- currentMaster + "; master was restarted? Waiting on znode " +
- "to expire...");
- // Hurry along the expiration of the znode.
- ZKUtil.deleteNode(this.watcher, this.watcher.masterAddressZNode);
+ String msg;
+ byte[] bytes =
+ ZKUtil.getDataAndWatch(this.watcher, this.watcher.masterAddressZNode);
+ if (bytes == null) {
+ msg = ("A master was detected, but went down before its address " +
+ "could be read. Attempting to become the next active master");
} else {
- msg = "Another master is the active master, " + currentMaster +
- "; waiting to become the next active master";
+ ServerName currentMaster = ServerName.parseVersionedServerName(bytes);
+ if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) {
+ msg = ("Current master has this master's address, " +
+ currentMaster + "; master was restarted? Deleting node.");
+ // Hurry along the expiration of the znode.
+ ZKUtil.deleteNode(this.watcher, this.watcher.masterAddressZNode);
+ } else {
+ msg = "Another master is the active master, " + currentMaster +
+ "; waiting to become the next active master";
+ }
}
+ LOG.info(msg);
+ startupStatus.setStatus(msg);
+ } catch (KeeperException ke) {
+ master.abort("Received an unexpected KeeperException, aborting", ke);
+ return false;
}
- LOG.info(msg);
- startupStatus.setStatus(msg);
- } catch (KeeperException ke) {
- master.abort("Received an unexpected KeeperException, aborting", ke);
- return false;
- }
- synchronized (this.clusterHasActiveMaster) {
- while (this.clusterHasActiveMaster.get() && !this.master.isStopped()) {
- try {
- this.clusterHasActiveMaster.wait();
- } catch (InterruptedException e) {
- // We expect to be interrupted when a master dies, will fall out if so
- LOG.debug("Interrupted waiting for master to die", e);
+ synchronized (this.clusterHasActiveMaster) {
+ while (this.clusterHasActiveMaster.get() && !this.master.isStopped()) {
+ try {
+ this.clusterHasActiveMaster.wait();
+ } catch (InterruptedException e) {
+ // We expect to be interrupted when a master dies,
+ // will fall out if so
+ LOG.debug("Interrupted waiting for master to die", e);
+ }
}
+ if (!clusterStatusTracker.isClusterUp()) {
+ this.master.stop(
+ "Cluster went down before this master became active");
+ }
+ if (this.master.isStopped()) {
+ return false;
+ }
+ // there is no active master so we can try to become active master again
}
- if (!clusterStatusTracker.isClusterUp()) {
- this.master.stop("Cluster went down before this master became active");
- }
- if (this.master.isStopped()) {
- return cleanSetOfActiveMaster;
- }
- // Try to become active master again now that there is no active master
- blockUntilBecomingActiveMaster(startupStatus,clusterStatusTracker);
}
- return cleanSetOfActiveMaster;
}
/**
diff --git a/src/main/java/org/apache/hadoop/hbase/master/HMaster.java b/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
index cc56b620ef09..f814dcdaec2c 100644
--- a/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
+++ b/src/main/java/org/apache/hadoop/hbase/master/HMaster.java
@@ -1527,8 +1527,7 @@ public void abort(final String msg, final Throwable t) {
private boolean tryRecoveringExpiredZKSession() throws InterruptedException,
IOException, KeeperException, ExecutionException {
- this.zooKeeper = new ZooKeeperWatcher(conf, MASTER + ":"
- + this.serverName.getPort(), this, true);
+ this.zooKeeper.reconnectAfterExpiration();
Callable<Boolean> callable = new Callable<Boolean> () {
public Boolean call() throws InterruptedException,
diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
index 3e5ac0a839ff..a484d362c066 100644
--- a/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
+++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
@@ -73,25 +73,41 @@ public class RecoverableZooKeeper {
// An identifier of this process in the cluster
private final String identifier;
private final byte[] id;
- private int retryIntervalMillis;
+ private Watcher watcher;
+ private int sessionTimeout;
+ private String quorumServers;
private static final int ID_OFFSET = Bytes.SIZEOF_INT;
// the magic number is to be backward compatible
private static final byte MAGIC =(byte) 0XFF;
private static final int MAGIC_OFFSET = Bytes.SIZEOF_BYTE;
- public RecoverableZooKeeper(String quorumServers, int seesionTimeout,
+ public RecoverableZooKeeper(String quorumServers, int sessionTimeout,
Watcher watcher, int maxRetries, int retryIntervalMillis)
throws IOException {
- this.zk = new ZooKeeper(quorumServers, seesionTimeout, watcher);
+ this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
this.retryCounterFactory =
new RetryCounterFactory(maxRetries, retryIntervalMillis);
- this.retryIntervalMillis = retryIntervalMillis;
// the identifier = processID@hostName
this.identifier = ManagementFactory.getRuntimeMXBean().getName();
LOG.info("The identifier of this process is " + identifier);
this.id = Bytes.toBytes(identifier);
+
+ this.watcher = watcher;
+ this.sessionTimeout = sessionTimeout;
+ this.quorumServers = quorumServers;
+ }
+
+ public void reconnectAfterExpiration()
+ throws IOException, InterruptedException {
+ LOG.info("Closing dead ZooKeeper connection, session" +
+ " was: 0x"+Long.toHexString(zk.getSessionId()));
+ zk.close();
+ this.zk = new ZooKeeper(this.quorumServers,
+ this.sessionTimeout, this.watcher);
+ LOG.info("Recreated a ZooKeeper, session" +
+ " is: 0x"+Long.toHexString(zk.getSessionId()));
}
/**
@@ -123,6 +139,7 @@ public void delete(String path, int version)
throw e;
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -159,6 +176,7 @@ public Stat exists(String path, Watcher watcher)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -194,6 +212,7 @@ public Stat exists(String path, boolean watch)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -229,6 +248,7 @@ public List<String> getChildren(String path, Watcher watcher)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -264,6 +284,7 @@ public List<String> getChildren(String path, boolean watch)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -301,6 +322,7 @@ public byte[] getData(String path, Watcher watcher, Stat stat)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -338,6 +360,7 @@ public byte[] getData(String path, boolean watch, Stat stat)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -377,6 +400,7 @@ public Stat setData(String path, byte[] data, int version)
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -484,6 +508,7 @@ private String createNonSequential(String path, byte[] data, List<ACL> acl,
throw e;
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
@@ -523,6 +548,7 @@ private String createSequential(String path, byte[] data,
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
+ case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
diff --git a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
index 5472cc878691..79b660476f83 100644
--- a/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
+++ b/src/main/java/org/apache/hadoop/hbase/zookeeper/ZooKeeperWatcher.java
@@ -253,6 +253,10 @@ public RecoverableZooKeeper getRecoverableZooKeeper() {
return recoverableZooKeeper;
}
+ public void reconnectAfterExpiration() throws IOException, InterruptedException {
+ recoverableZooKeeper.reconnectAfterExpiration();
+ }
+
/**
* Get the quorum address of this instance.
* @return quorum string of this zookeeper connection instance
diff --git a/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java b/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
index 4696e4dc4869..d9a2a0272f7c 100644
--- a/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
+++ b/src/test/java/org/apache/hadoop/hbase/HBaseTestingUtility.java
@@ -39,6 +39,7 @@
import java.util.NavigableSet;
import java.util.Random;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -73,6 +74,7 @@
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
+import org.apache.hadoop.hbase.util.JVMClusterUtil;
import org.apache.hadoop.hbase.util.RegionSplitter;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.hadoop.hbase.util.Writables;
@@ -86,6 +88,7 @@
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
+import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
/**
@@ -1308,7 +1311,7 @@ public void enableDebug(Class<?> clazz) {
*/
public void expireMasterSession() throws Exception {
HMaster master = hbaseCluster.getMaster();
- expireSession(master.getZooKeeper(), master);
+ expireSession(master.getZooKeeper(), false);
}
/**
@@ -1318,7 +1321,7 @@ public void expireMasterSession() throws Exception {
*/
public void expireRegionServerSession(int index) throws Exception {
HRegionServer rs = hbaseCluster.getRegionServer(index);
- expireSession(rs.getZooKeeper(), rs);
+ expireSession(rs.getZooKeeper(), false);
}
@@ -1334,8 +1337,15 @@ public void expireSession(ZooKeeperWatcher nodeZK, Server server)
}
/**
- * Expire a ZooKeeer session as recommended in ZooKeeper documentation
+ * Expire a ZooKeeper session as recommended in ZooKeeper documentation
* http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
+ * There are issues when doing this:
+ * [1] http://www.mail-archive.com/[email protected]/msg01942.html
+ * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105
+ *
+ * @param nodeZK - the ZK watcher to expire
+ * @param checkStatus - true to check if we can create an HTable with the
+ * current configuration.
*/
public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus)
throws Exception {
@@ -1345,14 +1355,29 @@ public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus)
byte[] password = zk.getSessionPasswd();
long sessionID = zk.getSessionId();
+ // Expiry seems to be asynchronous (see comment from P. Hunt in [1]),
+ // so we create a first watcher to be sure that the
+ // event was sent. We expect that if our watcher receives the event
+ // other watchers on the same machine will get is as well.
+ // When we ask to close the connection, ZK does not close it before
+ // we receive all the events, so don't have to capture the event, just
+ // closing the connection should be enough.
+ ZooKeeper monitor = new ZooKeeper(quorumServers,
+ 1000, new org.apache.zookeeper.Watcher(){
+ @Override
+ public void process(WatchedEvent watchedEvent) {
+ LOG.info("Monitor ZKW received event="+watchedEvent);
+ }
+ } , sessionID, password);
+
+ // Making it expire
ZooKeeper newZK = new ZooKeeper(quorumServers,
1000, EmptyWatcher.instance, sessionID, password);
newZK.close();
LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));
- // There is actually no reason to sleep here. Session is expired.
- // May be for old ZK versions?
- // Thread.sleep(sleep);
+ // Now closing & waiting to be sure that the clients get it.
+ monitor.close();
if (checkStatus) {
new HTable(new Configuration(conf), HConstants.META_TABLE_NAME).close();
@@ -1508,7 +1533,7 @@ public void waitTableAvailable(byte[] table, long timeoutMillis)
* Make sure that at least the specified number of region servers
* are running
* @param num minimum number of region servers that should be running
- * @return True if we started some servers
+ * @return true if we started some servers
* @throws IOException
*/
public boolean ensureSomeRegionServersAvailable(final int num)
@@ -1524,6 +1549,31 @@ public boolean ensureSomeRegionServersAvailable(final int num)
}
+ /**
+ * Make sure that at least the specified number of region servers
+ * are running. We don't count the ones that are currently stopping or are
+ * stopped.
+ * @param num minimum number of region servers that should be running
+ * @return true if we started some servers
+ * @throws IOException
+ */
+ public boolean ensureSomeNonStoppedRegionServersAvailable(final int num)
+ throws IOException {
+ boolean startedServer = ensureSomeRegionServersAvailable(num);
+
+ for (JVMClusterUtil.RegionServerThread rst :
+ hbaseCluster.getRegionServerThreads()) {
+
+ HRegionServer hrs = rst.getRegionServer();
+ if (hrs.isStopping() || hrs.isStopped()) {
+ LOG.info("A region server is stopped or stopping:"+hrs);
+ LOG.info("Started new server=" + hbaseCluster.startRegionServer());
+ startedServer = true;
+ }
+ }
+
+ return startedServer;
+ }
/**
diff --git a/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java b/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java
index a39de81d723a..fc3c46ec973d 100644
--- a/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java
+++ b/src/test/java/org/apache/hadoop/hbase/TestZooKeeper.java
@@ -36,6 +36,7 @@
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
+import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.ZKConfig;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
@@ -93,40 +94,75 @@ public void setUp() throws Exception {
*/
@Test
public void testClientSessionExpired() throws Exception {
- LOG.info("testClientSessionExpired");
Configuration c = new Configuration(TEST_UTIL.getConfiguration());
- new HTable(c, HConstants.META_TABLE_NAME).close();
+
+ // We don't want to share the connection as we will check
+ // its state
+ c.set(HConstants.HBASE_CLIENT_INSTANCE_ID, "1111");
HConnection connection = HConnectionManager.getConnection(c);
+
ZooKeeperWatcher connectionZK = connection.getZooKeeperWatcher();
+ LOG.info("ZooKeeperWatcher= 0x"+ Integer.toHexString(
+ connectionZK.hashCode()));
+ LOG.info("getRecoverableZooKeeper= 0x"+ Integer.toHexString(
+ connectionZK.getRecoverableZooKeeper().hashCode()));
+ LOG.info("session="+Long.toHexString(
+ connectionZK.getRecoverableZooKeeper().getSessionId()));
TEST_UTIL.expireSession(connectionZK);
- // Depending on how long you wait here, the state after dump will
- // be 'closed' or 'Connecting'.
- // There should be no reason to wait, the connection is closed on the server
- // Thread.sleep(sessionTimeout * 3L);
-
- LOG.info("Before dump state=" +
+ LOG.info("Before using zkw state=" +
connectionZK.getRecoverableZooKeeper().getState());
// provoke session expiration by doing something with ZK
- ZKUtil.dump(connectionZK);
+ try {
+ connectionZK.getRecoverableZooKeeper().getZooKeeper().exists(
+ "/1/1", false);
+ } catch (KeeperException ignored) {
+ }
// Check that the old ZK connection is closed, means we did expire
- LOG.info("ZooKeeper should have timed out");
States state = connectionZK.getRecoverableZooKeeper().getState();
- LOG.info("After dump state=" + state);
+ LOG.info("After using zkw state=" + state);
+ LOG.info("session="+Long.toHexString(
+ connectionZK.getRecoverableZooKeeper().getSessionId()));
+
+ // It's asynchronous, so we may have to wait a little...
+ final long limit1 = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < limit1 && state != States.CLOSED){
+ state = connectionZK.getRecoverableZooKeeper().getState();
+ }
+ LOG.info("After using zkw loop=" + state);
+ LOG.info("ZooKeeper should have timed out");
+ LOG.info("session="+Long.toHexString(
+ connectionZK.getRecoverableZooKeeper().getSessionId()));
+
+ // It's surprising but sometimes we can still be in connected state.
+ // As it's known (even if not understood) we don't make the the test fail
+ // for this reason.
Assert.assertTrue(state == States.CLOSED);
// Check that the client recovered
ZooKeeperWatcher newConnectionZK = connection.getZooKeeperWatcher();
- //Here, if you wait, you will have a CONNECTED state. If you don't,
- // you may have the CONNECTING one.
- //Thread.sleep(sessionTimeout * 3L);
+
States state2 = newConnectionZK.getRecoverableZooKeeper().getState();
LOG.info("After new get state=" +state2);
+
+ // As it's an asynchronous event we may got the same ZKW, if it's not
+ // yet invalidated. Hence this loop.
+ final long limit2 = System.currentTimeMillis() + 3000;
+ while (System.currentTimeMillis() < limit2 &&
+ state2 != States.CONNECTED && state2 != States.CONNECTING) {
+
+ newConnectionZK = connection.getZooKeeperWatcher();
+ state2 = newConnectionZK.getRecoverableZooKeeper().getState();
+ }
+ LOG.info("After new get state loop=" + state2);
+
Assert.assertTrue(
state2 == States.CONNECTED || state2 == States.CONNECTING);
+
+ connection.close();
}
@Test
@@ -141,7 +177,21 @@ public void testRegionServerSessionExpired() throws Exception {
public void testMasterSessionExpired() throws Exception {
LOG.info("Starting testMasterSessionExpired");
TEST_UTIL.expireMasterSession();
- Thread.sleep(7000); // Helps the test to succeed!!!
+ testSanity();
+ }
+
+ /**
+ * Master recovery when the znode already exists. Internally, this
+ * test differs from {@link #testMasterSessionExpired} because here
+ * the master znode will exist in ZK.
+ */
+ @Test(timeout=20000)
+ public void testMasterZKSessionRecoveryFailure() throws Exception {
+ MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
+ HMaster m = cluster.getMaster();
+ m.abort("Test recovery from zk session expired",
+ new KeeperException.SessionExpiredException());
+ assertFalse(m.isStopped());
testSanity();
}
diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java b/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java
index 3a0c6b07e89b..afd9f0e68c96 100644
--- a/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java
+++ b/src/test/java/org/apache/hadoop/hbase/master/TestDistributedLogSplitting.java
@@ -87,6 +87,8 @@ private void startCluster(int num_rs) throws Exception{
LOG.info("Starting cluster");
conf = HBaseConfiguration.create();
conf.getLong("hbase.splitlog.max.resubmit", 0);
+ // Make the failure test faster
+ conf.setInt("zookeeper.recovery.retry", 0);
TEST_UTIL = new HBaseTestingUtility(conf);
TEST_UTIL.startMiniCluster(NUM_MASTERS, num_rs);
cluster = TEST_UTIL.getHBaseCluster();
@@ -245,7 +247,7 @@ public void run() {
slm.enqueueSplitTask(logfiles[0].getPath().toString(), batch);
//waitForCounter but for one of the 2 counters
long curt = System.currentTimeMillis();
- long waitTime = 30000;
+ long waitTime = 80000;
long endt = curt + waitTime;
while (curt < endt) {
if ((tot_wkr_task_resigned.get() + tot_wkr_task_err.get() +
diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java b/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java
deleted file mode 100644
index 1b9b24ec560b..000000000000
--- a/src/test/java/org/apache/hadoop/hbase/master/TestMasterZKSessionRecovery.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * Copyright The Apache Software Foundation
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.hadoop.hbase.master;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hbase.HBaseTestingUtility;
-import org.apache.hadoop.hbase.MediumTests;
-import org.apache.hadoop.hbase.MiniHBaseCluster;
-import org.apache.zookeeper.KeeperException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-/**
- * Test cases for master to recover from ZK session expiry.
- */
-@Category(MediumTests.class)
-public class TestMasterZKSessionRecovery {
- private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
-
- /**
- * The default timeout is 5 minutes.
- * Shorten it so that the test won't wait for too long.
- */
- static {
- Configuration conf = TEST_UTIL.getConfiguration();
- conf.setLong("hbase.master.zksession.recover.timeout", 50000);
- }
-
- @Before
- public void setUp() throws Exception {
- // Start a cluster of one regionserver.
- TEST_UTIL.startMiniCluster(1);
- }
-
- @After
- public void tearDown() throws Exception {
- TEST_UTIL.shutdownMiniCluster();
- }
-
- /**
- * Negative test of master recovery from zk session expiry.
- * <p>
- * Starts with one master. Fakes the master zk session expired.
- * Ensures the master cannot recover the expired zk session since
- * the master zk node is still there.
- * @throws Exception
- */
- @Test(timeout=10000)
- public void testMasterZKSessionRecoveryFailure() throws Exception {
- MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
- HMaster m = cluster.getMaster();
- m.abort("Test recovery from zk session expired",
- new KeeperException.SessionExpiredException());
- assertTrue(m.isStopped());
- }
-
- /**
- * Positive test of master recovery from zk session expiry.
- * <p>
- * Starts with one master. Closes the master zk session.
- * Ensures the master can recover the expired zk session.
- * @throws Exception
- */
- @Test(timeout=60000)
- public void testMasterZKSessionRecoverySuccess() throws Exception {
- MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
- HMaster m = cluster.getMaster();
- m.getZooKeeperWatcher().close();
- m.abort("Test recovery from zk session expired",
- new KeeperException.SessionExpiredException());
- assertFalse(m.isStopped());
- }
-}
-
diff --git a/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java b/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
index 1997abd531cb..7485832ee48f 100644
--- a/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
+++ b/src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
@@ -20,6 +20,7 @@
package org.apache.hadoop.hbase.regionserver;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
@@ -78,7 +79,7 @@ public class TestSplitTransactionOnCluster {
}
@Before public void setup() throws IOException {
- TESTING_UTIL.ensureSomeRegionServersAvailable(NB_SERVERS);
+ TESTING_UTIL.ensureSomeNonStoppedRegionServersAvailable(NB_SERVERS);
this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration());
this.cluster = TESTING_UTIL.getMiniHBaseCluster();
}
@@ -398,7 +399,10 @@ private int ensureTableRegionNotOnSameServerAsMeta(final HBaseAdmin admin,
HRegionServer tableRegionServer = cluster.getRegionServer(tableRegionIndex);
if (metaRegionServer.getServerName().equals(tableRegionServer.getServerName())) {
HRegionServer hrs = getOtherRegionServer(cluster, metaRegionServer);
- LOG.info("Moving " + hri.getRegionNameAsString() + " to " +
+ assertNotNull(hrs);
+ assertNotNull(hri);
+ LOG.
+ info("Moving " + hri.getRegionNameAsString() + " to " +
hrs.getServerName() + "; metaServerIndex=" + metaServerIndex);
admin.move(hri.getEncodedNameAsBytes(),
Bytes.toBytes(hrs.getServerName().toString()));
diff --git a/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java b/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java
index a9ae7cac46e0..f6775bad836b 100644
--- a/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java
+++ b/src/test/java/org/apache/hadoop/hbase/replication/TestReplication.java
@@ -93,6 +93,8 @@ public static void setUpBeforeClass() throws Exception {
conf1.setLong("replication.source.sleepforretries", 100);
conf1.setInt("hbase.regionserver.maxlogs", 10);
conf1.setLong("hbase.master.logcleaner.ttl", 10);
+ conf1.setInt("zookeeper.recovery.retry", 1);
+ conf1.setInt("zookeeper.recovery.retry.intervalmill", 10);
conf1.setBoolean(HConstants.REPLICATION_ENABLE_KEY, true);
conf1.setBoolean("dfs.support.append", true);
conf1.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
@@ -651,9 +653,11 @@ public void queueFailover() throws Exception {
int lastCount = 0;
+ final long start = System.currentTimeMillis();
for (int i = 0; i < NB_RETRIES; i++) {
if (i==NB_RETRIES-1) {
- fail("Waited too much time for queueFailover replication");
+ fail("Waited too much time for queueFailover replication. " +
+ "Waited "+(System.currentTimeMillis() - start)+"ms.");
}
Scan scan2 = new Scan();
ResultScanner scanner2 = htable2.getScanner(scan2);
diff --git a/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java b/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java
index dd5460c3968c..1922d60a77fe 100644
--- a/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java
+++ b/src/test/java/org/apache/hadoop/hbase/replication/TestReplicationPeer.java
@@ -24,6 +24,7 @@
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
+import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.junit.*;
import org.junit.experimental.categories.Category;
@@ -58,7 +59,9 @@ public void testResetZooKeeperSession() throws Exception {
try {
LOG.info("Attempting to use expired ReplicationPeer ZooKeeper session.");
// Trying to use the expired session to assert that it is indeed closed
- zkw.getRecoverableZooKeeper().exists("/1/2", false);
+ zkw.getRecoverableZooKeeper().getZooKeeper().exists("/2/2", false);
+ Assert.fail(
+ "ReplicationPeer ZooKeeper session was not properly expired.");
} catch (SessionExpiredException k) {
rp.reloadZkWatcher();
@@ -66,13 +69,12 @@ public void testResetZooKeeperSession() throws Exception {
// Try to use the connection again
LOG.info("Attempting to use refreshed "
- + "ReplicationPeer ZooKeeper session.");
- zkw.getRecoverableZooKeeper().exists("/1/2", false);
+ + "ReplicationPeer ZooKeeper session.");
+ zkw.getRecoverableZooKeeper().exists("/3/2", false);
- return;
+ } catch (KeeperException.ConnectionLossException ignored) {
+ // We sometimes receive this exception. We just ignore it.
}
-
- Assert.fail("ReplicationPeer ZooKeeper session was not properly expired.");
}
|
0f30646656428e3f2eb7c3a598fdf9cb1edee919
|
hbase
|
HBASE-7579 HTableDescriptor equals method fails- if results are returned in a different order; REVERT -- OVERCOMMITTED--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1471053 13f79535-47bb-0310-9956-ffa450edef68-
|
c
|
https://github.com/apache/hbase
|
diff --git a/bin/hbase-daemon.sh b/bin/hbase-daemon.sh
index 91a15ec87d0d..e45054b5ac72 100755
--- a/bin/hbase-daemon.sh
+++ b/bin/hbase-daemon.sh
@@ -36,7 +36,7 @@
usage="Usage: hbase-daemon.sh [--config <conf-dir>]\
(start|stop|restart|autorestart) <hbase-command> \
- [--formatZK] [--formatFS] <args...>"
+ <args...>"
# if no args specified, show usage
if [ $# -le 1 ]; then
@@ -57,19 +57,6 @@ shift
command=$1
shift
-if [ "$startStop" = "start" ];then
- for i in 1 2
- do
- if [ "$1" = "--formatZK" ];then
- formatzk=$1
- shift
- elif [ "$1" = "--formatFS" ];then
- formatfs=$1
- shift
- fi
- done
-fi
-
hbase_rotate_log ()
{
log=$1;
@@ -111,10 +98,6 @@ check_before_start(){
fi
}
-clear_hbase_data() {
- $bin/hbase-cleanup.sh $formatzk $formatfs
-}
-
wait_until_done ()
{
p=$1
@@ -189,7 +172,6 @@ case $startStop in
(start)
check_before_start
- clear_hbase_data
nohup $thiscmd --config "${HBASE_CONF_DIR}" internal_start $command $args < /dev/null > /dev/null 2>&1 &
;;
diff --git a/bin/start-hbase.sh b/bin/start-hbase.sh
index 672a0e89ed01..8fca03ca7769 100755
--- a/bin/start-hbase.sh
+++ b/bin/start-hbase.sh
@@ -24,7 +24,7 @@
# Start hadoop hbase daemons.
# Run this on master node.
-usage="Usage: start-hbase.sh [autorestart] [--formatZK] [--formatFS]"
+usage="Usage: start-hbase.sh"
bin=`dirname "${BASH_SOURCE-$0}"`
bin=`cd "$bin">/dev/null; pwd`
@@ -37,19 +37,12 @@ if [ $errCode -ne 0 ]
then
exit $errCode
fi
-for i in 1 2 3
-do
- if [ "$1" = "autorestart" ];then
- commandToRun="autorestart"
- elif [ "$1" = "--formatZK" ];then
- formatzk=$1
- elif [ "$1" = "--formatFS" ];then
- formatfs=$1
- fi
- shift
-done
-if [ "$commandToRun" = "" ];then
+
+if [ "$1" = "autorestart" ]
+then
+ commandToRun="autorestart"
+else
commandToRun="start"
fi
@@ -59,10 +52,10 @@ distMode=`$bin/hbase --config "$HBASE_CONF_DIR" org.apache.hadoop.hbase.util.HBa
if [ "$distMode" == 'false' ]
then
- "$bin"/hbase-daemon.sh $commandToRun master $formatzk $formatfs
+ "$bin"/hbase-daemon.sh $commandToRun master
else
"$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" $commandToRun zookeeper
- "$bin"/hbase-daemon.sh --config "${HBASE_CONF_DIR}" $commandToRun master $formatzk $formatfs
+ "$bin"/hbase-daemon.sh --config "${HBASE_CONF_DIR}" $commandToRun master
"$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" \
--hosts "${HBASE_REGIONSERVERS}" $commandToRun regionserver
"$bin"/hbase-daemons.sh --config "${HBASE_CONF_DIR}" \
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java
index 4e2c2a829429..ecb0826b5ed8 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java
@@ -1125,10 +1125,12 @@ public void write(DataOutput out) throws IOException {
public int compareTo(HColumnDescriptor o) {
int result = Bytes.compareTo(this.name, o.getName());
if (result == 0) {
- // The maps interface should compare values, even if they're in different orders
- if (!this.values.equals(o.values)) {
- return 1;
- }
+ // punt on comparison for ordering, just calculate difference
+ result = this.values.hashCode() - o.values.hashCode();
+ if (result < 0)
+ result = -1;
+ else if (result > 0)
+ result = 1;
}
if (result == 0) {
result = this.configuration.hashCode() - o.configuration.hashCode();
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java
index b27826856f7c..8d2afcf36eff 100644
--- a/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java
+++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java
@@ -225,7 +225,9 @@ public class HTableDescriptor implements WritableComparable<HTableDescriptor> {
* catalog tables, <code>.META.</code> and <code>-ROOT-</code>.
*/
protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families) {
- setName(name);
+ this.name = name.clone();
+ this.nameAsString = Bytes.toString(this.name);
+ setMetaFlags(name);
for(HColumnDescriptor descriptor : families) {
this.families.put(descriptor.getName(), descriptor);
}
@@ -237,7 +239,12 @@ protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families) {
*/
protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families,
Map<ImmutableBytesWritable,ImmutableBytesWritable> values) {
- this(name.clone(), families);
+ this.name = name.clone();
+ this.nameAsString = Bytes.toString(this.name);
+ setMetaFlags(name);
+ for(HColumnDescriptor descriptor : families) {
+ this.families.put(descriptor.getName(), descriptor);
+ }
for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry:
values.entrySet()) {
setValue(entry.getKey(), entry.getValue());
@@ -277,7 +284,9 @@ public HTableDescriptor(final String name) {
*/
public HTableDescriptor(final byte [] name) {
super();
- setName(name);
+ setMetaFlags(this.name);
+ this.name = this.isMetaRegion()? name: isLegalTableName(name);
+ this.nameAsString = Bytes.toString(this.name);
}
/**
@@ -289,7 +298,9 @@ public HTableDescriptor(final byte [] name) {
*/
public HTableDescriptor(final HTableDescriptor desc) {
super();
- setName(desc.name.clone());
+ this.name = desc.name.clone();
+ this.nameAsString = Bytes.toString(this.name);
+ setMetaFlags(this.name);
for (HColumnDescriptor c: desc.families.values()) {
this.families.put(c.getName(), new HColumnDescriptor(c));
}
@@ -639,13 +650,9 @@ public String getRegionSplitPolicyClassName() {
* Set the name of the table.
*
* @param name name of table
- * @throws IllegalArgumentException if passed a table name
- * that is made of other than 'word' characters, underscore or period: i.e.
- * <code>[a-zA-Z_0-9.].
- * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
*/
public void setName(byte[] name) {
- this.name = isMetaTable(name) ? name : isLegalTableName(name);
+ this.name = name;
this.nameAsString = Bytes.toString(this.name);
setMetaFlags(this.name);
}
@@ -980,34 +987,39 @@ public void write(DataOutput out) throws IOException {
*/
@Override
public int compareTo(final HTableDescriptor other) {
- // Check name matches
int result = Bytes.compareTo(this.name, other.name);
- if (result != 0) return result;
-
- // Check size matches
- result = families.size() - other.families.size();
- if (result != 0) return result;
-
- // Compare that all column families
- for (Iterator<HColumnDescriptor> it = families.values().iterator(),
- it2 = other.families.values().iterator(); it.hasNext(); ) {
- result = it.next().compareTo(it2.next());
- if (result != 0) {
- return result;
+ if (result == 0) {
+ result = families.size() - other.families.size();
+ }
+ if (result == 0 && families.size() != other.families.size()) {
+ result = Integer.valueOf(families.size()).compareTo(
+ Integer.valueOf(other.families.size()));
+ }
+ if (result == 0) {
+ for (Iterator<HColumnDescriptor> it = families.values().iterator(),
+ it2 = other.families.values().iterator(); it.hasNext(); ) {
+ result = it.next().compareTo(it2.next());
+ if (result != 0) {
+ break;
+ }
}
}
-
- // Compare values
- if (!values.equals(other.values)) {
- return 1;
+ if (result == 0) {
+ // punt on comparison for ordering, just calculate difference
+ result = this.values.hashCode() - other.values.hashCode();
+ if (result < 0)
+ result = -1;
+ else if (result > 0)
+ result = 1;
}
-
- // Compare configuration
- if (!configuration.equals(other.configuration)) {
- return 1;
+ if (result == 0) {
+ result = this.configuration.hashCode() - other.configuration.hashCode();
+ if (result < 0)
+ result = -1;
+ else if (result > 0)
+ result = 1;
}
-
- return 0;
+ return result;
}
/**
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java
index fb4506555bbd..253460936dd2 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java
@@ -18,14 +18,12 @@
package org.apache.hadoop.hbase;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
-import org.apache.hadoop.hbase.io.hfile.BlockType;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.junit.experimental.categories.Category;
@@ -96,71 +94,4 @@ public void testAddGetRemoveConfiguration() throws Exception {
desc.removeConfiguration(key);
assertEquals(null, desc.getConfigurationValue(key));
}
-
- @Test
- public void testEqualsWithFamilyName() {
- final String name1 = "someFamilyName";
- HColumnDescriptor hcd1 = new HColumnDescriptor(name1);
- HColumnDescriptor hcd2 = new HColumnDescriptor("someOtherFamilyName");
- HColumnDescriptor hcd3 = new HColumnDescriptor(name1);
-
- assertFalse(hcd1.equals(hcd2));
- assertFalse(hcd2.equals(hcd1));
-
- assertTrue(hcd3.equals(hcd1));
- assertTrue(hcd1.equals(hcd3));
- }
-
- @Test
- public void testEqualsWithAdditionalProperties() {
- final String name1 = "someFamilyName";
- HColumnDescriptor hcd1 = new HColumnDescriptor(name1);
- HColumnDescriptor hcd2 = new HColumnDescriptor(name1);
- hcd2.setBlocksize(4);
-
- assertFalse(hcd1.equals(hcd2));
- assertFalse(hcd2.equals(hcd1));
-
- hcd1.setBlocksize(4);
-
- assertTrue(hcd2.equals(hcd1));
- assertTrue(hcd1.equals(hcd2));
- }
-
- @Test
- public void testEqualsWithDifferentNumberOfProperties() {
- final String name1 = "someFamilyName";
- HColumnDescriptor hcd1 = new HColumnDescriptor(name1);
- HColumnDescriptor hcd2 = new HColumnDescriptor(name1);
- hcd2.setBlocksize(4);
- hcd1.setBlocksize(4);
-
- assertTrue(hcd2.equals(hcd1));
- assertTrue(hcd1.equals(hcd2));
-
- hcd2.setBloomFilterType(BloomType.ROW);
-
- assertFalse(hcd1.equals(hcd2));
- assertFalse(hcd2.equals(hcd1));
- }
-
- @Test
- public void testEqualsWithDifferentOrderingOfProperties() {
- final String name1 = "someFamilyName";
- HColumnDescriptor hcd1 = new HColumnDescriptor(name1);
- HColumnDescriptor hcd2 = new HColumnDescriptor(name1);
- hcd2.setBlocksize(4);
- hcd2.setBloomFilterType(BloomType.ROW);
- hcd1.setBloomFilterType(BloomType.ROW);
- hcd1.setBlocksize(4);
-
- assertTrue(hcd2.equals(hcd1));
- assertTrue(hcd1.equals(hcd2));
- }
-
- @Test
- public void testEqualityWithSameObject() {
- HColumnDescriptor hcd1 = new HColumnDescriptor("someName");
- assertTrue(hcd1.equals(hcd1));
- }
}
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java
index 5f06b429c91a..bc8e72c8689c 100644
--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java
+++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java
@@ -198,173 +198,4 @@ public void testAddGetRemoveConfiguration() throws Exception {
desc.removeConfiguration(key);
assertEquals(null, desc.getConfigurationValue(key));
}
-
- @Test
- public void testEqualsWithDifferentProperties() {
- // Test basic property difference
- HTableDescriptor h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- HTableDescriptor h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n2"));
-
- assertFalse(h2.equals(h1));
- assertFalse(h1.equals(h2));
-
- h2.setName(Bytes.toBytes("n1"));
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testEqualsWithDifferentNumberOfItems() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- // Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someOtherName"));
-
- h1.addFamily(hcd1);
- h2.addFamily(hcd1);
- h1.addFamily(hcd2);
-
- assertFalse(h2.equals(h1));
- assertFalse(h1.equals(h2));
-
- h2.addFamily(hcd2);
-
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testNotEqualsWithDifferentHCDs() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- // Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someOtherName"));
-
- h1.addFamily(hcd1);
- h2.addFamily(hcd2);
-
- assertFalse(h2.equals(h1));
- assertFalse(h1.equals(h2));
- }
-
- @Test
- public void testEqualsWithDifferentHCDObjects() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- // Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someName"));
-
- h1.addFamily(hcd1);
- h2.addFamily(hcd2);
-
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testNotEqualsWithDifferentItems() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- // Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someOtherName"));
- h1.addFamily(hcd1);
- h2.addFamily(hcd2);
-
- assertFalse(h2.equals(h1));
- assertFalse(h1.equals(h2));
- }
-
- @Test
- public void testEqualsWithDifferentOrderingsOfItems() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- //Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someOtherName"));
- h1.addFamily(hcd1);
- h2.addFamily(hcd2);
- h1.addFamily(hcd2);
- h2.addFamily(hcd1);
-
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testSingleItemEquals() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- //Test diff # of items
- h1 = new HTableDescriptor();
- h1.setName(Bytes.toBytes("n1"));
-
- h2 = new HTableDescriptor();
- h2.setName(Bytes.toBytes("n1"));
-
- HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes("someName"));
- HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes("someName"));
- h1.addFamily(hcd1);
- h2.addFamily(hcd2);
-
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testEmptyEquals() {
- HTableDescriptor h1 = new HTableDescriptor();
- HTableDescriptor h2 = new HTableDescriptor();
-
- assertTrue(h2.equals(h1));
- assertTrue(h1.equals(h2));
- }
-
- @Test
- public void testEqualityWithSameObject() {
- HTableDescriptor htd = new HTableDescriptor("someName");
- assertTrue(htd.equals(htd));
- }
}
|
503476bdcbe037c72860b8d932ce74db766b4028
|
fenix-framework$fenix-framework
|
Move group communication down to jvstm-ispn only
This commit complements cc88fe2, which first added support for group
communication in all JVSTM-based backends. It is considered best for now to
keep this backend-specific, so, in this commit, we move such functionality
to the only backend that currently extends jvstm-common: jvsmt-ispn.
|
p
|
https://github.com/fenix-framework/fenix-framework
|
diff --git a/backend/jvstm-common/runtime/pom.xml b/backend/jvstm-common/runtime/pom.xml
index 1148f6ca4..ca0006853 100644
--- a/backend/jvstm-common/runtime/pom.xml
+++ b/backend/jvstm-common/runtime/pom.xml
@@ -74,10 +74,6 @@
<groupId>jvstm</groupId>
<artifactId>jvstm-fenix</artifactId>
</dependency>
- <dependency>
- <groupId>com.hazelcast</groupId>
- <artifactId>hazelcast</artifactId>
- </dependency>
</dependencies>
</project>
diff --git a/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMBackEnd.java b/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMBackEnd.java
index ca0d5b8f5..5b10d0250 100644
--- a/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMBackEnd.java
+++ b/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMBackEnd.java
@@ -29,10 +29,6 @@
import pt.ist.fenixframework.core.DomainObjectAllocator;
import pt.ist.fenixframework.core.SharedIdentityMap;
-import com.hazelcast.core.AtomicNumber;
-import com.hazelcast.core.Hazelcast;
-import com.hazelcast.core.HazelcastInstance;
-
/**
*
*/
@@ -45,8 +41,6 @@ public class JVSTMBackEnd implements BackEnd {
protected final Repository repository;
protected final JVSTMTransactionManager transactionManager;
- protected HazelcastInstance hazelcastInstance;
-
// this constructor is used by the JVSTMConfig when no sub-backend has been created
JVSTMBackEnd() {
this(new NoRepository());
@@ -108,48 +102,9 @@ public <T extends DomainObject> T fromOid(Object oid) {
* @param jvstmConfig
* @throws Exception
*/
- public void init(JVSTMConfig jvstmConfig) throws Exception {
- logger.info("initializeGroupCommunication()");
- initializeGroupCommunication(jvstmConfig);
-
- int serverId = obtainServerId();
- boolean firstNode = (serverId == 0);
-
- if (firstNode) {
- logger.info("This is the first node!");
- localInit(jvstmConfig, serverId);
- // any necessary distributed communication infrastructures must be configured/set before notifying others to proceed
- notifyStartupComplete();
-
- } else {
- logger.info("This is NOT the first node.");
- waitForStartupFromFirstNode();
- localInit(jvstmConfig, serverId);
- }
- }
-
- private void notifyStartupComplete() {
- logger.info("Notify other nodes that startup completed");
-
- AtomicNumber initMarker = getHazelCastInstance().getAtomicNumber("initMarker");
- initMarker.incrementAndGet();
- }
-
- private void waitForStartupFromFirstNode() {
- logger.info("Waiting for startup from first node");
-
- // check initMarker in AtomicNumber (value 1)
- AtomicNumber initMarker = getHazelCastInstance().getAtomicNumber("initMarker");
-
- while (initMarker.get() == 0) {
- logger.debug("Waiting for first node to startup...");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // ignore
- }
- }
- logger.debug("First node startup is complete. We can proceed.");
+ public void init(JVSTMConfig jvstmConfig) {
+ int serverId = obtainNewServerId();
+ localInit(jvstmConfig, serverId);
}
protected void localInit(JVSTMConfig jvstmConfig, int serverId) {
@@ -177,29 +132,17 @@ protected void localInit(JVSTMConfig jvstmConfig, int serverId) {
}
- private int obtainServerId() {
- /* currently does not reuse the server Id value while any server is up.
- This can be changed if needed. However, we currently depend on the first
- server getting the AtomicNumber 0 to know that it is the first member
- to appear. By reusing numbers with the cluster alive, we either don't
- reuse 0 or change the algorithm that detects the first member */
-
- AtomicNumber serverIdGenerator = getHazelCastInstance().getAtomicNumber("serverId");
- long longId = serverIdGenerator.getAndAdd(1L);
-
- logger.info("Got (long) serverId: {}", longId);
-
- int shortId = (int) longId;
- if (shortId != longId) {
- throw new Error("Failed to obtain a valid id");
- }
-
- return shortId;
- }
-
- protected void initializeGroupCommunication(JVSTMConfig jvstmConfig) {
- com.hazelcast.config.Config hzlCfg = jvstmConfig.getHazecastConfig();
- this.hazelcastInstance = Hazelcast.newHazelcastInstance(hzlCfg);
+ /**
+ * Each concrete backend should override this method to provide a new server id when requested. Ideally this method could be
+ * abstract, but the default implementation always returns 0. This is so for two reasons: 1) It works well as a default value
+ * while this jvstm-common code does not wish enforce clustering support on all of its implementations; 2) The NoRepository is
+ * currently implemented at this level (some time in the future it should probably be moved to a 'jvstm-mem' backend). The
+ * Repository implementation does not support clustering, but still requires a serverId value.
+ *
+ * @return
+ */
+ protected int obtainNewServerId() {
+ return 0;
}
// returns whether the repository is new, so that we know we need to create the DomainRoot
@@ -257,13 +200,8 @@ private void ensureFenixFrameworkDataExists() {
}
}
- protected HazelcastInstance getHazelCastInstance() {
- return this.hazelcastInstance;
- }
-
@Override
public void shutdown() {
- getHazelCastInstance().getLifecycleService().shutdown();
}
public Repository getRepository() {
diff --git a/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMConfig.java b/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMConfig.java
index f9d52891c..8e305c129 100644
--- a/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMConfig.java
+++ b/backend/jvstm-common/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/JVSTMConfig.java
@@ -11,11 +11,6 @@
import pt.ist.fenixframework.ConfigError;
import pt.ist.fenixframework.hibernatesearch.HibernateSearchConfig;
-import com.hazelcast.config.ClasspathXmlConfig;
-//import com.hazelcast.core.AtomicNumber;
-//import com.hazelcast.core.Hazelcast;
-//import com.hazelcast.core.HazelcastInstance;
-
/**
* This is the JVSTM configuration manager common for all JVSTM-based backends.
*
@@ -24,17 +19,7 @@
*/
public class JVSTMConfig extends HibernateSearchConfig {
- private static final String FAILED_INIT = "Failed to initialize Backend Infinispan";
-
- protected static final String HAZELCAST_FF_GROUP_NAME = "FenixFrameworkGroup";
-
- /**
- * This <strong>optional</strong> parameter specifies the Hazelcast configuration file. This
- * configuration will used to create a group communication system between Fenix Framework nodes. The default value
- * for this parameter is <code>fenix-framework-hazelcast-default.xml</code>, which is the default
- * configuration file that ships with the framework.
- */
- protected String hazelcastConfigFile = "fenix-framework-hazelcast-default.xml";
+ private static final String FAILED_INIT = "Failed to initialize Backend";
protected JVSTMBackEnd backEnd;
@@ -75,15 +60,4 @@ public String getBackEndName() {
return JVSTMBackEnd.BACKEND_NAME;
}
- public String getHazelcastConfigFile() {
- return hazelcastConfigFile;
- }
-
- public com.hazelcast.config.Config getHazecastConfig() {
- System.setProperty("hazelcast.logging.type", "slf4j");
- com.hazelcast.config.Config hzlCfg = new ClasspathXmlConfig(getHazelcastConfigFile());
- hzlCfg.getGroupConfig().setName(HAZELCAST_FF_GROUP_NAME);
- return hzlCfg;
- }
-
}
diff --git a/backend/jvstm-infinispan/runtime/pom.xml b/backend/jvstm-infinispan/runtime/pom.xml
index 5a2f29ad2..39370d68a 100644
--- a/backend/jvstm-infinispan/runtime/pom.xml
+++ b/backend/jvstm-infinispan/runtime/pom.xml
@@ -83,5 +83,9 @@
<groupId>org.jboss.jbossts</groupId>
<artifactId>jbossjta</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.hazelcast</groupId>
+ <artifactId>hazelcast</artifactId>
+ </dependency>
</dependencies>
</project>
diff --git a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/InfinispanRepository.java b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/InfinispanRepository.java
index 899430030..f100590eb 100644
--- a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/InfinispanRepository.java
+++ b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/InfinispanRepository.java
@@ -80,7 +80,7 @@ private void createCacheContainer(String ispnConfigFile) {
try {
if (ispnConfigFile == null || ispnConfigFile.isEmpty()) {
logger.info("Initializing CacheManager with defaults", ispnConfigFile);
- this.cacheManager = new DefaultCacheManager(makeDefaultGlobalConfiguration()); // smf: make ispnConfigFile optional???
+ this.cacheManager = new DefaultCacheManager(makeDefaultGlobalConfiguration());
} else {
logger.info("Initializing CacheManager with default configuration provided in {}", ispnConfigFile);
this.cacheManager = new DefaultCacheManager(ispnConfigFile);
diff --git a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnBackEnd.java b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnBackEnd.java
index 6aa654c44..9acc3155b 100644
--- a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnBackEnd.java
+++ b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnBackEnd.java
@@ -12,14 +12,21 @@
import pt.ist.fenixframework.FenixFramework;
import pt.ist.fenixframework.backend.jvstm.JVSTMBackEnd;
+import pt.ist.fenixframework.backend.jvstm.JVSTMConfig;
import pt.ist.fenixframework.backend.jvstm.pstm.PersistentReadOnlyTransaction;
import pt.ist.fenixframework.backend.jvstm.pstm.PersistentTransaction;
+import com.hazelcast.core.AtomicNumber;
+import com.hazelcast.core.Hazelcast;
+import com.hazelcast.core.HazelcastInstance;
+
public class JvstmIspnBackEnd extends JVSTMBackEnd {
private static final Logger logger = LoggerFactory.getLogger(JvstmIspnBackEnd.class);
public static final String BACKEND_NAME = "jvstmispn";
+ protected HazelcastInstance hazelcastInstance;
+
JvstmIspnBackEnd() {
super(new InfinispanRepository());
}
@@ -33,6 +40,79 @@ public String getName() {
return BACKEND_NAME;
}
+ @Override
+ public void init(JVSTMConfig jvstmConfig) {
+ JvstmIspnConfig thisConfig = (JvstmIspnConfig) jvstmConfig;
+
+ logger.info("initializeGroupCommunication()");
+ initializeGroupCommunication(thisConfig);
+
+ int serverId = obtainNewServerId();
+ boolean firstNode = (serverId == 0);
+
+ if (firstNode) {
+ logger.info("This is the first node!");
+ localInit(thisConfig, serverId);
+ // any necessary distributed communication infrastructures must be configured/set before notifying others to proceed
+ notifyStartupComplete();
+
+ } else {
+ logger.info("This is NOT the first node.");
+ waitForStartupFromFirstNode();
+ localInit(thisConfig, serverId);
+ }
+ }
+
+ protected void initializeGroupCommunication(JvstmIspnConfig thisConfig) {
+ com.hazelcast.config.Config hzlCfg = thisConfig.getHazelcastConfig();
+ this.hazelcastInstance = Hazelcast.newHazelcastInstance(hzlCfg);
+ }
+
+ private void notifyStartupComplete() {
+ logger.info("Notify other nodes that startup completed");
+
+ AtomicNumber initMarker = getHazelCastInstance().getAtomicNumber("initMarker");
+ initMarker.incrementAndGet();
+ }
+
+ private void waitForStartupFromFirstNode() {
+ logger.info("Waiting for startup from first node");
+
+ // check initMarker in AtomicNumber (value 1)
+ AtomicNumber initMarker = getHazelCastInstance().getAtomicNumber("initMarker");
+
+ while (initMarker.get() == 0) {
+ logger.debug("Waiting for first node to startup...");
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ }
+ logger.debug("First node startup is complete. We can proceed.");
+ }
+
+ @Override
+ protected int obtainNewServerId() {
+ /* currently does not reuse the server Id value while any server is up.
+ This can be changed if needed. However, we currently depend on the first
+ server getting the AtomicNumber 0 to know that it is the first member
+ to appear. By reusing numbers with the cluster alive, we either don't
+ reuse 0 or change the algorithm that detects the first member */
+
+ AtomicNumber serverIdGenerator = getHazelCastInstance().getAtomicNumber("serverId");
+ long longId = serverIdGenerator.getAndAdd(1L);
+
+ logger.info("Got (long) serverId: {}", longId);
+
+ int shortId = (int) longId;
+ if (shortId != longId) {
+ throw new Error("Failed to obtain a valid id");
+ }
+
+ return shortId;
+ }
+
@Override
protected void initializeTransactionFactory() {
jvstm.Transaction.setTransactionFactory(new jvstm.TransactionFactory() {
@@ -48,9 +128,14 @@ public jvstm.Transaction makeReadOnlyTopLevelTransaction(jvstm.ActiveTransaction
});
}
+ protected HazelcastInstance getHazelCastInstance() {
+ return this.hazelcastInstance;
+ }
+
@Override
public void shutdown() {
getRepository().closeRepository();
+ getHazelCastInstance().getLifecycleService().shutdown();
super.shutdown();
}
diff --git a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnConfig.java b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnConfig.java
index d0afdc4fd..878fd6b7e 100644
--- a/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnConfig.java
+++ b/backend/jvstm-infinispan/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/infinispan/JvstmIspnConfig.java
@@ -12,6 +12,11 @@
import pt.ist.fenixframework.backend.jvstm.JVSTMConfig;
+import com.hazelcast.config.ClasspathXmlConfig;
+//import com.hazelcast.core.AtomicNumber;
+//import com.hazelcast.core.Hazelcast;
+//import com.hazelcast.core.HazelcastInstance;
+
/**
* This is the configuration manager used by the fenix-framework-backend-jvstm-infinispan project.
*
@@ -22,13 +27,25 @@ public class JvstmIspnConfig extends JVSTMConfig {
private static final String FAILED_INIT = "Failed to initialize Backend JVSTM-Infinispan";
+ protected static final String HAZELCAST_FF_GROUP_NAME = "FenixFrameworkGroup";
+
+ /**
+ * This <strong>optional</strong> parameter specifies the Hazelcast configuration file. This
+ * configuration will used to create a group communication system between Fenix Framework nodes. The default value
+ * for this parameter is <code>fenix-framework-hazelcast-default.xml</code>, which is the default
+ * configuration file that ships with the framework.
+ */
+ protected String hazelcastConfigFile = "fenix-framework-hazelcast-default.xml";
+
/**
* This <strong>optional</strong> parameter specifies the location of the XML file used to configure Infinispan. This file
* should be available in the application's classpath.
*/
protected String ispnConfigFile = null;
- // process this config's parameters
+ public String getHazelcastConfigFile() {
+ return hazelcastConfigFile;
+ }
public String getIspnConfigFile() {
return this.ispnConfigFile;
@@ -51,4 +68,11 @@ public String getBackEndName() {
return JvstmIspnBackEnd.BACKEND_NAME;
}
+ public com.hazelcast.config.Config getHazelcastConfig() {
+ System.setProperty("hazelcast.logging.type", "slf4j");
+ com.hazelcast.config.Config hzlCfg = new ClasspathXmlConfig(getHazelcastConfigFile());
+ hzlCfg.getGroupConfig().setName(HAZELCAST_FF_GROUP_NAME);
+ return hzlCfg;
+ }
+
}
diff --git a/backend/jvstm-common/runtime/src/main/resources/fenix-framework-hazelcast-default.xml b/backend/jvstm-infinispan/runtime/src/main/resources/fenix-framework-hazelcast-default.xml
similarity index 100%
rename from backend/jvstm-common/runtime/src/main/resources/fenix-framework-hazelcast-default.xml
rename to backend/jvstm-infinispan/runtime/src/main/resources/fenix-framework-hazelcast-default.xml
diff --git a/pom.xml b/pom.xml
index f80370634..718f77e15 100644
--- a/pom.xml
+++ b/pom.xml
@@ -111,7 +111,7 @@
<configuration>
<reuseForks>false</reuseForks>
<forkCount>${forkCount}</forkCount>
- <argLine>-Xms512m -Xmx512m</argLine>
+ <argLine>-Xms512m -Xmx512m -Djava.net.preferIPv4Stack=true</argLine>
<excludes>
<exclude>${test.excludes}</exclude>
</excludes>
diff --git a/test/test-backend-jvstm-common/src/test/resources/infinispanConf.xml b/test/test-backend-jvstm-common/src/test/resources/infinispanConf.xml
index f5b73ada2..625a405fe 100644
--- a/test/test-backend-jvstm-common/src/test/resources/infinispanConf.xml
+++ b/test/test-backend-jvstm-common/src/test/resources/infinispanConf.xml
@@ -1,11 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<infinispan>
- <!-- <global> -->
+ <global>
+ <transport
+ clusterName="infinispan-cluster">
+ <properties>
+ <property
+ name="configurationFile"
+ value="fenix-framework-udp-jgroups.xml"/>
+ </properties>
+ </transport>
<!-- <globalJmxStatistics -->
<!-- enabled="true" -->
<!-- jmxDomain="org.infinispan"/> -->
- <!-- </global> -->
+ </global>
<default>
+ <clustering mode="r">
+ <sync
+ replTimeout="15000"/>
+ <stateTransfer
+ fetchInMemoryState="true"
+ chunkSize="100"
+ timeout="240000"/>
+ </clustering>
+
<!-- <jmxStatistics enabled="true" /> -->
<loaders preload="false" shared="false">
diff --git a/test/test-backend-jvstm-common/src/test/resources/log4j.properties b/test/test-backend-jvstm-common/src/test/resources/log4j.properties
index a71382e1a..50b883877 100644
--- a/test/test-backend-jvstm-common/src/test/resources/log4j.properties
+++ b/test/test-backend-jvstm-common/src/test/resources/log4j.properties
@@ -1,7 +1,7 @@
log4j.logger.test.backend=WARN, FFAPEND
log4j.logger.pt.ist.fenixframework=WARN, FFAPEND
-log4j.logger.org.jgroups=WARN, FFAPEND
+log4j.logger.org.jgroups=ERROR, FFAPEND
log4j.logger.org.hibernate.search.impl=WARN, FFAPEND
log4j.logger.org=WARN, FFAPEND
log4j.logger.com=WARN, FFAPEND
|
3fdd2f2b7464a310674bb62f58dcbff90d1ad16a
|
restlet-framework-java
|
- Fixed bugs--
|
c
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/source/main/com/noelios/restlet/build/ChainletBuilder.java b/source/main/com/noelios/restlet/build/ChainletBuilder.java
index ed7fe22341..e5ea77d6c9 100644
--- a/source/main/com/noelios/restlet/build/ChainletBuilder.java
+++ b/source/main/com/noelios/restlet/build/ChainletBuilder.java
@@ -62,7 +62,7 @@ public ChainletBuilder(DefaultBuilder parent, Chainlet node)
*/
public Chainlet getNode()
{
- return (Chainlet)getNode();
+ return (Chainlet)super.getNode();
}
/**
diff --git a/source/main/com/noelios/restlet/build/ComponentBuilder.java b/source/main/com/noelios/restlet/build/ComponentBuilder.java
index 5135b31ba9..80d42b3092 100644
--- a/source/main/com/noelios/restlet/build/ComponentBuilder.java
+++ b/source/main/com/noelios/restlet/build/ComponentBuilder.java
@@ -51,7 +51,7 @@ public ComponentBuilder(DefaultBuilder parent, Component node)
*/
public Component getNode()
{
- return (Component)getNode();
+ return (Component)super.getNode();
}
/**
diff --git a/source/main/com/noelios/restlet/build/ExtractChainletBuilder.java b/source/main/com/noelios/restlet/build/ExtractChainletBuilder.java
index 40d40eac8b..22945cda33 100644
--- a/source/main/com/noelios/restlet/build/ExtractChainletBuilder.java
+++ b/source/main/com/noelios/restlet/build/ExtractChainletBuilder.java
@@ -46,7 +46,7 @@ public ExtractChainletBuilder(DefaultBuilder parent, ExtractChainlet node)
*/
public ExtractChainlet getNode()
{
- return (ExtractChainlet)getNode();
+ return (ExtractChainlet)super.getNode();
}
/**
diff --git a/source/main/com/noelios/restlet/build/GuardChainletBuilder.java b/source/main/com/noelios/restlet/build/GuardChainletBuilder.java
index 420e4a20cd..1dd5e1c17b 100644
--- a/source/main/com/noelios/restlet/build/GuardChainletBuilder.java
+++ b/source/main/com/noelios/restlet/build/GuardChainletBuilder.java
@@ -46,7 +46,7 @@ public GuardChainletBuilder(DefaultBuilder parent, GuardChainlet node)
*/
public GuardChainlet getNode()
{
- return (GuardChainlet)getNode();
+ return (GuardChainlet)super.getNode();
}
/**
|
3ea0cf36bc778a46127c20d9d12da921baa237d7
|
spring-framework
|
Hibernate synchronization properly unbinds- Session even in case of afterCompletion exception (SPR-8757)--
|
c
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SpringSessionSynchronization.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SpringSessionSynchronization.java
index aab75ceb2024..240ebcbcc944 100644
--- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SpringSessionSynchronization.java
+++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/SpringSessionSynchronization.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -218,32 +218,40 @@ public void afterCommit() {
}
public void afterCompletion(int status) {
- if (!this.hibernateTransactionCompletion || !this.newSession) {
- // No Hibernate TransactionManagerLookup: apply afterTransactionCompletion callback.
- // Always perform explicit afterTransactionCompletion callback for pre-bound Session,
- // even with Hibernate TransactionManagerLookup (which only applies to new Sessions).
- Session session = this.sessionHolder.getSession();
- // Provide correct transaction status for releasing the Session's cache locks,
- // if possible. Else, closing will release all cache locks assuming a rollback.
- if (session instanceof SessionImplementor) {
- ((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED, null);
- }
- // Close the Hibernate Session here if necessary
- // (closed in beforeCompletion in case of TransactionManagerLookup).
- if (this.newSession) {
- SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory);
+ try {
+ if (!this.hibernateTransactionCompletion || !this.newSession) {
+ // No Hibernate TransactionManagerLookup: apply afterTransactionCompletion callback.
+ // Always perform explicit afterTransactionCompletion callback for pre-bound Session,
+ // even with Hibernate TransactionManagerLookup (which only applies to new Sessions).
+ Session session = this.sessionHolder.getSession();
+ // Provide correct transaction status for releasing the Session's cache locks,
+ // if possible. Else, closing will release all cache locks assuming a rollback.
+ try {
+ if (session instanceof SessionImplementor) {
+ ((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED, null);
+ }
+ }
+ finally {
+ // Close the Hibernate Session here if necessary
+ // (closed in beforeCompletion in case of TransactionManagerLookup).
+ if (this.newSession) {
+ SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory);
+ }
+ else if (!this.hibernateTransactionCompletion) {
+ session.disconnect();
+ }
+ }
}
- else if (!this.hibernateTransactionCompletion) {
- session.disconnect();
+ if (!this.newSession && status != STATUS_COMMITTED) {
+ // Clear all pending inserts/updates/deletes in the Session.
+ // Necessary for pre-bound Sessions, to avoid inconsistent state.
+ this.sessionHolder.getSession().clear();
}
}
- if (!this.newSession && status != STATUS_COMMITTED) {
- // Clear all pending inserts/updates/deletes in the Session.
- // Necessary for pre-bound Sessions, to avoid inconsistent state.
- this.sessionHolder.getSession().clear();
- }
- if (this.sessionHolder.doesNotHoldNonDefaultSession()) {
- this.sessionHolder.setSynchronizedWithTransaction(false);
+ finally {
+ if (this.sessionHolder.doesNotHoldNonDefaultSession()) {
+ this.sessionHolder.setSynchronizedWithTransaction(false);
+ }
}
}
diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/SpringSessionSynchronization.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/SpringSessionSynchronization.java
index fa49ace3f743..19f47c86fc83 100644
--- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/SpringSessionSynchronization.java
+++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate4/SpringSessionSynchronization.java
@@ -111,12 +111,16 @@ public void afterCommit() {
}
public void afterCompletion(int status) {
- if (status != STATUS_COMMITTED) {
- // Clear all pending inserts/updates/deletes in the Session.
- // Necessary for pre-bound Sessions, to avoid inconsistent state.
- this.sessionHolder.getSession().clear();
+ try {
+ if (status != STATUS_COMMITTED) {
+ // Clear all pending inserts/updates/deletes in the Session.
+ // Necessary for pre-bound Sessions, to avoid inconsistent state.
+ this.sessionHolder.getSession().clear();
+ }
+ }
+ finally {
+ this.sessionHolder.setSynchronizedWithTransaction(false);
}
- this.sessionHolder.setSynchronizedWithTransaction(false);
}
}
|
590e82afc18b5d5663f9ad08f3b49d802698b95e
|
aeshell$aesh
|
[AESH-303]
added support for help info for group commands
|
a
|
https://github.com/aeshell/aesh
|
diff --git a/src/main/java/AeshExample.java b/src/main/java/AeshExample.java
index f20290926..33fa74927 100644
--- a/src/main/java/AeshExample.java
+++ b/src/main/java/AeshExample.java
@@ -474,23 +474,37 @@ public InputStream getManualDocument(String commandName) {
}
}
- @GroupCommandDefinition(name = "group", description = "", groupCommands = {Child1.class, Child2.class})
+ @GroupCommandDefinition(name = "group", description = "This is a group command",
+ groupCommands = {Child1.class, Child2.class})
public static class GroupCommand implements Command {
+
+ @Option(hasValue = false, description = "display this help option")
+ private boolean help;
+
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException {
- commandInvocation.getShell().out().println("only executed group, it doesnt do much...");
+ if(help)
+ commandInvocation.getShell().out().println(commandInvocation.getHelpInfo("group"));
+ else
+ commandInvocation.getShell().out().println("only executed group, it doesnt do much...");
return CommandResult.SUCCESS;
}
}
@CommandDefinition(name = "child1", description = "")
public static class Child1 implements Command {
- @Option
+
+ @Option(description = "set foo")
private String foo;
+ @Option(hasValue = false, description = "display this help option")
+ private boolean help;
@Override
public CommandResult execute(CommandInvocation commandInvocation) throws IOException, InterruptedException {
- commandInvocation.getShell().out().println("foo is set to: "+foo);
+ if(help)
+ commandInvocation.getShell().out().println(commandInvocation.getHelpInfo("group child1"));
+ else
+ commandInvocation.getShell().out().println("foo is set to: "+foo);
return CommandResult.SUCCESS;
}
}
diff --git a/src/main/java/org/jboss/aesh/cl/parser/AeshCommandLineParser.java b/src/main/java/org/jboss/aesh/cl/parser/AeshCommandLineParser.java
index b1417d322..ac6fb91b2 100644
--- a/src/main/java/org/jboss/aesh/cl/parser/AeshCommandLineParser.java
+++ b/src/main/java/org/jboss/aesh/cl/parser/AeshCommandLineParser.java
@@ -24,6 +24,7 @@
import org.jboss.aesh.cl.internal.ProcessedCommand;
import org.jboss.aesh.cl.internal.ProcessedOption;
import org.jboss.aesh.cl.populator.CommandPopulator;
+import org.jboss.aesh.console.Config;
import org.jboss.aesh.console.command.Command;
import org.jboss.aesh.parser.AeshLine;
import org.jboss.aesh.parser.Parser;
@@ -114,7 +115,20 @@ public CommandPopulator getCommandPopulator() {
*/
@Override
public String printHelp() {
- return processedCommand.printHelp();
+ if(childParsers != null && childParsers.size() > 0) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(processedCommand.printHelp())
+ .append(Config.getLineSeparator())
+ .append(processedCommand.getName())
+ .append(" commands:")
+ .append(Config.getLineSeparator());
+ for(CommandLineParser child : childParsers)
+ sb.append(" ").append(child.getProcessedCommand().getName()).append(Config.getLineSeparator());
+
+ return sb.toString();
+ }
+ else
+ return processedCommand.printHelp();
}
/**
diff --git a/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java b/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java
index 98af4aee8..09a145302 100644
--- a/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java
+++ b/src/main/java/org/jboss/aesh/console/AeshConsoleImpl.java
@@ -138,7 +138,7 @@ public void clear() {
public String getHelpInfo(String commandName) {
try (CommandContainer commandContainer = registry.getCommand(commandName, "")) {
if (commandContainer != null)
- return commandContainer.getParser().printHelp();
+ return commandContainer.printHelp(commandName);
}
catch (Exception e) { // ignored
}
diff --git a/src/main/java/org/jboss/aesh/console/command/container/CommandContainer.java b/src/main/java/org/jboss/aesh/console/command/container/CommandContainer.java
index 22ec5a878..4cd3386d3 100644
--- a/src/main/java/org/jboss/aesh/console/command/container/CommandContainer.java
+++ b/src/main/java/org/jboss/aesh/console/command/container/CommandContainer.java
@@ -52,6 +52,12 @@ public interface CommandContainer<T extends Command> extends AutoCloseable {
*/
boolean haveBuildError();
+ /**
+ * @param childCommandName (for group commands)
+ * @return help info
+ */
+ String printHelp(String childCommandName);
+
/**
* @return error message
*/
diff --git a/src/main/java/org/jboss/aesh/console/command/container/DefaultCommandContainer.java b/src/main/java/org/jboss/aesh/console/command/container/DefaultCommandContainer.java
index 647a9536a..04fa79750 100644
--- a/src/main/java/org/jboss/aesh/console/command/container/DefaultCommandContainer.java
+++ b/src/main/java/org/jboss/aesh/console/command/container/DefaultCommandContainer.java
@@ -20,6 +20,7 @@
package org.jboss.aesh.console.command.container;
import org.jboss.aesh.cl.CommandLine;
+import org.jboss.aesh.cl.parser.CommandLineParser;
import org.jboss.aesh.cl.parser.CommandLineParserException;
import org.jboss.aesh.cl.validator.CommandValidatorException;
import org.jboss.aesh.cl.validator.OptionValidatorException;
@@ -53,4 +54,19 @@ public CommandContainerResult executeCommand(AeshLine line, InvocationProviders
return new CommandContainerResult(commandLine.getParser().getProcessedCommand().getResultHandler(), result);
}
+
+ @Override
+ public String printHelp(String childCommandName) {
+ if(getParser().isGroupCommand() && childCommandName.contains(" ")) {
+ String[] names = childCommandName.split(" ");
+ if(names.length > 1 && names[1].length() > 0) {
+ CommandLineParser child = getParser().getChildParser(names[1]);
+ if(child != null)
+ return child.printHelp();
+ }
+ return "Child command "+names[1]+" not found.";
+ }
+ else
+ return getParser().printHelp();
+ }
}
diff --git a/src/main/java/org/jboss/aesh/console/command/registry/MutableCommandRegistry.java b/src/main/java/org/jboss/aesh/console/command/registry/MutableCommandRegistry.java
index 2c4824ca0..0d2abe506 100644
--- a/src/main/java/org/jboss/aesh/console/command/registry/MutableCommandRegistry.java
+++ b/src/main/java/org/jboss/aesh/console/command/registry/MutableCommandRegistry.java
@@ -50,6 +50,14 @@ public void setCommandContainerBuilder(CommandContainerBuilder containerBuilder)
public CommandContainer getCommand(String name, String line) throws CommandNotFoundException {
if(registry.containsKey(name))
return registry.get(name);
+ //group command
+ else if(name.contains(" ")) {
+ String[] names = name.split(" ");
+ if(registry.containsKey(names[0])) {
+ return registry.get(names[0]);
+ }
+ throw new CommandNotFoundException("Command: "+names[0]+" was not found.");
+ }
else
throw new CommandNotFoundException("Command: "+name+" was not found.");
}
diff --git a/src/test/java/org/jboss/aesh/cl/CommandLineFormatterTest.java b/src/test/java/org/jboss/aesh/cl/CommandLineFormatterTest.java
index 5117dd0ba..7ac962038 100644
--- a/src/test/java/org/jboss/aesh/cl/CommandLineFormatterTest.java
+++ b/src/test/java/org/jboss/aesh/cl/CommandLineFormatterTest.java
@@ -19,7 +19,6 @@
*/
package org.jboss.aesh.cl;
-import junit.framework.TestCase;
import org.jboss.aesh.cl.internal.ProcessedCommandBuilder;
import org.jboss.aesh.cl.internal.ProcessedOptionBuilder;
import org.jboss.aesh.cl.parser.CommandLineParserException;
@@ -27,17 +26,18 @@
import org.jboss.aesh.cl.parser.CommandLineParserBuilder;
import org.jboss.aesh.console.Config;
import org.jboss.aesh.util.ANSI;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* @author <a href="mailto:[email protected]">Ståle W. Pedersen</a>
*/
-public class CommandLineFormatterTest extends TestCase {
+public class CommandLineFormatterTest {
- public CommandLineFormatterTest(String name) {
- super(name);
- }
- public void testFormatter() throws CommandLineParserException {
+ @Test
+ public void formatter() throws CommandLineParserException {
ProcessedCommandBuilder pb = new ProcessedCommandBuilder().name("man").description("[OPTION...]");
pb.addOption(
@@ -68,7 +68,8 @@ public void testFormatter() throws CommandLineParserException {
clp.printHelp());
}
- public void testFormatter2() throws CommandLineParserException {
+ @Test
+ public void formatter2() throws CommandLineParserException {
ProcessedCommandBuilder pb = new ProcessedCommandBuilder().name("man").description("[OPTION...]");
pb.addOption(
@@ -114,4 +115,58 @@ public void testFormatter2() throws CommandLineParserException {
clp.printHelp());
}
+ @Test
+ public void groupFormatter() throws CommandLineParserException {
+ ProcessedCommandBuilder git = new ProcessedCommandBuilder().name("git").description("[OPTION...]");
+ git.addOption(
+ new ProcessedOptionBuilder()
+ .shortName('h')
+ .name("help")
+ .description("display help info")
+ .type(boolean.class)
+ .create()
+ );
+
+ ProcessedCommandBuilder rebase = new ProcessedCommandBuilder().name("rebase").description("[OPTION...]");
+ rebase.addOption(
+ new ProcessedOptionBuilder()
+ .shortName('f')
+ .name("foo")
+ .required(true)
+ .description("reset all options to their default values")
+ .type(String.class)
+ .create()
+ );
+
+ ProcessedCommandBuilder branch = new ProcessedCommandBuilder().name("branch").description("branching");
+ branch.addOption(
+ new ProcessedOptionBuilder()
+ .shortName('b')
+ .name("bar")
+ .required(true)
+ .description("reset all options to their default values")
+ .type(String.class)
+ .create()
+ );
+
+
+ CommandLineParser clpGit = new CommandLineParserBuilder().processedCommand(git.create()).create();
+ CommandLineParser clpBranch = new CommandLineParserBuilder().processedCommand(branch.create()).create();
+ CommandLineParser clpRebase = new CommandLineParserBuilder().processedCommand(rebase.create()).create();
+
+ clpGit.addChildParser(clpBranch);
+ clpGit.addChildParser(clpRebase);
+
+ assertEquals("Usage: git [OPTION...]" + Config.getLineSeparator() +
+ Config.getLineSeparator() +
+ "Options:" + Config.getLineSeparator() +
+ " -h, --help display help info" + Config.getLineSeparator()
+ + Config.getLineSeparator()+"git commands:"+Config.getLineSeparator()+
+ " branch"+Config.getLineSeparator()+
+ " rebase"+Config.getLineSeparator(),
+ clpGit.printHelp());
+
+
+ }
+
}
|
bd1b559d47603748f6d57a0ff21f68505258ace5
|
spring-framework
|
MockHttpServletResponse supports multiple- includes (SPR-
|
a
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
index 6256bbe51632..6d220572665d 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -98,7 +98,7 @@ public class MockHttpServletResponse implements HttpServletResponse {
private String forwardedUrl;
- private String includedUrl;
+ private final List<String> includedUrls = new ArrayList<String>();
//---------------------------------------------------------------------
@@ -443,11 +443,28 @@ public String getForwardedUrl() {
}
public void setIncludedUrl(String includedUrl) {
- this.includedUrl = includedUrl;
+ this.includedUrls.clear();
+ if (includedUrl != null) {
+ this.includedUrls.add(includedUrl);
+ }
}
public String getIncludedUrl() {
- return this.includedUrl;
+ int count = this.includedUrls.size();
+ if (count > 1) {
+ throw new IllegalStateException(
+ "More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
+ }
+ return (count == 1 ? this.includedUrls.get(0) : null);
+ }
+
+ public void addIncludedUrl(String includedUrl) {
+ Assert.notNull(includedUrl, "Included URL must not be null");
+ this.includedUrls.add(includedUrl);
+ }
+
+ public List<String> getIncludedUrls() {
+ return this.includedUrls;
}
diff --git a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
index 17485d21f381..a87bea43c91c 100644
--- a/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
+++ b/org.springframework.test/src/main/java/org/springframework/mock/web/MockRequestDispatcher.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,7 +68,7 @@ public void forward(ServletRequest request, ServletResponse response) {
public void include(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
- getMockHttpServletResponse(response).setIncludedUrl(this.url);
+ getMockHttpServletResponse(response).addIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
}
|
8dbd55da75fb5a06077011cdec31749fe27f03dd
|
duracloud$duracloud
|
DURACLOUD-303 - Added server configuration mode of standard/advanced to the bulk services. Advanced allows for the previous functionality of choosing the number and type of server instances. Standard allows the choice of "Optimize for Cost" and "Optimize for Speed"
git-svn-id: https://svn.duraspace.org/duracloud/trunk@304 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
|
p
|
https://github.com/duracloud/duracloud
|
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
index 6a149b550..769006959 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/AmazonFixityServiceInfo.java
@@ -12,6 +12,7 @@
import org.duracloud.serviceconfig.user.UserConfig;
import org.duracloud.serviceconfig.user.UserConfigMode;
import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import org.duracloud.storage.domain.HadoopTypes.INSTANCES;
/**
@@ -20,33 +21,6 @@
*/
public class AmazonFixityServiceInfo extends AbstractServiceInfo {
- protected enum ModeType {
- SERVICE_PROVIDES_BOTH_LISTS("all-in-one-for-list",
- "Verify integrity of a Space"),
- USER_PROVIDES_ONE_OF_LISTS("compare",
- "Verify integrity from an item list");
-
- private String key;
- private String desc;
-
- private ModeType(String key, String desc) {
- this.key = key;
- this.desc = desc;
- }
-
- public String toString() {
- return getKey();
- }
-
- protected String getKey() {
- return key;
- }
-
- protected String getDesc() {
- return desc;
- }
- }
-
@Override
public ServiceInfo getServiceXml(int index, String version) {
@@ -73,13 +47,13 @@ public ServiceInfo getServiceXml(int index, String version) {
private List<UserConfigModeSet> getModeSets() {
List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
- modes.add(getMode(ModeType.SERVICE_PROVIDES_BOTH_LISTS));
- modes.add(getMode(ModeType.USER_PROVIDES_ONE_OF_LISTS));
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
UserConfigModeSet modeSet = new UserConfigModeSet();
modeSet.setModes(modes);
- modeSet.setDisplayName("Service Mode");
- modeSet.setName("mode");
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
modeSets.add(modeSet);
@@ -87,64 +61,156 @@ private List<UserConfigModeSet> getModeSets() {
}
private UserConfigMode getMode(ModeType modeType) {
- List<UserConfig> userConfigs = new ArrayList<UserConfig>();
- userConfigs.add(getTargetSpace());
-
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
switch (modeType) {
- case SERVICE_PROVIDES_BOTH_LISTS:
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
break;
- case USER_PROVIDES_ONE_OF_LISTS:
- userConfigs.add(getSpaceOfProvidedListingSelection());
- userConfigs.add(getContentIdOfProvidedListingConfig());
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
break;
default:
throw new RuntimeException("Unexpected ModeType: " + modeType);
}
- userConfigs.addAll(getHadoopConfigs());
-
UserConfigMode mode = new UserConfigMode();
mode.setDisplayName(modeType.getDesc());
mode.setName(modeType.getKey());
mode.setUserConfigs(userConfigs);
- mode.setUserConfigModeSets(new ArrayList<UserConfigModeSet>());
+ mode.setUserConfigModeSets(getListModeSets());
return mode;
}
- private List<UserConfig> getHadoopConfigs() {
- List<UserConfig> userConfigs = new ArrayList<UserConfig>();
+ private List<UserConfig> getDefaultUserConfigs()
+ {
+ // User Configs
+ List<UserConfig> userConfig = new ArrayList<UserConfig>();
+
+ // Include all user configs
+ userConfig.add(getTargetSpace());
+
+ return userConfig;
+ }
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances = new SingleSelectUserConfig(
+
+ return new SingleSelectUserConfig(
"numInstances",
"Number of Server Instances",
numInstancesOptions);
+ }
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
+
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
// Instance type
List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option(INSTANCES.SMALL.getDescription(),
- INSTANCES.SMALL.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
true));
- instanceTypeOptions.add(new Option(INSTANCES.LARGE.getDescription(),
- INSTANCES.LARGE.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
false));
- instanceTypeOptions.add(new Option(INSTANCES.XLARGE.getDescription(),
- INSTANCES.XLARGE.getId(),
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
false));
- SingleSelectUserConfig instanceType = new SingleSelectUserConfig(
+ return new SingleSelectUserConfig(
"instanceType",
"Type of Server Instance",
instanceTypeOptions);
+ }
- userConfigs.add(numInstances);
- userConfigs.add(instanceType);
- return userConfigs;
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard"),
+ SERVICE_PROVIDES_BOTH_LISTS("all-in-one-for-list",
+ "Verify integrity of a Space"),
+ USER_PROVIDES_ONE_OF_LISTS("compare",
+ "Verify integrity from an item list");
+
+ private String key;
+ private String desc;
+
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
+
+ public String toString() {
+ return getKey();
+ }
+
+ protected String getKey() {
+ return key;
+ }
+
+ protected String getDesc() {
+ return desc;
+ }
+ }
+
+ private List<UserConfigModeSet> getListModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getListMode(ModeType.SERVICE_PROVIDES_BOTH_LISTS));
+ modes.add(getListMode(ModeType.USER_PROVIDES_ONE_OF_LISTS));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Service Mode");
+ modeSet.setName("mode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getListMode(ModeType modeType) {
+ List<UserConfig> userConfigs = new ArrayList<UserConfig>();
+
+ switch (modeType) {
+ case SERVICE_PROVIDES_BOTH_LISTS:
+ break;
+ case USER_PROVIDES_ONE_OF_LISTS:
+ userConfigs.add(getSpaceOfProvidedListingSelection());
+ userConfigs.add(getContentIdOfProvidedListingConfig());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(new ArrayList<UserConfigModeSet>());
+ return mode;
}
private TextUserConfig getContentIdOfProvidedListingConfig() {
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
index 208e20160..fe546c7e4 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/BulkImageConversionServiceInfo.java
@@ -7,6 +7,9 @@
import org.duracloud.serviceconfig.user.SingleSelectUserConfig;
import org.duracloud.serviceconfig.user.TextUserConfig;
import org.duracloud.serviceconfig.user.UserConfig;
+import org.duracloud.serviceconfig.user.UserConfigMode;
+import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import java.util.ArrayList;
import java.util.List;
@@ -37,6 +40,85 @@ public ServiceInfo getServiceXml(int index, String version) {
icService.setServiceVersion(version);
icService.setMaxDeploymentsAllowed(1);
+
+ icService.setUserConfigModeSets(getModeSets());
+
+ // System Configs
+ List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+
+ SystemConfig host = new SystemConfig("duraStoreHost",
+ ServiceConfigUtil.STORE_HOST_VAR,
+ "localhost");
+ SystemConfig port = new SystemConfig("duraStorePort",
+ ServiceConfigUtil.STORE_PORT_VAR,
+ "8080");
+ SystemConfig context = new SystemConfig("duraStoreContext",
+ ServiceConfigUtil.STORE_CONTEXT_VAR,
+ "durastore");
+ SystemConfig username = new SystemConfig("username",
+ ServiceConfigUtil.STORE_USER_VAR,
+ "no-username");
+ SystemConfig password = new SystemConfig("password",
+ ServiceConfigUtil.STORE_PWORD_VAR,
+ "no-password");
+ SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
+ "1",
+ "1");
+
+ systemConfig.add(host);
+ systemConfig.add(port);
+ systemConfig.add(context);
+ systemConfig.add(username);
+ systemConfig.add(password);
+ systemConfig.add(mappersPerInstance);
+
+ icService.setSystemConfigs(systemConfig);
+
+ icService.setDeploymentOptions(getSimpleDeploymentOptions());
+
+ return icService;
+ }
+
+ private List<UserConfigModeSet> getModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getMode(ModeType modeType) {
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
+ switch (modeType) {
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
+ break;
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(null);
+ return mode;
+ }
+
+ private List<UserConfig> getDefaultUserConfigs()
+ {
// User Configs
List<UserConfig> icServiceUserConfig = new ArrayList<UserConfig>();
@@ -106,73 +188,92 @@ public ServiceInfo getServiceXml(int index, String version) {
"with this value will be converted.",
"");
+ // Include all user configs
+ icServiceUserConfig.add(sourceSpace);
+ icServiceUserConfig.add(destSpace);
+ icServiceUserConfig.add(toFormat);
+ icServiceUserConfig.add(colorSpace);
+ icServiceUserConfig.add(namePrefix);
+ icServiceUserConfig.add(nameSuffix);
+
+ return icServiceUserConfig;
+ }
+
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
- for(int i = 1; i<20; i++) {
+ for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances =
- new SingleSelectUserConfig("numInstances",
- "Number of Server Instances",
- numInstancesOptions);
+ return new SingleSelectUserConfig(
+ "numInstances",
+ "Number of Server Instances",
+ numInstancesOptions);
+ }
+
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
+
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
// Instance type
List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option("Small Instance", "m1.small", true));
- instanceTypeOptions.add(new Option("Large Instance", "m1.large", false));
- instanceTypeOptions.add(
- new Option("Extra Large Instance", "m1.xlarge", false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
+ true));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
+ false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
+ false));
- SingleSelectUserConfig instanceType =
- new SingleSelectUserConfig("instanceType",
- "Type of Server Instance",
- instanceTypeOptions);
-
- // Include all user configs
- icServiceUserConfig.add(sourceSpace);
- icServiceUserConfig.add(destSpace);
- icServiceUserConfig.add(toFormat);
- icServiceUserConfig.add(colorSpace);
- icServiceUserConfig.add(namePrefix);
- icServiceUserConfig.add(nameSuffix);
- icServiceUserConfig.add(numInstances);
- icServiceUserConfig.add(instanceType);
- icService.setUserConfigModeSets(createDefaultModeSet(icServiceUserConfig));
+ return new SingleSelectUserConfig(
+ "instanceType",
+ "Type of Server Instance",
+ instanceTypeOptions);
+ }
- // System Configs
- List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard");
- SystemConfig host = new SystemConfig("duraStoreHost",
- ServiceConfigUtil.STORE_HOST_VAR,
- "localhost");
- SystemConfig port = new SystemConfig("duraStorePort",
- ServiceConfigUtil.STORE_PORT_VAR,
- "8080");
- SystemConfig context = new SystemConfig("duraStoreContext",
- ServiceConfigUtil.STORE_CONTEXT_VAR,
- "durastore");
- SystemConfig username = new SystemConfig("username",
- ServiceConfigUtil.STORE_USER_VAR,
- "no-username");
- SystemConfig password = new SystemConfig("password",
- ServiceConfigUtil.STORE_PWORD_VAR,
- "no-password");
- SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
- "1",
- "1");
+ private String key;
+ private String desc;
- systemConfig.add(host);
- systemConfig.add(port);
- systemConfig.add(context);
- systemConfig.add(username);
- systemConfig.add(password);
- systemConfig.add(mappersPerInstance);
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
- icService.setSystemConfigs(systemConfig);
+ public String toString() {
+ return getKey();
+ }
- icService.setDeploymentOptions(getSimpleDeploymentOptions());
+ protected String getKey() {
+ return key;
+ }
- return icService;
+ protected String getDesc() {
+ return desc;
+ }
}
}
diff --git a/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java b/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
index 90c863c16..064a7d8ff 100644
--- a/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
+++ b/duraservice/src/main/java/org/duracloud/duraservice/config/ReplicationOnDemandServiceInfo.java
@@ -7,6 +7,9 @@
import org.duracloud.serviceconfig.user.SingleSelectUserConfig;
import org.duracloud.serviceconfig.user.TextUserConfig;
import org.duracloud.serviceconfig.user.UserConfig;
+import org.duracloud.serviceconfig.user.UserConfigMode;
+import org.duracloud.serviceconfig.user.UserConfigModeSet;
+import org.duracloud.storage.domain.HadoopTypes;
import java.util.ArrayList;
import java.util.List;
@@ -38,7 +41,83 @@ public ServiceInfo getServiceXml(int index, String version) {
repService.setUserConfigVersion("1.0");
repService.setServiceVersion(version);
repService.setMaxDeploymentsAllowed(1);
+ repService.setUserConfigModeSets(getModeSets());
+ // System Configs
+ List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+
+ SystemConfig host = new SystemConfig("duraStoreHost",
+ ServiceConfigUtil.STORE_HOST_VAR,
+ "localhost");
+ SystemConfig port = new SystemConfig("duraStorePort",
+ ServiceConfigUtil.STORE_PORT_VAR,
+ "8080");
+ SystemConfig context = new SystemConfig("duraStoreContext",
+ ServiceConfigUtil.STORE_CONTEXT_VAR,
+ "durastore");
+ SystemConfig username = new SystemConfig("username",
+ ServiceConfigUtil.STORE_USER_VAR,
+ "no-username");
+ SystemConfig password = new SystemConfig("password",
+ ServiceConfigUtil.STORE_PWORD_VAR,
+ "no-password");
+ SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
+ "1",
+ "1");
+
+ systemConfig.add(host);
+ systemConfig.add(port);
+ systemConfig.add(context);
+ systemConfig.add(username);
+ systemConfig.add(password);
+ systemConfig.add(mappersPerInstance);
+
+ repService.setSystemConfigs(systemConfig);
+ repService.setDeploymentOptions(getSimpleDeploymentOptions());
+
+ return repService;
+ }
+
+ private List<UserConfigModeSet> getModeSets() {
+ List<UserConfigMode> modes = new ArrayList<UserConfigMode>();
+
+ modes.add(getMode(ModeType.OPTIMIZE_STANDARD));
+ modes.add(getMode(ModeType.OPTIMIZE_ADVANCED));
+
+ UserConfigModeSet modeSet = new UserConfigModeSet();
+ modeSet.setModes(modes);
+ modeSet.setDisplayName("Configuration");
+ modeSet.setName("optimizeMode");
+
+ List<UserConfigModeSet> modeSets = new ArrayList<UserConfigModeSet>();
+ modeSets.add(modeSet);
+ return modeSets;
+ }
+
+ private UserConfigMode getMode(ModeType modeType) {
+ List<UserConfig> userConfigs = getDefaultUserConfigs();
+ switch (modeType) {
+ case OPTIMIZE_ADVANCED:
+ userConfigs.add(getNumberOfInstancesSelection());
+ userConfigs.add(getTypeOfInstanceListingSelection());
+ break;
+ case OPTIMIZE_STANDARD:
+ userConfigs.add(getOptimizationSelection());
+ break;
+ default:
+ throw new RuntimeException("Unexpected ModeType: " + modeType);
+ }
+
+ UserConfigMode mode = new UserConfigMode();
+ mode.setDisplayName(modeType.getDesc());
+ mode.setName(modeType.getKey());
+ mode.setUserConfigs(userConfigs);
+ mode.setUserConfigModeSets(null);
+ return mode;
+ }
+
+ private List<UserConfig> getDefaultUserConfigs()
+ {
// User Configs
List<UserConfig> repServiceUserConfig = new ArrayList<UserConfig>();
@@ -55,7 +134,7 @@ public ServiceInfo getServiceXml(int index, String version) {
new Option("Stores", ServiceConfigUtil.STORES_VAR, false);
storeOptions.add(stores);
- SingleSelectUserConfig sourceSpace =
+ SingleSelectUserConfig sourceSpace =
new SingleSelectUserConfig("sourceSpaceId",
"Source Space",
spaceOptions);
@@ -68,71 +147,89 @@ public ServiceInfo getServiceXml(int index, String version) {
TextUserConfig repSpace =
new TextUserConfig("repSpaceId", "Copy to this space");
+ // Include all user configs
+ repServiceUserConfig.add(sourceSpace);
+ repServiceUserConfig.add(repStore);
+ repServiceUserConfig.add(repSpace);
+
+ return repServiceUserConfig;
+ }
+
+ private SingleSelectUserConfig getNumberOfInstancesSelection() {
// Number of instances
List<Option> numInstancesOptions = new ArrayList<Option>();
- for(int i = 1; i<20; i++) {
+ for (int i = 1; i < 20; i++) {
Option op = new Option(String.valueOf(i), String.valueOf(i), false);
numInstancesOptions.add(op);
}
- SingleSelectUserConfig numInstances =
- new SingleSelectUserConfig("numInstances",
- "Number of Server Instances",
- numInstancesOptions);
-
- // Instance type
- List<Option> instanceTypeOptions = new ArrayList<Option>();
- instanceTypeOptions.add(new Option("Small Instance", "m1.small", true));
- instanceTypeOptions.add(new Option("Large Instance", "m1.large", false));
- instanceTypeOptions.add(
- new Option("Extra Large Instance", "m1.xlarge", false));
- SingleSelectUserConfig instanceType =
- new SingleSelectUserConfig("instanceType",
- "Type of Server Instance",
- instanceTypeOptions);
+ return new SingleSelectUserConfig(
+ "numInstances",
+ "Number of Server Instances",
+ numInstancesOptions);
+ }
- // Include all user configs
- repServiceUserConfig.add(sourceSpace);
- repServiceUserConfig.add(repStore);
- repServiceUserConfig.add(repSpace);
- repServiceUserConfig.add(numInstances);
- repServiceUserConfig.add(instanceType);
+ private SingleSelectUserConfig getOptimizationSelection() {
+ List<Option> options = new ArrayList<Option>();
+ options.add(new Option("Optimize for cost",
+ "optimize_for_cost",
+ true));
+ options.add(new Option("Optimize for speed",
+ "optimize_for_speed",
+ false));
+
+ return new SingleSelectUserConfig(
+ "optimizeType",
+ "Optimize",
+ options);
+ }
- repService.setUserConfigModeSets(createDefaultModeSet(repServiceUserConfig));
+ private SingleSelectUserConfig getTypeOfInstanceListingSelection() {
+ // Instance type
+ List<Option> instanceTypeOptions = new ArrayList<Option>();
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .SMALL.getDescription(),
+ HadoopTypes.INSTANCES.SMALL.getId(),
+ true));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .LARGE.getDescription(),
+ HadoopTypes.INSTANCES.LARGE.getId(),
+ false));
+ instanceTypeOptions.add(new Option(HadoopTypes.INSTANCES
+ .XLARGE.getDescription(),
+ HadoopTypes.INSTANCES.XLARGE.getId(),
+ false));
+
+ return new SingleSelectUserConfig(
+ "instanceType",
+ "Type of Server Instance",
+ instanceTypeOptions);
+ }
- // System Configs
- List<SystemConfig> systemConfig = new ArrayList<SystemConfig>();
+ protected enum ModeType {
+ OPTIMIZE_ADVANCED("advanced",
+ "Advanced"),
+ OPTIMIZE_STANDARD("standard",
+ "Standard");
- SystemConfig host = new SystemConfig("duraStoreHost",
- ServiceConfigUtil.STORE_HOST_VAR,
- "localhost");
- SystemConfig port = new SystemConfig("duraStorePort",
- ServiceConfigUtil.STORE_PORT_VAR,
- "8080");
- SystemConfig context = new SystemConfig("duraStoreContext",
- ServiceConfigUtil.STORE_CONTEXT_VAR,
- "durastore");
- SystemConfig username = new SystemConfig("username",
- ServiceConfigUtil.STORE_USER_VAR,
- "no-username");
- SystemConfig password = new SystemConfig("password",
- ServiceConfigUtil.STORE_PWORD_VAR,
- "no-password");
- SystemConfig mappersPerInstance = new SystemConfig("mappersPerInstance",
- "1",
- "1");
+ private String key;
+ private String desc;
- systemConfig.add(host);
- systemConfig.add(port);
- systemConfig.add(context);
- systemConfig.add(username);
- systemConfig.add(password);
- systemConfig.add(mappersPerInstance);
+ private ModeType(String key, String desc) {
+ this.key = key;
+ this.desc = desc;
+ }
- repService.setSystemConfigs(systemConfig);
+ public String toString() {
+ return getKey();
+ }
- repService.setDeploymentOptions(getSimpleDeploymentOptions());
+ protected String getKey() {
+ return key;
+ }
- return repService;
+ protected String getDesc() {
+ return desc;
+ }
}
}
diff --git a/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java b/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
index 0d4b75853..a70eb8a52 100644
--- a/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
+++ b/duraservice/src/test/java/org/duracloud/duraservice/config/ServiceXmlGeneratorTest.java
@@ -203,9 +203,13 @@ private void verifyFixityTools(ServiceInfo serviceInfo) {
}
private void verifyBulkImageconversion(ServiceInfo serviceInfo) {
- int numUserConfigs = 8;
+ int numUserConfigs = 0;
int numSystemConfigs = 6;
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
+
+ List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
+ setsModesConfigs.add(Arrays.asList(7,8));
+ verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyAmazonFixity(ServiceInfo serviceInfo) {
@@ -214,14 +218,18 @@ private void verifyAmazonFixity(ServiceInfo serviceInfo) {
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
- setsModesConfigs.add(Arrays.asList(3, 5));
+ setsModesConfigs.add(Arrays.asList(2, 3));
verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyRepOnDemand(ServiceInfo serviceInfo) {
- int numUserConfigs = 5;
+ int numUserConfigs = 0;
int numSystemConfigs = 6;
verifyServiceInfo(numUserConfigs, numSystemConfigs, serviceInfo);
+
+ List<List<Integer>> setsModesConfigs = new ArrayList<List<Integer>>();
+ setsModesConfigs.add(Arrays.asList(4,5));
+ verifyServiceModes(setsModesConfigs, serviceInfo);
}
private void verifyServiceInfo(int numUserConfigs,
diff --git a/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java b/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
index 7f8e0a592..47234d373 100644
--- a/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
+++ b/services/amazonfixityservice/src/main/java/org/duracloud/services/amazonfixity/AmazonFixityService.java
@@ -37,6 +37,14 @@ public class AmazonFixityService extends BaseAmazonMapReduceService implements M
private String providedListingSpaceIdB;
private String providedListingContentIdB;
private String mode;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
@Override
protected AmazonMapReduceJobWorker getJobWorker() {
@@ -131,6 +139,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
public String getProvidedListingSpaceIdB() {
return providedListingSpaceIdB;
}
@@ -154,4 +194,92 @@ public String getMode() {
public void setMode(String mode) {
this.mode = mode;
}
+
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
}
diff --git a/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml b/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
index abd17d931..ffb37c98a 100644
--- a/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/amazonfixityservice/src/main/resources/META-INF/spring/bundle-context.xml
@@ -15,6 +15,10 @@
<property name="serviceId" value="amazonfixityservice-${project.version}" />
<property name="destSpaceId" value="${service.output.spaceid}"/>
<property name="workSpaceId" value="${service.work.spaceid}"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.small"/>
+ <property name="speedNumInstances" value="10"/>
+ <property name="speedInstanceType" value="m1.xlarge"/>
</bean>
</beans>
diff --git a/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java b/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
index caab9516e..eb558f54f 100644
--- a/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
+++ b/services/amazonfixityservice/src/test/java/org/duracloud/services/amazonfixity/AmazonFixityServiceTest.java
@@ -25,6 +25,7 @@
import java.util.HashMap;
import java.util.Map;
+import static junit.framework.Assert.assertEquals;
import static org.duracloud.storage.domain.HadoopTypes.RUN_HADOOP_TASK_NAME;
import static org.duracloud.storage.domain.HadoopTypes.TASK_OUTPUTS;
import static org.duracloud.storage.domain.HadoopTypes.JOB_TYPES;
@@ -69,6 +70,30 @@ private void verifyNumMappers(String num, String expected) {
Assert.assertEquals(expected, num);
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ AmazonFixityService service = new AmazonFixityService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testStart() throws Exception {
setUpStart();
@@ -93,6 +118,8 @@ private void sleep(long millis) {
private void setUpStart() throws Exception {
service.setWorkSpaceId("work-space-id");
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_cost");
contentStore = createMockContentStore();
service.setContentStore(contentStore);
diff --git a/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java b/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
index 00205b3bb..8bababa78 100644
--- a/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
+++ b/services/amazonmapreduce-servicescommon/src/main/java/org/duracloud/services/amazonmapreduce/BaseAmazonMapReduceService.java
@@ -47,10 +47,14 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
private static final String DEFAULT_DURASTORE_PORT = "8080";
private static final String DEFAULT_DURASTORE_CONTEXT = "durastore";
private static final String DEFAULT_SOURCE_SPACE_ID = "service-source";
- private static final String DEFAULT_NUM_INSTANCES = "1";
- private static final String DEFAULT_INSTANCE_TYPE = SMALL.getId();
+ protected static final String DEFAULT_NUM_INSTANCES = "1";
+ protected static final String DEFAULT_INSTANCE_TYPE = SMALL.getId();
protected static final String DEFAULT_NUM_MAPPERS = "1";
+ protected static final String OPTIMIZE_MODE_STANDARD = "standard";
+ protected static final String OPTIMIZE_COST = "optimize_for_cost";
+ protected static final String OPTIMIZE_SPEED = "optimize_for_speed";
+
private String duraStoreHost;
private String duraStorePort;
private String duraStoreContext;
@@ -59,8 +63,6 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
private String sourceSpaceId;
private String destSpaceId;
private String workSpaceId;
- private String numInstances;
- private String instanceType;
private String mappersPerInstance;
private ContentStore contentStore;
@@ -73,6 +75,10 @@ public abstract class BaseAmazonMapReduceService extends BaseService implements
protected abstract String getNumMappers(String instanceType);
+ protected abstract String getInstancesType();
+
+ protected abstract String getNumOfInstances();
+
@Override
public void start() throws Exception {
log.info("Starting " + getServiceId() + " as " + username);
@@ -98,11 +104,11 @@ protected Map<String, String> collectTaskParams() {
taskParams.put(TASK_PARAMS.WORKSPACE_ID.name(), workSpaceId);
taskParams.put(TASK_PARAMS.SOURCE_SPACE_ID.name(), sourceSpaceId);
taskParams.put(TASK_PARAMS.DEST_SPACE_ID.name(), destSpaceId);
- taskParams.put(TASK_PARAMS.INSTANCE_TYPE.name(), instanceType);
- taskParams.put(TASK_PARAMS.NUM_INSTANCES.name(), numInstances);
+ taskParams.put(TASK_PARAMS.INSTANCE_TYPE.name(), getInstancesType());
+ taskParams.put(TASK_PARAMS.NUM_INSTANCES.name(), getNumOfInstances());
taskParams.put(TASK_PARAMS.MAPPERS_PER_INSTANCE.name(), getNumMappers(
- instanceType));
+ getInstancesType()));
taskParams.put(TASK_PARAMS.DC_HOST.name(), getDuraStoreHost());
taskParams.put(TASK_PARAMS.DC_PORT.name(), getDuraStorePort());
@@ -284,45 +290,6 @@ public void setWorkSpaceId(String workSpaceId) {
this.workSpaceId = workSpaceId;
}
- public String getNumInstances() {
- return numInstances;
- }
-
- public void setNumInstances(String numInstances) {
- if (numInstances != null && !numInstances.equals("")) {
- try {
- Integer.valueOf(numInstances);
- this.numInstances = numInstances;
- } catch (NumberFormatException e) {
- log("Attempt made to set numInstances to a non-numerical " +
- "value, which is not valid. Setting value to default: " +
- DEFAULT_NUM_INSTANCES);
- this.numInstances = DEFAULT_NUM_INSTANCES;
- }
- } else {
- log("Attempt made to set numInstances to to null or empty, " +
- ", which is not valid. Setting value to default: " +
- DEFAULT_NUM_INSTANCES);
- this.numInstances = DEFAULT_NUM_INSTANCES;
- }
- }
-
- public String getInstanceType() {
- return instanceType;
- }
-
- public void setInstanceType(String instanceType) {
-
- if (instanceType != null && !instanceType.equals("")) {
- this.instanceType = instanceType;
- } else {
- log("Attempt made to set typeOfInstance to null or empty, " +
- ", which is not valid. Setting value to default: " +
- DEFAULT_INSTANCE_TYPE);
- this.instanceType = DEFAULT_INSTANCE_TYPE;
- }
- }
-
public String getMappersPerInstance() {
return mappersPerInstance;
}
diff --git a/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java b/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
index 26e7ce684..c35698d16 100644
--- a/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
+++ b/services/bulkimageconversionservice/src/main/java/org/duracloud/services/bulkimageconversion/BulkImageConversionService.java
@@ -42,6 +42,14 @@ public class BulkImageConversionService extends BaseAmazonMapReduceService imple
private String colorSpace;
private String namePrefix;
private String nameSuffix;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
private AmazonMapReduceJobWorker worker;
private AmazonMapReduceJobWorker postWorker;
@@ -84,6 +92,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
@Override
protected Map<String, String> collectTaskParams() {
Map<String, String> taskParams = super.collectTaskParams();
@@ -168,6 +208,94 @@ public void setNameSuffix(String nameSuffix) {
}
}
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
+
private void log(String logMsg) {
log.warn(logMsg);
}
diff --git a/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml b/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
index 02f08aa9b..496cbb2eb 100644
--- a/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/bulkimageconversionservice/src/main/resources/META-INF/spring/bundle-context.xml
@@ -23,8 +23,10 @@
<property name="workSpaceId" value="${service.work.spaceid}"/>
<property name="namePrefix" value=""/>
<property name="nameSuffix" value=""/>
- <property name="numInstances" value="1"/>
- <property name="instanceType" value="m1.small"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.large"/>
+ <property name="speedNumInstances" value="10"/>
+ <property name="speedInstanceType" value="m1.xlarge"/>
<property name="mappersPerInstance" value="1"/>
</bean>
diff --git a/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java b/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
index b0124f5dd..03a542e3e 100644
--- a/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
+++ b/services/bulkimageconversionservice/src/test/java/org/duracloud/services/bulkimageconversion/BulkImageConversionServiceTest.java
@@ -33,6 +33,7 @@ public void testCollectTaskParams() {
service.setNamePrefix("test-");
service.setNameSuffix("-test");
service.setColorSpace("sRGB");
+ service.setOptimizeMode("advanced");
service.setInstanceType("c1.xlarge");
service.setNumInstances("8");
@@ -130,6 +131,30 @@ public void testBulkImageConversionParameters() {
assertEquals("8", service.getMappersPerInstance());
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ BulkImageConversionService service = new BulkImageConversionService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testGetNumMappers() {
BulkImageConversionService service = new BulkImageConversionService();
diff --git a/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java b/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
index 04611342f..134d059be 100644
--- a/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
+++ b/services/replication-on-demand-service/src/main/java/org/duracloud/services/replicationod/ReplicationOnDemandService.java
@@ -36,6 +36,14 @@ public class ReplicationOnDemandService extends BaseAmazonMapReduceService imple
private String repStoreId;
private String repSpaceId;
+ private String optimizeMode;
+ private String optimizeType;
+ private String numInstances;
+ private String instanceType;
+ private String costNumInstances;
+ private String costInstanceType;
+ private String speedNumInstances;
+ private String speedInstanceType;
private ReplicationOnDemandJobWorker worker;
@@ -85,6 +93,38 @@ protected String getNumMappers(String instanceType) {
return mappers;
}
+ @Override
+ protected String getInstancesType() {
+ String instanceType = getInstanceType();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ instanceType = getCostInstanceType();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ instanceType = getSpeedInstanceType();
+ }
+ }
+
+ return instanceType;
+ }
+
+ @Override
+ protected String getNumOfInstances() {
+ String numOfInstances = getNumInstances();
+
+ if(getOptimizeMode().equals(OPTIMIZE_MODE_STANDARD)) {
+ if(getOptimizeType().equals(OPTIMIZE_COST)) {
+ numOfInstances = getCostNumInstances();
+ }
+ else if(getOptimizeType().equals(OPTIMIZE_SPEED)) {
+ numOfInstances = getSpeedNumInstances();
+ }
+ }
+
+ return numOfInstances;
+ }
+
@Override
protected Map<String, String> collectTaskParams() {
Map<String, String> taskParams = super.collectTaskParams();
@@ -130,6 +170,94 @@ public void setRepSpaceId(String repSpaceId) {
}
}
+ public String getOptimizeMode() {
+ return optimizeMode;
+ }
+
+ public void setOptimizeMode(String optimizeMode) {
+ this.optimizeMode = optimizeMode;
+ }
+
+ public String getNumInstances() {
+ return numInstances;
+ }
+
+ public void setNumInstances(String numInstances) {
+ if (numInstances != null && !numInstances.equals("")) {
+ try {
+ Integer.valueOf(numInstances);
+ this.numInstances = numInstances;
+ } catch (NumberFormatException e) {
+ log.warn(
+ "Attempt made to set numInstances to a non-numerical " +
+ "value, which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ } else {
+ log.warn("Attempt made to set numInstances to to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_NUM_INSTANCES);
+ this.numInstances = DEFAULT_NUM_INSTANCES;
+ }
+ }
+
+ public String getInstanceType() {
+ return instanceType;
+ }
+
+ public void setInstanceType(String instanceType) {
+
+ if (instanceType != null && !instanceType.equals("")) {
+ this.instanceType = instanceType;
+ } else {
+ log.warn("Attempt made to set typeOfInstance to null or empty, " +
+ ", which is not valid. Setting value to default: " +
+ DEFAULT_INSTANCE_TYPE);
+ this.instanceType = DEFAULT_INSTANCE_TYPE;
+ }
+ }
+
+ public String getOptimizeType() {
+ return optimizeType;
+ }
+
+ public void setOptimizeType(String optimizeType) {
+ this.optimizeType = optimizeType;
+ }
+
+ public String getCostNumInstances() {
+ return costNumInstances;
+ }
+
+ public void setCostNumInstances(String costNumInstances) {
+ this.costNumInstances = costNumInstances;
+ }
+
+ public String getCostInstanceType() {
+ return costInstanceType;
+ }
+
+ public void setCostInstanceType(String costInstanceType) {
+ this.costInstanceType = costInstanceType;
+ }
+
+ public String getSpeedNumInstances() {
+ return speedNumInstances;
+ }
+
+ public void setSpeedNumInstances(String speedNumInstances) {
+ this.speedNumInstances = speedNumInstances;
+ }
+
+ public String getSpeedInstanceType() {
+ return speedInstanceType;
+ }
+
+ public void setSpeedInstanceType(String speedInstanceType) {
+ this.speedInstanceType = speedInstanceType;
+ }
+
private void log(String logMsg) {
log.warn(logMsg);
}
diff --git a/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml b/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
index 86fdcef1d..c1c37ab13 100644
--- a/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
+++ b/services/replication-on-demand-service/src/main/resources/META-INF/spring/bundle-context.xml
@@ -23,8 +23,10 @@
<property name="repSpaceId" value="replication-space"/>
<property name="destSpaceId" value="${service.output.spaceid}"/>
<property name="workSpaceId" value="${service.work.spaceid}"/>
- <property name="numInstances" value="1"/>
- <property name="instanceType" value="m1.small"/>
+ <property name="costNumInstances" value="3"/>
+ <property name="costInstanceType" value="m1.small"/>
+ <property name="speedNumInstances" value="5"/>
+ <property name="speedInstanceType" value="m1.large"/>
<property name="mappersPerInstance" value="1"/>
</bean>
diff --git a/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java b/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
index 06bc11e85..f99193f70 100644
--- a/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
+++ b/services/replication-on-demand-service/src/test/java/org/duracloud/services/replicationod/ReplicationOnDemandServiceTest.java
@@ -30,6 +30,7 @@ public void testCollectTaskParams() {
String repStoreId = "0";
String repSpaceId = "rep-space";
String destSpaceId = "test-dest";
+ String optimizeMode = "advanced";
String instanceType = "c1.xlarge";
String numInstances = "8";
String dcHost = "dchost";
@@ -44,6 +45,7 @@ public void testCollectTaskParams() {
service.setRepStoreId(repStoreId);
service.setRepSpaceId(repSpaceId);
service.setDestSpaceId(destSpaceId);
+ service.setOptimizeMode(optimizeMode);
service.setInstanceType(instanceType);
service.setNumInstances(numInstances);
service.setDuraStoreHost(dcHost);
@@ -138,6 +140,30 @@ public void testReplicationOnDemandParameters() {
assertEquals("8", service.getMappersPerInstance());
}
+ @Test
+ public void testOptmizationConfig() {
+ String instanceType = "m1.xlarge";
+ String numOfInstances = "10";
+
+ ReplicationOnDemandService service = new ReplicationOnDemandService();
+ service.setOptimizeMode("standard");
+ service.setOptimizeType("optimize_for_speed");
+ service.setSpeedInstanceType(instanceType);
+ service.setSpeedNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+
+ instanceType = "m1.large";
+ numOfInstances = "3";
+ service.setOptimizeType("optimize_for_cost");
+ service.setSpeedInstanceType(null);
+ service.setSpeedNumInstances(null);
+ service.setCostInstanceType(instanceType);
+ service.setCostNumInstances(numOfInstances);
+ assertEquals(instanceType,service.getInstancesType());
+ assertEquals(numOfInstances,service.getNumOfInstances());
+ }
+
@Test
public void testGetNumMappers() {
ReplicationOnDemandService service = new ReplicationOnDemandService();
|
5dbf97fd3d868f6db605fcf3b1a82bb55c47fed1
|
drools
|
[BZ-1042867] fix ProjectClassLoader when running in- osgi--
|
c
|
https://github.com/kiegroup/drools
|
diff --git a/drools-core/src/main/java/org/drools/core/common/ProjectClassLoader.java b/drools-core/src/main/java/org/drools/core/common/ProjectClassLoader.java
index 51c0ad48c57..aacc316afcb 100644
--- a/drools-core/src/main/java/org/drools/core/common/ProjectClassLoader.java
+++ b/drools-core/src/main/java/org/drools/core/common/ProjectClassLoader.java
@@ -68,15 +68,11 @@ private static ProjectClassLoader internalCreate(ClassLoader parent) {
public static ClassLoader getClassLoader(final ClassLoader classLoader,
final Class< ? > cls,
final boolean enableCache) {
- if (classLoader == null) {
- return cls == null ? createProjectClassLoader() : createProjectClassLoader(cls.getClassLoader());
- } else {
- ProjectClassLoader projectClassLoader = createProjectClassLoader(classLoader);
- if (cls != null) {
- projectClassLoader.setDroolsClassLoader(cls.getClassLoader());
- }
- return projectClassLoader;
+ ProjectClassLoader projectClassLoader = createProjectClassLoader(classLoader);
+ if (cls != null) {
+ projectClassLoader.setDroolsClassLoader(cls.getClassLoader());
}
+ return projectClassLoader;
}
public static ProjectClassLoader createProjectClassLoader() {
|
b3a51c94ab0a44a22874fc835c772a26abaaebd3
|
Mylyn Reviews
|
Merge branch 'master' of git://git.eclipse.org/gitroot/mylyn/org.eclipse.mylyn.reviews
|
p
|
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
|
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritConnector.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritConnector.java
index dd69ca7f..6d34e8ab 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritConnector.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritConnector.java
@@ -161,10 +161,13 @@ public IStatus performQuery(TaskRepository repository, IRepositoryQuery query, T
monitor.beginTask("Executing query", IProgressMonitor.UNKNOWN);
GerritClient client = getClient(repository);
List<ChangeInfo> result = null;
- if (GerritQuery.ALL_OPEN_CHANGES.equals(query.getAttribute("gerrit query type"))) {
+ if (GerritQuery.ALL_OPEN_CHANGES.equals(query.getAttribute(GerritQuery.TYPE))) {
result = client.queryAllReviews(monitor);
- } else if (GerritQuery.MY_OPEN_CHANGES.equals(query.getAttribute("gerrit query type"))) {
+ } else if (GerritQuery.MY_OPEN_CHANGES.equals(query.getAttribute(GerritQuery.TYPE))) {
result = client.queryMyReviews(monitor);
+ } else if (GerritQuery.OPEN_CHANGES_BY_PROJECT.equals(query.getAttribute(GerritQuery.TYPE))) {
+ String project = query.getAttribute(GerritQuery.PROJECT);
+ result = client.queryByProject(monitor, project);
}
if (result != null) {
@@ -177,7 +180,7 @@ public IStatus performQuery(TaskRepository repository, IRepositoryQuery query, T
return Status.OK_STATUS;
} else {
return new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, NLS.bind("Unknows query type: {0}",
- query.getAttribute("gerrit query type")));
+ query.getAttribute(GerritQuery.PROJECT)));
}
} catch (GerritException e) {
return toStatus(repository, e);
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritQuery.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritQuery.java
index 63bcd585..a5936b5a 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritQuery.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/GerritQuery.java
@@ -33,4 +33,14 @@ public class GerritQuery {
*/
public static final String ALL_OPEN_CHANGES = "all open changes";
+ /**
+ * query type: all open changes
+ */
+ public static final String OPEN_CHANGES_BY_PROJECT = "open changes by project"; //$NON-NLS-1$
+
+ /**
+ * Key for the project attribute
+ */
+ public static final String PROJECT = "gerrit query project"; //$NON-NLS-1$
+
}
diff --git a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
index e38ba565..786bfe0e 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.core/src/org/eclipse/mylyn/internal/gerrit/core/client/GerritClient.java
@@ -174,10 +174,21 @@ public int id(String id) throws GerritException {
* Returns the latest 25 reviews.
*/
public List<ChangeInfo> queryAllReviews(IProgressMonitor monitor) throws GerritException {
+ return executeQuery(monitor, "status:open"); //$NON-NLS-1$
+ }
+
+ /**
+ * Returns the latest 25 reviews for the given project.
+ */
+ public List<ChangeInfo> queryByProject(IProgressMonitor monitor, final String project) throws GerritException {
+ return executeQuery(monitor, "status:open project:" + project); //$NON-NLS-1$
+ }
+
+ private List<ChangeInfo> executeQuery(IProgressMonitor monitor, final String queryString) throws GerritException {
SingleListChangeInfo sl = execute(monitor, new GerritOperation<SingleListChangeInfo>() {
@Override
public void execute(IProgressMonitor monitor) throws GerritException {
- getChangeListService().allQueryNext("status:open", "z", 25, this);
+ getChangeListService().allQueryNext(queryString, "z", 25, this); //$NON-NLS-1$
}
});
return sl.getChanges();
diff --git a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java
index 72cb44df..32074577 100644
--- a/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java
+++ b/gerrit/org.eclipse.mylyn.gerrit.ui/src/org/eclipse/mylyn/internal/gerrit/ui/wizards/GerritCustomQueryPage.java
@@ -17,6 +17,8 @@
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
@@ -36,8 +38,12 @@ public class GerritCustomQueryPage extends AbstractRepositoryQueryPage {
private Button allOpenChangesButton;
+ private Button byProjectButton;
+
private Text titleText;
+ private Text projectText;
+
/**
* Constructor.
*
@@ -58,14 +64,7 @@ public void createControl(Composite parent) {
GridLayout layout = new GridLayout(3, false);
control.setLayout(layout);
- Label titleLabel = new Label(control, SWT.NONE);
- titleLabel.setText("Query Title :");
-
- titleText = new Text(control, SWT.BORDER);
- GridData gd2 = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
- gd2.horizontalSpan = 2;
- titleText.setLayoutData(gd2);
- titleText.addKeyListener(new KeyListener() {
+ KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
// ignore
}
@@ -73,32 +72,75 @@ public void keyPressed(KeyEvent e) {
public void keyReleased(KeyEvent e) {
getContainer().updateButtons();
}
- });
+ };
+
+ Label titleLabel = new Label(control, SWT.NONE);
+ titleLabel.setText("Query Title:");
+
+ titleText = new Text(control, SWT.BORDER);
+ GridData gd2 = new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
+ gd2.horizontalSpan = 2;
+ titleText.setLayoutData(gd2);
+ titleText.addKeyListener(keyListener);
Label typeLabel = new Label(control, SWT.NONE);
- typeLabel.setText("Query type :");
+ typeLabel.setText("Query type:");
// radio button to select query type
myOpenChangesButton = new Button(control, SWT.RADIO);
myOpenChangesButton.setText("My open changes");
+ myOpenChangesButton.setLayoutData(gd2);
+ new Label(control, SWT.NONE);
allOpenChangesButton = new Button(control, SWT.RADIO);
allOpenChangesButton.setText("All open changes");
+ allOpenChangesButton.setLayoutData(gd2);
+
+ new Label(control, SWT.NONE);
+ byProjectButton = new Button(control, SWT.RADIO);
+ byProjectButton.setText("Open changes by project");
+
+ projectText = new Text(control, SWT.BORDER);
+ projectText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));
+ projectText.addKeyListener(keyListener);
if (query != null) {
titleText.setText(query.getSummary());
if (GerritQuery.MY_OPEN_CHANGES.equals(query.getAttribute(GerritQuery.TYPE))) {
myOpenChangesButton.setSelection(true);
+ } else if (GerritQuery.OPEN_CHANGES_BY_PROJECT.equals(query.getAttribute(GerritQuery.TYPE))) {
+ byProjectButton.setSelection(true);
} else {
allOpenChangesButton.setSelection(true);
}
+ if (query.getAttribute(GerritQuery.PROJECT) != null) {
+ projectText.setText(query.getAttribute(GerritQuery.PROJECT));
+ }
+ } else {
+ myOpenChangesButton.setSelection(true);
}
+ SelectionListener buttonSelectionListener = new SelectionListener() {
+ public void widgetSelected(SelectionEvent e) {
+ projectText.setEnabled(byProjectButton.getSelection());
+ getContainer().updateButtons();
+ }
+
+ public void widgetDefaultSelected(SelectionEvent e) {
+ }
+ };
+ buttonSelectionListener.widgetSelected(null);
+ byProjectButton.addSelectionListener(buttonSelectionListener);
+
setControl(control);
}
@Override
public boolean isPageComplete() {
- return (titleText != null && titleText.getText().length() > 0);
+ boolean ret = (titleText != null && titleText.getText().length() > 0);
+ if (byProjectButton != null && byProjectButton.getSelection()) {
+ ret &= (projectText != null && projectText.getText().length() > 0);
+ }
+ return ret;
}
@Override
@@ -106,8 +148,14 @@ public void applyTo(IRepositoryQuery query) {
// TODO: set URL ????
// query.setUrl(getQueryUrl());
query.setSummary(getTitleText());
- query.setAttribute(GerritQuery.TYPE, myOpenChangesButton.getSelection() ? GerritQuery.MY_OPEN_CHANGES
- : GerritQuery.ALL_OPEN_CHANGES);
+ if (myOpenChangesButton.getSelection()) {
+ query.setAttribute(GerritQuery.TYPE, GerritQuery.MY_OPEN_CHANGES);
+ } else if (byProjectButton.getSelection()) {
+ query.setAttribute(GerritQuery.TYPE, GerritQuery.OPEN_CHANGES_BY_PROJECT);
+ } else {
+ query.setAttribute(GerritQuery.TYPE, GerritQuery.ALL_OPEN_CHANGES);
+ }
+ query.setAttribute(GerritQuery.PROJECT, projectText.getText());
}
private String getTitleText() {
|
b2107efb3355d921350058e3caaede813cc7795c
|
restlet-framework-java
|
Updated to Scripturian 1.0RC3--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/libraries/com.threecrickets.scripturian_1.0/com.threecrickets.scripturian.jar b/libraries/com.threecrickets.scripturian_1.0/com.threecrickets.scripturian.jar
index f6e8ed4ad4..25d47aece3 100644
Binary files a/libraries/com.threecrickets.scripturian_1.0/com.threecrickets.scripturian.jar and b/libraries/com.threecrickets.scripturian_1.0/com.threecrickets.scripturian.jar differ
diff --git a/modules/org.restlet.ext.script/src/org/restlet/ext/script/ScriptedTextRepresentation.java b/modules/org.restlet.ext.script/src/org/restlet/ext/script/ScriptedTextRepresentation.java
index 2b6a8178aa..03b70ca8dc 100644
--- a/modules/org.restlet.ext.script/src/org/restlet/ext/script/ScriptedTextRepresentation.java
+++ b/modules/org.restlet.ext.script/src/org/restlet/ext/script/ScriptedTextRepresentation.java
@@ -33,10 +33,7 @@
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
@@ -47,6 +44,7 @@
import org.restlet.representation.WriterRepresentation;
import com.threecrickets.scripturian.EmbeddedScript;
+import com.threecrickets.scripturian.EmbeddedScriptContext;
import com.threecrickets.scripturian.ScriptContextController;
/**
@@ -181,11 +179,11 @@ public void setScriptContextController(
@Override
public void write(Writer writer) throws IOException {
try {
- ConcurrentMap<String, ScriptEngine> scriptEngines = new ConcurrentHashMap<String, ScriptEngine>();
- this.embeddedScript.run(writer, this.errorWriter, false,
- scriptEngines,
+ this.embeddedScript.run(false, writer, this.errorWriter, false,
+ new EmbeddedScriptContext(this.embeddedScript
+ .getScriptEngineManager()),
new ExposedScriptedTextRepresentationContainer(this),
- getScriptContextController(), false);
+ getScriptContextController());
} catch (ScriptException e) {
IOException ioe = new IOException("Script exception");
ioe.initCause(e);
diff --git a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedResourceContainer.java b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedResourceContainer.java
index 91e416a5ff..93fd12a932 100644
--- a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedResourceContainer.java
+++ b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedResourceContainer.java
@@ -34,10 +34,7 @@
import java.io.IOException;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.restlet.data.CharacterSet;
@@ -51,6 +48,7 @@
import org.restlet.resource.ResourceException;
import com.threecrickets.scripturian.EmbeddedScript;
+import com.threecrickets.scripturian.EmbeddedScriptContext;
import com.threecrickets.scripturian.ScriptContextController;
import com.threecrickets.scripturian.ScriptSource;
@@ -104,9 +102,9 @@ public class ExposedScriptedResourceContainer {
private Language language;
/**
- * A cache of script engines used by {@link EmbeddedScript}.
+ * The embedded script context.
*/
- private final ConcurrentMap<String, ScriptEngine> scriptEngines = new ConcurrentHashMap<String, ScriptEngine>();
+ private final EmbeddedScriptContext embeddedScriptContext;
/**
* Constructs a container with no variant or entity, plain text media type,
@@ -125,6 +123,8 @@ public ExposedScriptedResourceContainer(ScriptedResource resource,
this.entity = null;
this.mediaType = MediaType.TEXT_PLAIN;
this.characterSet = resource.getDefaultCharacterSet();
+ this.embeddedScriptContext = new EmbeddedScriptContext(resource
+ .getScriptEngineManager());
}
/**
@@ -152,6 +152,8 @@ public ExposedScriptedResourceContainer(ScriptedResource resource,
if (this.characterSet == null) {
this.characterSet = resource.getDefaultCharacterSet();
}
+ this.embeddedScriptContext = new EmbeddedScriptContext(resource
+ .getScriptEngineManager());
}
/**
@@ -177,6 +179,8 @@ public ExposedScriptedResourceContainer(ScriptedResource resource,
if (this.characterSet == null) {
this.characterSet = resource.getDefaultCharacterSet();
}
+ this.embeddedScriptContext = new EmbeddedScriptContext(resource
+ .getScriptEngineManager());
}
/**
@@ -335,9 +339,9 @@ public void include(String name, String scriptEngineName)
scriptDescriptor.setScriptIfAbsent(script);
}
- script.run(this.resource.getWriter(), this.resource.getErrorWriter(),
- true, this.scriptEngines, this, this.resource
- .getScriptContextController(), false);
+ script.run(false, this.resource.getWriter(), this.resource
+ .getErrorWriter(), true, this.embeddedScriptContext, this,
+ this.resource.getScriptContextController());
}
/**
@@ -369,9 +373,9 @@ public Object invoke(String entryPointName) throws ResourceException {
if (existing != null) {
script = existing;
}
- script.run(this.resource.getWriter(), this.resource
- .getErrorWriter(), true, this.scriptEngines, this,
- this.resource.getScriptContextController(), false);
+ script.run(false, this.resource.getWriter(), this.resource
+ .getErrorWriter(), true, this.embeddedScriptContext,
+ this, this.resource.getScriptContextController());
}
return script.invoke(entryPointName, this, this.resource
diff --git a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedTextResourceContainer.java b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedTextResourceContainer.java
index 2afd553d1d..b9a0816d2e 100644
--- a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedTextResourceContainer.java
+++ b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ExposedScriptedTextResourceContainer.java
@@ -34,10 +34,8 @@
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
-import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.restlet.data.CharacterSet;
@@ -51,6 +49,7 @@
import org.restlet.representation.Variant;
import com.threecrickets.scripturian.EmbeddedScript;
+import com.threecrickets.scripturian.EmbeddedScriptContext;
import com.threecrickets.scripturian.ScriptSource;
/**
@@ -111,9 +110,9 @@ public class ExposedScriptedTextResourceContainer {
private StringBuffer buffer;
/**
- * A cache of script engines used by {@link EmbeddedScript}.
+ * The embedded script context.
*/
- private final ConcurrentMap<String, ScriptEngine> scriptEngines = new ConcurrentHashMap<String, ScriptEngine>();
+ private final EmbeddedScriptContext embeddedScriptContext;
/**
* Constructs a container with media type and character set according to the
@@ -137,6 +136,8 @@ public ExposedScriptedTextResourceContainer(ScriptedTextResource resource,
if (this.characterSet == null) {
this.characterSet = resource.getDefaultCharacterSet();
}
+ this.embeddedScriptContext = new EmbeddedScriptContext(resource
+ .getScriptEngineManager());
}
/**
@@ -322,9 +323,10 @@ public Representation include(String name, String scriptEngineName)
try {
// Do not allow caching in streaming mode
- if (script.run(writer, this.resource.getErrorWriter(), false,
- this.scriptEngines, this, this.resource
- .getScriptContextController(), !isStreaming)) {
+ if (script.run(!isStreaming, writer,
+ this.resource.getErrorWriter(), false,
+ this.embeddedScriptContext, this, this.resource
+ .getScriptContextController())) {
// Did the script ask us to start streaming?
if (this.startStreaming) {
@@ -332,7 +334,7 @@ public Representation include(String name, String scriptEngineName)
// Note that this will cause the script to run again!
return new ScriptedTextStreamingRepresentation(
- this.resource, this, this.scriptEngines,
+ this.resource, this, this.embeddedScriptContext,
this.resource.getScriptContextController(), script,
this.flushLines);
}
@@ -379,7 +381,7 @@ public Representation include(String name, String scriptEngineName)
// Note that this will cause the script to run again!
return new ScriptedTextStreamingRepresentation(this.resource,
- this, this.scriptEngines, this.resource
+ this, this.embeddedScriptContext, this.resource
.getScriptContextController(), script,
this.flushLines);
diff --git a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ScriptedTextStreamingRepresentation.java b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ScriptedTextStreamingRepresentation.java
index 2dd8dea288..5e105252ae 100644
--- a/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ScriptedTextStreamingRepresentation.java
+++ b/modules/org.restlet.ext.script/src/org/restlet/ext/script/internal/ScriptedTextStreamingRepresentation.java
@@ -33,9 +33,7 @@
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
-import java.util.concurrent.ConcurrentMap;
-import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.restlet.data.Language;
@@ -43,6 +41,7 @@
import org.restlet.representation.WriterRepresentation;
import com.threecrickets.scripturian.EmbeddedScript;
+import com.threecrickets.scripturian.EmbeddedScriptContext;
import com.threecrickets.scripturian.ScriptContextController;
/**
@@ -74,9 +73,9 @@ class ScriptedTextStreamingRepresentation extends WriterRepresentation {
private final ScriptContextController scriptContextController;
/**
- * A cache of script contexts used by {@link EmbeddedScript}.
+ * The embedded script context.
*/
- private final ConcurrentMap<String, ScriptEngine> scriptEngines;
+ private final EmbeddedScriptContext embeddedScriptContext;
/**
* Whether to flush the writers after every line.
@@ -90,8 +89,8 @@ class ScriptedTextStreamingRepresentation extends WriterRepresentation {
* The resource
* @param container
* The container
- * @param scriptEngines
- * A cache of script engines used by {@link EmbeddedScript}.
+ * @param embeddedScriptContext
+ * The embedded script context
* @param scriptContextController
* The script context controller
* @param script
@@ -101,7 +100,7 @@ class ScriptedTextStreamingRepresentation extends WriterRepresentation {
*/
public ScriptedTextStreamingRepresentation(ScriptedTextResource resource,
ExposedScriptedTextResourceContainer container,
- ConcurrentMap<String, ScriptEngine> scriptEngines,
+ EmbeddedScriptContext embeddedScriptContext,
ScriptContextController scriptContextController,
EmbeddedScript script, boolean flushLines) {
// Note that we are setting representation characteristics
@@ -109,7 +108,7 @@ public ScriptedTextStreamingRepresentation(ScriptedTextResource resource,
super(container.getMediaType());
this.resource = resource;
this.container = container;
- this.scriptEngines = scriptEngines;
+ this.embeddedScriptContext = embeddedScriptContext;
this.scriptContextController = scriptContextController;
this.flushLines = flushLines;
setCharacterSet(container.getCharacterSet());
@@ -126,9 +125,9 @@ public void write(Writer writer) throws IOException {
this.container.isStreaming = true;
this.resource.setWriter(writer);
try {
- this.script.run(writer, this.resource.getErrorWriter(),
- this.flushLines, this.scriptEngines, this.container,
- this.scriptContextController, false);
+ this.script.run(false, writer, this.resource.getErrorWriter(),
+ this.flushLines, this.embeddedScriptContext,
+ this.container, this.scriptContextController);
} catch (ScriptException e) {
IOException ioe = new IOException("Script exception");
ioe.initCause(e);
|
9cb89acac0adf0ee111ffc6e52115966c549690a
|
Valadoc
|
libvaladoc/content: SourceCode: Strip leading and trailing empty lines
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala
index 86ad66fd80..de3bdebe61 100644
--- a/src/libvaladoc/content/sourcecode.vala
+++ b/src/libvaladoc/content/sourcecode.vala
@@ -123,6 +123,29 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
}
}
+ private inline bool is_empty_string (string line) {
+ for (int i = 0; line[i] != '\0'; i++) {
+ if (line[i].isspace () == false) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private string strip_code (string code) {
+ string[] lines = code.split ("\n");
+ for (int i = lines.length - 1; i >= 0 && is_empty_string (lines[i]); i--) {
+ lines[i] = null;
+ }
+
+ string** _lines = lines;
+ for (int i = 0; lines[i] != null && is_empty_string (lines[i]); i++) {
+ _lines = &lines[i + 1];
+ }
+
+ return string.joinv ("\n", (string[]) _lines);
+ }
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
string[] splitted = code.split ("\n", 2);
if (splitted[0].strip () == "") {
@@ -140,10 +163,11 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline {
if (_language == null && name != "none") {
string node_segment = (container is Api.Package)? "" : container.get_full_name () + ": ";
reporter.simple_warning ("%s: %s{{{: warning: Unsupported programming language '%s'", file_path, node_segment, name);
- return ;
}
}
}
+
+ code = strip_code (code);
}
public override void accept (ContentVisitor visitor) {
diff --git a/src/libvaladoc/html/htmlrenderer.vala b/src/libvaladoc/html/htmlrenderer.vala
index 4bf69d7427..513913fb68 100644
--- a/src/libvaladoc/html/htmlrenderer.vala
+++ b/src/libvaladoc/html/htmlrenderer.vala
@@ -463,11 +463,11 @@ public class Valadoc.Html.HtmlRenderer : ContentRenderer {
}
public override void visit_source_code (SourceCode element) {
- writer.start_tag ("pre", {"class", "main_source"});
writer.set_wrap (false);
+ writer.start_tag ("pre", {"class", "main_source"});
write_string (element.code);
- writer.set_wrap (true);
writer.end_tag ("pre");
+ writer.set_wrap (true);
}
public override void visit_table (Table element) {
|
64974b8bb083d41fb37ec54f6d074a51a697f479
|
Valadoc
|
libvaladoc: Add context check for @return
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/taglets/tagletreturn.vala b/src/libvaladoc/taglets/tagletreturn.vala
index 5a2797737c..8a8e0640b8 100644
--- a/src/libvaladoc/taglets/tagletreturn.vala
+++ b/src/libvaladoc/taglets/tagletreturn.vala
@@ -31,7 +31,20 @@ public class Valadoc.Taglets.Return : InlineContent, Taglet, Block {
}
public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) {
- // TODO check for the existence of a return type
+ Api.TypeReference? type_ref = null;
+ if (container is Api.Method) {
+ type_ref = ((Api.Method) container).return_type;
+ } else if (container is Api.Delegate) {
+ type_ref = ((Api.Delegate) container).return_type;
+ } else if (container is Api.Signal) {
+ type_ref = ((Api.Signal) container).return_type;
+ } else {
+ reporter.simple_warning ("@return used outside method/delegate/signal context");
+ }
+
+ if (type_ref != null && type_ref.data_type == null) {
+ reporter.simple_warning ("Return description declared for void function");
+ }
base.check (api_root, container, file_path, reporter, settings);
}
|
30661b0551940cf7e40b3db2dd3263b3d8b23c2a
|
Delta Spike
|
DELTASPIKE-289 add postback handling for windowId
|
a
|
https://github.com/apache/deltaspike
|
diff --git a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
index c20b420f7..b935ffcb8 100644
--- a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
+++ b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties
@@ -1,19 +1,19 @@
-#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
+# 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.
+# 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.
testProperty03=test_value_03
org.apache.deltaspike.core.spi.activation.ClassDeactivator=org.apache.deltaspike.test.core.impl.activation.TestClassDeactivator
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java
new file mode 100644
index 000000000..d272f3353
--- /dev/null
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindow.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.jsf.spi.scope.window;
+
+import javax.faces.context.FacesContext;
+
+/**
+ * <p>API to interact with the window/browser tab handling.
+ * This originally got implemented in Apache MyFaces CODI
+ * which was the basis for the respective feature in JSF-2.2.
+ * We now orientate us a bit on the JSF-2.2 API for making it
+ * easier to provide this feature for JSF-2.0, JSF-2.1 and also
+ * JSF-2.2 JSF implementations.</p>
+ *
+ * <p>Please not that in JSF-2.2 a <code>javax.faces.lifecycle.ClientWindow</code>
+ * instance gets created for each and every request, but in DeltaSpike our
+ * ClientWindow instances are most likely @ApplicationScoped.
+ * </p>
+ */
+public interface ClientWindow
+{
+
+ /**
+ * Extract the windowId for the current request.
+ * This method is intended to get executed at the start of the JSF lifecycle.
+ * We also need to take care about JSF-2.2 ClientWindow in the future.
+ * Depending on the {@link ClientWindowConfig.ClientWindowRenderMode} and
+ * after consulting {@link ClientWindowConfig} we will first send an
+ * intermediate page if the request is an initial GET request.
+ *
+ * @param facesContext for the request
+ * @return the extracted WindowId of the Request, or <code>null</code> if there is no window assigned.
+ */
+ String getWindowId(FacesContext facesContext);
+}
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
similarity index 92%
rename from deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
rename to deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
index 94690ec2a..dd3c5db0e 100644
--- a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/ClientWindowConfig.java
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/ClientWindowConfig.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.spi.window;
+package org.apache.deltaspike.jsf.spi.scope.window;
import javax.faces.context.FacesContext;
@@ -46,7 +46,12 @@ public enum ClientWindowRenderMode
* Render each GET request with the windowId you get during the request
* and perform a lazy check on the client side via JavaScript or similar.
*/
- LAZY
+ LAZY,
+
+ /**
+ * If you set this mode, you also need to provide an own {@link ClientWindow} implementation.
+ */
+ CUSTOM
}
diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
similarity index 95%
rename from deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
rename to deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
index dbec59177..a3bcf22a5 100644
--- a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/window/DefaultClientWindowConfig.java
+++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/spi/scope/window/DefaultClientWindowConfig.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.deltaspike.jsf.spi.window;
+package org.apache.deltaspike.jsf.spi.scope.window;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
@@ -32,8 +32,11 @@
import org.apache.deltaspike.core.util.ExceptionUtils;
/**
- * Default implementation of {@link ClientWindowConfig}.
- * It will use the internal <code>windowhandler.html</code>
+ * <p>Default implementation of {@link ClientWindowConfig}.
+ * By default it will use the internal <code>windowhandler.html</code></p>
+ *
+ * <p>You can @Specializes this class to tweak the configuration or
+ * provide a completely new implementation as @Alternative.</p>
*/
@SessionScoped
public class DefaultClientWindowConfig implements ClientWindowConfig, Serializable
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
index 28ad66dd4..9d4808d85 100644
--- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/listener/request/DeltaSpikeLifecycleWrapper.java
@@ -56,7 +56,10 @@ public void execute(FacesContext facesContext)
//TODO broadcastApplicationStartupBroadcaster();
broadcastBeforeFacesRequestEvent(facesContext);
+ //X TODO add ClientWindow handling
this.wrapped.execute(facesContext);
+
+
}
@Override
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
new file mode 100644
index 000000000..4ab6d37f8
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.deltaspike.jsf.impl.scope.window;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import javax.inject.Inject;
+
+import java.util.logging.Logger;
+
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+import org.apache.deltaspike.jsf.spi.scope.window.ClientWindow;
+import org.apache.deltaspike.jsf.spi.scope.window.ClientWindowConfig;
+
+import static org.apache.deltaspike.jsf.spi.scope.window.ClientWindowConfig.ClientWindowRenderMode;
+
+/**
+ * This is the default implementation of the window/browser tab
+ * detection handling for JSF applications.
+ * This is to big degrees a port of Apache MyFaces CODI
+ * ClientSideWindowHandler.
+ *
+ * It will act according to the configured {@link ClientWindowRenderMode}.
+ *
+ *
+ */
+@ApplicationScoped
+public class DefaultClientWindow implements ClientWindow
+{
+ private static final Logger logger = Logger.getLogger(DefaultClientWindow.class.getName());
+
+
+ @Inject
+ private ClientWindowConfig clientWindowConfig;
+
+ @Inject
+ private WindowContext windowContext;
+
+
+ @Override
+ public String getWindowId(FacesContext facesContext)
+ {
+ if (ClientWindowRenderMode.NONE.equals(clientWindowConfig.getClientWindowRenderMode(facesContext)))
+ {
+ return null;
+ }
+
+ String windowId = null;
+
+ if (facesContext.isPostback())
+ {
+ return getPostBackWindowId(facesContext);
+ }
+
+ return windowId;
+ }
+
+ /**
+ * Extract the windowId for http POST
+ */
+ private String getPostBackWindowId(FacesContext facesContext)
+ {
+ UIViewRoot uiViewRoot = facesContext.getViewRoot();
+
+ if (uiViewRoot != null)
+ {
+ WindowIdHolderComponent existingWindowIdHolder
+ = WindowIdHolderComponent.getWindowIdHolderComponent(uiViewRoot);
+ if (existingWindowIdHolder != null)
+ {
+ return existingWindowIdHolder.getWindowId();
+ }
+ }
+
+ return null;
+ }
+
+
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
new file mode 100644
index 000000000..e4f73268b
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java
@@ -0,0 +1,154 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.component.UIComponent;
+import javax.faces.component.UIOutput;
+import javax.faces.component.UIViewRoot;
+import javax.faces.context.FacesContext;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ * UI Component holder for the windowId in case of post-backs.
+ * We store this component as direct child in the ViewRoot
+ * and evaluate it's value on postbacks.
+ */
+public class WindowIdHolderComponent extends UIOutput
+{
+ private static final Logger logger = Logger.getLogger(WindowIdHolderComponent.class.getName());
+
+ private String windowId;
+
+ /**
+ * Default constructor might be invoked by the jsf implementation
+ */
+ @SuppressWarnings("UnusedDeclaration")
+ public WindowIdHolderComponent()
+ {
+ }
+
+ /**
+ * Constructor which creates the holder for the given window-id
+ * @param windowId current window-id
+ */
+ public WindowIdHolderComponent(String windowId)
+ {
+ this.windowId = windowId;
+ }
+
+ /**
+ * Needed for server-side window-handler and client-side window handler for supporting postbacks
+ */
+ public static void addWindowIdHolderComponent(FacesContext facesContext, String windowId)
+ {
+ if (windowId == null || windowId.length() == 0)
+ {
+ return;
+ }
+
+ UIViewRoot uiViewRoot = facesContext.getViewRoot();
+
+ if (uiViewRoot == null)
+ {
+ return;
+ }
+
+ WindowIdHolderComponent existingWindowIdHolder = getWindowIdHolderComponent(uiViewRoot);
+ if (existingWindowIdHolder != null)
+ {
+ if (!windowId.equals(existingWindowIdHolder.getWindowId()))
+ {
+ logger.log(Level.FINE, "updating WindowIdHolderComponent from %1 to %2",
+ new Object[]{existingWindowIdHolder.getId(), windowId});
+
+ existingWindowIdHolder.changeWindowId(windowId);
+ }
+ return;
+ }
+ else
+ {
+ // add as first child
+ uiViewRoot.getChildren().add(0, new WindowIdHolderComponent(windowId));
+ }
+ }
+
+ public static WindowIdHolderComponent getWindowIdHolderComponent(UIViewRoot uiViewRoot)
+ {
+ List<UIComponent> uiComponents = uiViewRoot.getChildren();
+
+ // performance improvement - don't change - see EXTCDI-256 :
+ for (int i = 0, size = uiComponents.size(); i < size; i++)
+ {
+ UIComponent uiComponent = uiComponents.get(i);
+ if (uiComponent instanceof WindowIdHolderComponent)
+ {
+ //in this case we have the same view-root
+ return (WindowIdHolderComponent) uiComponent;
+ }
+ }
+
+ return null;
+ }
+
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Object saveState(FacesContext facesContext)
+ {
+ Object[] values = new Object[2];
+ values[0] = super.saveState(facesContext);
+ values[1] = windowId;
+ return values;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void restoreState(FacesContext facesContext, Object state)
+ {
+ if (state == null)
+ {
+ return;
+ }
+
+ Object[] values = (Object[]) state;
+ super.restoreState(facesContext, values[0]);
+
+ windowId = (String) values[1];
+ }
+
+ /**
+ * @return the current windowId
+ */
+ public String getWindowId()
+ {
+ return windowId;
+ }
+
+ void changeWindowId(String windowId)
+ {
+ this.windowId = windowId;
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
new file mode 100644
index 000000000..883ddb022
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java
@@ -0,0 +1,101 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.context.FacesContext;
+import javax.faces.render.RenderKit;
+import javax.faces.render.RenderKitFactory;
+import java.util.Iterator;
+
+import org.apache.deltaspike.core.spi.activation.Deactivatable;
+import org.apache.deltaspike.core.util.ClassDeactivationUtils;
+
+
+/**
+ * Registers the @{link WindowIdRenderKit}
+ */
+public class WindowIdRenderKitFactory extends RenderKitFactory implements Deactivatable
+{
+ private final RenderKitFactory wrapped;
+
+ private final boolean deactivated;
+
+ /**
+ * Constructor for wrapping the given {@link javax.faces.render.RenderKitFactory}
+ * @param wrapped render-kit-factory which will be wrapped
+ */
+ public WindowIdRenderKitFactory(RenderKitFactory wrapped)
+ {
+ this.wrapped = wrapped;
+ this.deactivated = !isActivated();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void addRenderKit(String s, RenderKit renderKit)
+ {
+ wrapped.addRenderKit(s, renderKit);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public RenderKit getRenderKit(FacesContext facesContext, String s)
+ {
+ RenderKit renderKit = wrapped.getRenderKit(facesContext, s);
+
+ if (renderKit == null)
+ {
+ return null;
+ }
+
+ if (deactivated)
+ {
+ return renderKit;
+ }
+
+ return new WindowIdRenderKitWrapper(renderKit);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Iterator<String> getRenderKitIds()
+ {
+ return wrapped.getRenderKitIds();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public RenderKitFactory getWrapped()
+ {
+ return wrapped;
+ }
+
+ public boolean isActivated()
+ {
+ return ClassDeactivationUtils.isActivated(getClass());
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
new file mode 100644
index 000000000..bb939d516
--- /dev/null
+++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java
@@ -0,0 +1,92 @@
+/*
+ * 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.deltaspike.jsf.impl.scope.window;
+
+import javax.faces.context.FacesContext;
+import javax.faces.context.ResponseWriter;
+import javax.faces.render.RenderKit;
+import javax.faces.render.RenderKitWrapper;
+import java.io.Writer;
+
+import org.apache.deltaspike.core.api.provider.BeanProvider;
+import org.apache.deltaspike.core.spi.scope.window.WindowContext;
+
+/**
+ * Wraps the RenderKit and adds the
+ * {@link WindowIdHolderComponent} to the view tree
+ */
+public class WindowIdRenderKitWrapper extends RenderKitWrapper
+{
+ private final RenderKit wrapped;
+
+ /**
+ * This will get initialized lazily to prevent boot order issues
+ * with the JSF and CDI containers.
+ */
+ private volatile WindowContext windowContext;
+
+
+ //needed if the renderkit gets proxied - see EXTCDI-215
+ protected WindowIdRenderKitWrapper()
+ {
+ this.wrapped = null;
+ }
+
+ public WindowIdRenderKitWrapper(RenderKit wrapped)
+ {
+ this.wrapped = wrapped;
+ }
+
+ @Override
+ public RenderKit getWrapped()
+ {
+ return wrapped;
+ }
+
+ /**
+ * Adds a {@link WindowIdHolderComponent} with the
+ * current windowId to the component tree.
+ */
+ public ResponseWriter createResponseWriter(Writer writer, String s, String s1)
+ {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ String windowId = getWindowContext().getCurrentWindowId();
+
+ WindowIdHolderComponent.addWindowIdHolderComponent(facesContext, windowId);
+
+ return wrapped.createResponseWriter(writer, s, s1);
+ }
+
+
+ private WindowContext getWindowContext()
+ {
+ if (windowContext == null)
+ {
+ synchronized (this)
+ {
+ if (windowContext == null)
+ {
+ windowContext = BeanProvider.getContextualReference(WindowContext.class);
+ }
+ }
+ }
+
+ return windowContext;
+ }
+}
diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
index 50ed16777..6d951da10 100644
--- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
+++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml
@@ -36,5 +36,6 @@
<factory>
<lifecycle-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleFactoryWrapper</lifecycle-factory>
<faces-context-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeFacesContextFactory</faces-context-factory>
+ <render-kit-factory>org.apache.deltaspike.jsf.impl.scope.window.WindowIdRenderKitFactory</render-kit-factory>
</factory>
-</faces-config>
\ No newline at end of file
+</faces-config>
|
42f200a010d5c374bfc9d1d9c6cfef58aa89be54
|
Valadoc
|
libvaladoc/html: Show all known sub-structs
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/html/basicdoclet.vala b/src/libvaladoc/html/basicdoclet.vala
index 29b2c6ceab..040fdd06ff 100644
--- a/src/libvaladoc/html/basicdoclet.vala
+++ b/src/libvaladoc/html/basicdoclet.vala
@@ -637,8 +637,10 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet {
var iface = node as Interface;
write_known_symbols_note (iface.get_known_implementations (), iface, "All known implementing classes:");
write_known_symbols_note (iface.get_known_related_interfaces (), iface, "All known sub-interfaces:");
+ } else if (node is Struct) {
+ var stru = node as Struct;
+ write_known_symbols_note (stru.get_known_child_structs (), stru, "All known sub-structs:");
}
- // TODO: All known sub-structs
if (node.parent is Namespace) {
|
ca2ba9131b10c5927172505f89f79cc0088dca3f
|
Valadoc
|
libvaladoc: gir-reader: improve short descs
|
a
|
https://github.com/GNOME/vala/
|
diff --git a/src/libvaladoc/content/blockcontent.vala b/src/libvaladoc/content/blockcontent.vala
index c3c55fdff1..e466177978 100755
--- a/src/libvaladoc/content/blockcontent.vala
+++ b/src/libvaladoc/content/blockcontent.vala
@@ -45,5 +45,15 @@ public abstract class Valadoc.Content.BlockContent : ContentElement {
element.accept (visitor);
}
}
+
+ public override bool is_empty () {
+ foreach (Block item in content) {
+ if (!item.is_empty ()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
}
diff --git a/src/libvaladoc/content/contentelement.vala b/src/libvaladoc/content/contentelement.vala
index 8886ca89eb..427cf66071 100755
--- a/src/libvaladoc/content/contentelement.vala
+++ b/src/libvaladoc/content/contentelement.vala
@@ -32,6 +32,8 @@ public abstract class Valadoc.Content.ContentElement : Object {
public abstract void accept (ContentVisitor visitor);
+ public abstract bool is_empty ();
+
public virtual void accept_children (ContentVisitor visitor) {
}
}
diff --git a/src/libvaladoc/content/embedded.vala b/src/libvaladoc/content/embedded.vala
index e3be516d0d..f158800aae 100755
--- a/src/libvaladoc/content/embedded.vala
+++ b/src/libvaladoc/content/embedded.vala
@@ -53,4 +53,8 @@ public class Valadoc.Content.Embedded : ContentElement, Inline, StyleAttributes
public override void accept (ContentVisitor visitor) {
visitor.visit_embedded (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/headline.vala b/src/libvaladoc/content/headline.vala
index c644c71c49..c7fcb29ce9 100755
--- a/src/libvaladoc/content/headline.vala
+++ b/src/libvaladoc/content/headline.vala
@@ -42,5 +42,10 @@ public class Valadoc.Content.Headline : Block, InlineContent {
public override void accept (ContentVisitor visitor) {
visitor.visit_headline (this);
}
+
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/inlinecontent.vala b/src/libvaladoc/content/inlinecontent.vala
index cdb2470369..389c66b96b 100755
--- a/src/libvaladoc/content/inlinecontent.vala
+++ b/src/libvaladoc/content/inlinecontent.vala
@@ -46,5 +46,15 @@ public abstract class Valadoc.Content.InlineContent : ContentElement {
element.accept (visitor);
}
}
+
+ public override bool is_empty () {
+ foreach (Inline item in content) {
+ if (!item.is_empty ()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
}
diff --git a/src/libvaladoc/content/inlinetaglet.vala b/src/libvaladoc/content/inlinetaglet.vala
index 1ea92bbb43..813bcf3390 100755
--- a/src/libvaladoc/content/inlinetaglet.vala
+++ b/src/libvaladoc/content/inlinetaglet.vala
@@ -57,5 +57,10 @@ public abstract class Valadoc.Content.InlineTaglet : ContentElement, Taglet, Inl
ContentElement element = get_content ();
element.accept (visitor);
}
+
+ public override bool is_empty () {
+ // taglets are not empty by default
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/link.vala b/src/libvaladoc/content/link.vala
index 421039aa01..e114e96947 100755
--- a/src/libvaladoc/content/link.vala
+++ b/src/libvaladoc/content/link.vala
@@ -40,4 +40,8 @@ public class Valadoc.Content.Link : InlineContent, Inline {
public override void accept (ContentVisitor visitor) {
visitor.visit_link (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/list.vala b/src/libvaladoc/content/list.vala
index 256eb88058..c7bae59a85 100755
--- a/src/libvaladoc/content/list.vala
+++ b/src/libvaladoc/content/list.vala
@@ -124,4 +124,8 @@ public class Valadoc.Content.List : ContentElement, Block {
element.accept (visitor);
}
}
+
+ public override bool is_empty () {
+ return _items.size == 0;
+ }
}
diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala
index 574a09623f..fb2bd625e9 100755
--- a/src/libvaladoc/content/sourcecode.vala
+++ b/src/libvaladoc/content/sourcecode.vala
@@ -70,4 +70,9 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline{
public override void accept (ContentVisitor visitor) {
visitor.visit_source_code (this);
}
+
+ public override bool is_empty () {
+ // empty source blocks are visible as well
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/symbollink.vala b/src/libvaladoc/content/symbollink.vala
index 11d4d330f0..ef52b30101 100755
--- a/src/libvaladoc/content/symbollink.vala
+++ b/src/libvaladoc/content/symbollink.vala
@@ -42,5 +42,9 @@ public class Valadoc.Content.SymbolLink : ContentElement, Inline {
public override void accept (ContentVisitor visitor) {
visitor.visit_symbol_link (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/table.vala b/src/libvaladoc/content/table.vala
index 95feebe7aa..dc232ae208 100755
--- a/src/libvaladoc/content/table.vala
+++ b/src/libvaladoc/content/table.vala
@@ -51,5 +51,9 @@ public class Valadoc.Content.Table : ContentElement, Block {
element.accept (visitor);
}
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/tablecell.vala b/src/libvaladoc/content/tablecell.vala
index dddd89f5e7..01e732f090 100755
--- a/src/libvaladoc/content/tablecell.vala
+++ b/src/libvaladoc/content/tablecell.vala
@@ -44,5 +44,10 @@ public class Valadoc.Content.TableCell : InlineContent, StyleAttributes {
public override void accept (ContentVisitor visitor) {
visitor.visit_table_cell (this);
}
+
+ public override bool is_empty () {
+ // empty cells are displayed as well
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/tablerow.vala b/src/libvaladoc/content/tablerow.vala
index b2868cc9de..943c95f646 100755
--- a/src/libvaladoc/content/tablerow.vala
+++ b/src/libvaladoc/content/tablerow.vala
@@ -49,5 +49,9 @@ public class Valadoc.Content.TableRow : ContentElement {
element.accept (visitor);
}
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/content/text.vala b/src/libvaladoc/content/text.vala
index f4704e8430..2b147235d5 100755
--- a/src/libvaladoc/content/text.vala
+++ b/src/libvaladoc/content/text.vala
@@ -42,5 +42,10 @@ public class Valadoc.Content.Text : ContentElement, Inline {
public override void accept (ContentVisitor visitor) {
visitor.visit_text (this);
}
+
+
+ public override bool is_empty () {
+ return content == "";
+ }
}
diff --git a/src/libvaladoc/content/wikilink.vala b/src/libvaladoc/content/wikilink.vala
index 3833c47bbe..e88bc18f71 100755
--- a/src/libvaladoc/content/wikilink.vala
+++ b/src/libvaladoc/content/wikilink.vala
@@ -45,4 +45,9 @@ public class Valadoc.Content.WikiLink : InlineContent, Inline {
public override void accept (ContentVisitor visitor) {
visitor.visit_wiki_link (this);
}
+
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala
index a376d400cb..984f56dff9 100644
--- a/src/libvaladoc/documentation/gtkdoccommentparser.vala
+++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala
@@ -54,6 +54,116 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
this.stack.clear ();
}
+ private inline Text? split_text (Text text) {
+ int offset = 0;
+ while ((offset = text.content.index_of_char ('.', offset)) >= 0) {
+ if (offset >= 2) {
+ // ignore e.g.
+ unowned string cmp4 = ((string) (((char*) text.content) + offset - 2));
+ if (cmp4.has_prefix (" e.g.") || cmp4.has_prefix ("(e.g.")) {
+ offset = offset + 3;
+ continue;
+ }
+
+ // ignore i.e.
+ if (cmp4.has_prefix (" i.e.") || cmp4.has_prefix ("(i.e.")) {
+ offset = offset + 3;
+ continue;
+ }
+ }
+
+ Text sec = factory.create_text (text.content.substring (offset+1, -1));
+ text.content = text.content.substring (0, offset+1);
+ return sec;
+ }
+
+ return null;
+ }
+
+ private inline Run? split_run (Run run) {
+ Run? sec = null;
+
+ Iterator<Inline> iter = run.content.iterator ();
+ for (bool has_next = iter.first (); has_next; has_next = iter.next ()) {
+ Inline item = iter.get ();
+ if (sec == null) {
+ Inline? tmp = split_inline (item);
+ if (tmp != null) {
+ sec = factory.create_run (run.style);
+ sec.content.add (tmp);
+ }
+ } else {
+ sec.content.add (item);
+ iter.remove ();
+ }
+ }
+
+ return sec;
+ }
+
+ private inline Inline? split_inline (Inline item) {
+ if (item is Text) {
+ return split_text ((Text) item);
+ } else if (item is Run) {
+ return split_run ((Run) item);
+ }
+
+ return null;
+ }
+
+ private inline Paragraph? split_paragraph (Paragraph p) {
+ Paragraph? sec = null;
+
+ Iterator<Inline> iter = p.content.iterator ();
+ for (bool has_next = iter.first (); has_next; has_next = iter.next ()) {
+ Inline item = iter.get ();
+ if (sec == null) {
+ Inline? tmp = split_inline (item);
+ if (tmp != null) {
+ sec = factory.create_paragraph ();
+ sec.horizontal_align = p.horizontal_align;
+ sec.vertical_align = p.vertical_align;
+ sec.style = p.style;
+ sec.content.add (tmp);
+ }
+ } else {
+ sec.content.add (item);
+ iter.remove ();
+ }
+ }
+
+ return sec;
+ }
+
+ private void extract_short_desc (Comment comment) {
+ if (comment.content.size == 0) {
+ return ;
+ }
+
+ Paragraph? first_paragraph = comment.content[0] as Paragraph;
+ if (first_paragraph == null) {
+ // add empty paragraph to avoid non-text as short descriptions
+ comment.content.insert (1, factory.create_paragraph ());
+ return ;
+ }
+
+
+ // avoid fancy stuff in short descriptions:
+ first_paragraph.horizontal_align = null;
+ first_paragraph.vertical_align = null;
+ first_paragraph.style = null;
+
+
+ Paragraph? second_paragraph = split_paragraph (first_paragraph);
+ if (second_paragraph == null) {
+ return ;
+ }
+
+ if (second_paragraph.is_empty () == false) {
+ comment.content.insert (1, second_paragraph);
+ }
+ }
+
private void report_unexpected_token (Token got, string expected) {
if (this.show_warnings) {
return ;
@@ -171,6 +281,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator {
return null;
}
+ extract_short_desc (comment);
+
return comment;
}
diff --git a/src/libvaladoc/taglets/tagletdeprecated.vala b/src/libvaladoc/taglets/tagletdeprecated.vala
index 4386571b0e..f51adc174f 100755
--- a/src/libvaladoc/taglets/tagletdeprecated.vala
+++ b/src/libvaladoc/taglets/tagletdeprecated.vala
@@ -35,4 +35,9 @@ public class Valadoc.Taglets.Deprecated : InlineContent, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
+
diff --git a/src/libvaladoc/taglets/tagletinheritdoc.vala b/src/libvaladoc/taglets/tagletinheritdoc.vala
index 4f4568faa6..329db68696 100755
--- a/src/libvaladoc/taglets/tagletinheritdoc.vala
+++ b/src/libvaladoc/taglets/tagletinheritdoc.vala
@@ -67,4 +67,8 @@ public class Valadoc.Taglets.InheritDoc : InlineTaglet {
}
return new Text ("");
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletlink.vala b/src/libvaladoc/taglets/tagletlink.vala
index 633fc4184a..3ebb6de3eb 100755
--- a/src/libvaladoc/taglets/tagletlink.vala
+++ b/src/libvaladoc/taglets/tagletlink.vala
@@ -100,4 +100,8 @@ public class Valadoc.Taglets.Link : InlineTaglet {
return link;
}
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletsee.vala b/src/libvaladoc/taglets/tagletsee.vala
index d976688770..68ed636ed6 100755
--- a/src/libvaladoc/taglets/tagletsee.vala
+++ b/src/libvaladoc/taglets/tagletsee.vala
@@ -58,4 +58,8 @@ public class Valadoc.Taglets.See : ContentElement, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletsince.vala b/src/libvaladoc/taglets/tagletsince.vala
index e28bf72a96..5b68ecfe82 100755
--- a/src/libvaladoc/taglets/tagletsince.vala
+++ b/src/libvaladoc/taglets/tagletsince.vala
@@ -25,7 +25,7 @@ using Valadoc.Content;
public class Valadoc.Taglets.Since : ContentElement, Taglet, Block {
- public string version;
+ public string version { get; internal set; }
public Rule? get_parser_rule (Rule run_rule) {
Rule optional_spaces = Rule.option ({ Rule.many ({ TokenType.SPACE }) });
@@ -43,4 +43,8 @@ public class Valadoc.Taglets.Since : ContentElement, Taglet, Block {
public override void accept (ContentVisitor visitor) {
visitor.visit_taglet (this);
}
+
+ public override bool is_empty () {
+ return false;
+ }
}
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala
index 79ae9c07e0..b592f6ca1e 100755
--- a/src/libvaladoc/taglets/tagletthrows.vala
+++ b/src/libvaladoc/taglets/tagletthrows.vala
@@ -49,3 +49,4 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block {
visitor.visit_taglet (this);
}
}
+
|
d7c90cff145edc3193a63b1b7751aee203d5c4d6
|
spring-framework
|
made ConversionExecutor internal; removed other- unused operations from public SPI--
|
p
|
https://github.com/spring-projects/spring-framework
|
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java
index 372e41fb2df2..782f78d8bd02 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionService.java
@@ -16,10 +16,10 @@
package org.springframework.core.convert;
/**
- * A service interface for type conversion. This is the entry point into the convert system. Call one of the
- * <i>executeConversion</i> operations to perform a thread-safe type conversion using
- * this system. Call one of the <i>getConversionExecutor</i> operations to obtain
- * a thread-safe {@link ConversionExecutor} command for later use.
+ * A service interface for type conversion. This is the entry point into the convert system.
+ * <p>
+ * Call {@link #executeConversion(Object, TypeDescriptor)} to perform a thread-safe type conversion using
+ * this system.
*
* @author Keith Donald
*/
@@ -28,47 +28,21 @@ public interface ConversionService {
/**
* Returns true if objects of sourceType can be converted to targetType.
* @param source the source to convert from (may be null)
- * @param targetType the target type to convert to
+ * @param targetType context about the target type to convert to
* @return true if a conversion can be performed, false if not
*/
public boolean canConvert(Class<?> sourceType, TypeDescriptor targetType);
- /**
- * Returns true if the source can be converted to targetType.
- * @param source the source to convert from (may be null)
- * @param targetType the target type to convert to
- * @return true if a conversion can be performed, false if not
- */
- public boolean canConvert(Object source, TypeDescriptor targetType);
-
/**
* Convert the source to targetType.
* @param source the source to convert from (may be null)
- * @param targetType the target type to convert to
- * @return the converted object, an instance of the <code>targetType</code>, or <code>null</code> if a null source
+ * @param targetType context about the target type to convert to
+ * @return the converted object, an instance of {@link TypeDescriptor#getType()}</code>, or <code>null</code> if a null source
* was provided
- * @throws ConversionExecutorNotFoundException if no suitable conversion executor could be found to convert the
+ * @throws ConverterNotFoundException if no suitable conversion executor could be found to convert the
* source to an instance of targetType
* @throws ConversionException if an exception occurred during the conversion process
*/
- public Object executeConversion(Object source, TypeDescriptor targetType) throws ConversionExecutorNotFoundException,
- ConversionException;
-
- /**
- * Get a ConversionExecutor that converts objects from sourceType to targetType.
- * The returned ConversionExecutor is thread-safe and may safely be cached for later use by client code.
- * @param sourceType the source type to convert from (required)
- * @param targetType the target type to convert to (required)
- * @return the executor that can execute instance type conversion, never null
- * @throws ConversionExecutorNotFoundException when no suitable conversion executor could be found
- */
- public ConversionExecutor getConversionExecutor(Class<?> sourceType, TypeDescriptor targetType)
- throws ConversionExecutorNotFoundException;
-
- /**
- * Get a type by its name; may be the fully-qualified class name or a registered type alias such as 'int'.
- * @return the class, or <code>null</code> if no such name exists
- */
- public Class<?> getType(String name);
+ public Object executeConversion(Object source, TypeDescriptor targetType);
}
\ No newline at end of file
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java b/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java
new file mode 100644
index 000000000000..8856a84101c8
--- /dev/null
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/ConverterNotFoundException.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2004-2009 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.core.convert;
+
+/**
+ * Thrown when a conversion executor could not be found in a conversion service.
+ *
+ * @author Keith Donald
+ */
+public class ConverterNotFoundException extends ConversionException {
+
+ private Class<?> sourceType;
+
+ private TypeDescriptor targetType;
+
+ /**
+ * Creates a new conversion executor not found exception.
+ * @param sourceType the source type requested to convert from
+ * @param targetType the target type requested to convert to
+ * @param message a descriptive message
+ */
+ public ConverterNotFoundException(Class<?> sourceType, TypeDescriptor targetType, String message) {
+ super(message);
+ this.sourceType = sourceType;
+ this.targetType = targetType;
+ }
+
+ /**
+ * Returns the source type that was requested to convert from.
+ */
+ public Class<?> getSourceType() {
+ return sourceType;
+ }
+
+ /**
+ * Returns the target type that was requested to convert to.
+ */
+ public TypeDescriptor getTargetType() {
+ return targetType;
+ }
+}
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java
index a43fa91155a6..a5ef6262e974 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/AbstractCollectionConverter.java
@@ -16,7 +16,6 @@
package org.springframework.core.convert.service;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
@@ -26,7 +25,7 @@
*/
abstract class AbstractCollectionConverter implements ConversionExecutor {
- private ConversionService conversionService;
+ private GenericConversionService conversionService;
private ConversionExecutor elementConverter;
@@ -34,7 +33,7 @@ abstract class AbstractCollectionConverter implements ConversionExecutor {
private TypeDescriptor targetCollectionType;
- public AbstractCollectionConverter(TypeDescriptor sourceCollectionType, TypeDescriptor targetCollectionType, ConversionService conversionService) {
+ public AbstractCollectionConverter(TypeDescriptor sourceCollectionType, TypeDescriptor targetCollectionType, GenericConversionService conversionService) {
this.conversionService = conversionService;
this.sourceCollectionType = sourceCollectionType;
this.targetCollectionType = targetCollectionType;
@@ -61,7 +60,7 @@ protected Class<?> getTargetElementType() {
return targetCollectionType.getElementType();
}
- protected ConversionService getConversionService() {
+ protected GenericConversionService getConversionService() {
return conversionService;
}
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java
index d971a645ce29..e21315f56174 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ArrayToCollection.java
@@ -18,7 +18,6 @@
import java.lang.reflect.Array;
import java.util.Collection;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
/**
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java
index b7e2ed98dbaf..d70bdae51597 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToArray.java
@@ -19,7 +19,6 @@
import java.util.Collection;
import java.util.Iterator;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
/**
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java
index a5921926cb0d..b189b547035a 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/CollectionToCollection.java
@@ -18,7 +18,6 @@
import java.util.Collection;
import java.util.Iterator;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
/**
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java
similarity index 87%
rename from org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java
rename to org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java
index 3059f003b729..a84bbe5019ce 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/ConversionExecutor.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/ConversionExecutor.java
@@ -13,7 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.springframework.core.convert;
+package org.springframework.core.convert.service;
+
+import org.springframework.core.convert.ConversionExecutionException;
/**
* A command parameterized with the information necessary to perform a conversion of a source input to a
@@ -29,6 +31,6 @@ public interface ConversionExecutor {
* @param source the source to convert
* @throws ConversionExecutionException if an exception occurs during type conversion
*/
- public Object execute(Object source) throws ConversionExecutionException;
+ public Object execute(Object source);
}
\ No newline at end of file
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java
index a149217bf58b..73e28ea151a1 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/DefaultConversionService.java
@@ -49,7 +49,6 @@ public class DefaultConversionService extends GenericConversionService {
*/
public DefaultConversionService() {
addDefaultConverters();
- addDefaultAliases();
}
/**
@@ -73,21 +72,4 @@ protected void addDefaultConverters() {
addConverter(new ObjectToString());
}
- protected void addDefaultAliases() {
- addAlias("string", String.class);
- addAlias("byte", Byte.class);
- addAlias("boolean", Boolean.class);
- addAlias("char", Character.class);
- addAlias("short", Short.class);
- addAlias("int", Integer.class);
- addAlias("long", Long.class);
- addAlias("float", Float.class);
- addAlias("double", Double.class);
- addAlias("bigInt", BigInteger.class);
- addAlias("bigDecimal", BigDecimal.class);
- addAlias("locale", Locale.class);
- addAlias("enum", Enum.class);
- addAlias("date", Date.class);
- }
-
}
\ No newline at end of file
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java
index 74d19fdcc082..8cee88e12eb1 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/GenericConversionService.java
@@ -26,10 +26,8 @@
import java.util.Map;
import org.springframework.core.GenericTypeResolver;
-import org.springframework.core.convert.ConversionException;
-import org.springframework.core.convert.ConversionExecutor;
-import org.springframework.core.convert.ConversionExecutorNotFoundException;
import org.springframework.core.convert.ConversionService;
+import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterInfo;
@@ -61,11 +59,6 @@ public class GenericConversionService implements ConversionService {
*/
private final Map sourceTypeSuperConverters = new HashMap();
- /**
- * Indexes classes by well-known aliases.
- */
- private final Map aliasMap = new HashMap<String, Class<?>>();
-
/**
* An optional parent conversion service.
*/
@@ -132,48 +125,41 @@ public static <S, T> Converter<S, T> converterFor(Class<S> sourceType, Class<T>
return new SuperTwoWayConverterConverter(converter, sourceType, targetType);
}
- /**
- * Add a convenient alias for the target type. {@link #getType(String)} can then be used to lookup the type given
- * the alias.
- * @see #getType(String)
- */
- public void addAlias(String alias, Class targetType) {
- aliasMap.put(alias, targetType);
- }
-
// implementing ConversionService
public boolean canConvert(Class<?> sourceType, TypeDescriptor targetType) {
- try {
- getConversionExecutor(sourceType, targetType);
+ ConversionExecutor executor = getConversionExecutor(sourceType, targetType);
+ if (executor != null) {
return true;
- } catch (ConversionExecutorNotFoundException e) {
- return false;
- }
- }
-
- public boolean canConvert(Object source, TypeDescriptor targetType) {
- if (source == null) {
- return true;
- }
- try {
- getConversionExecutor(source.getClass(), targetType);
- return true;
- } catch (ConversionExecutorNotFoundException e) {
- return false;
+ } else {
+ if (parent != null) {
+ return parent.canConvert(sourceType, targetType);
+ } else {
+ return false;
+ }
}
}
- public Object executeConversion(Object source, TypeDescriptor targetType)
- throws ConversionExecutorNotFoundException, ConversionException {
+ public Object executeConversion(Object source, TypeDescriptor targetType) {
if (source == null) {
return null;
}
- return getConversionExecutor(source.getClass(), targetType).execute(source);
+ ConversionExecutor executor = getConversionExecutor(source.getClass(), targetType);
+ if (executor != null) {
+ return executor.execute(source);
+ } else {
+ if (parent != null) {
+ return parent.executeConversion(source, targetType);
+ } else {
+ throw new ConverterNotFoundException(source.getClass(), targetType,
+ "No converter found that can convert from sourceType [" + source.getClass().getName()
+ + "] to targetType [" + targetType.getName() + "]");
+ }
+ }
}
- public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescriptor targetType)
- throws ConversionExecutorNotFoundException {
+ ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescriptor targetType)
+ throws ConverterNotFoundException {
Assert.notNull(sourceClass, "The sourceType to convert from is required");
Assert.notNull(targetType, "The targetType to convert to is required");
TypeDescriptor sourceType = TypeDescriptor.valueOf(sourceClass);
@@ -193,21 +179,21 @@ public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescripto
if (sourceType.isCollection()) {
return new CollectionToArray(sourceType, targetType, this);
} else {
- throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Array conversion not yet supported");
+ return null;
}
}
if (sourceType.isCollection()) {
if (targetType.isCollection()) {
return new CollectionToCollection(sourceType, targetType, this);
} else {
- throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Collection conversion not yet supported");
+ return null;
}
}
if (sourceType.isMap()) {
if (targetType.isMap()) {
return new MapToMap(sourceType, targetType, this);
} else {
- throw new ConversionExecutorNotFoundException(sourceType, targetType, "Object to Map conversion not yet supported");
+ return null;
}
}
Converter converter = findRegisteredConverter(sourceClass, targetType.getType());
@@ -217,28 +203,10 @@ public ConversionExecutor getConversionExecutor(Class sourceClass, TypeDescripto
SuperConverter superConverter = findRegisteredSuperConverter(sourceClass, targetType.getType());
if (superConverter != null) {
return new StaticSuperConversionExecutor(sourceType, targetType, superConverter);
- }
- if (parent != null) {
- return parent.getConversionExecutor(sourceClass, targetType);
} else {
if (sourceType.isAssignableTo(targetType)) {
return new StaticConversionExecutor(sourceType, targetType, NoOpConverter.INSTANCE);
}
- throw new ConversionExecutorNotFoundException(sourceType, targetType,
- "No ConversionExecutor found for converting from sourceType [" + sourceType.getName()
- + "] to targetType [" + targetType.getName() + "]");
- }
- }
- }
-
- public Class getType(String name) throws IllegalArgumentException {
- Class clazz = (Class) aliasMap.get(name);
- if (clazz != null) {
- return clazz;
- } else {
- if (parent != null) {
- return parent.getType(name);
- } else {
return null;
}
}
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java
index 90db0082c844..9d6712433e63 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/MapToMap.java
@@ -22,7 +22,6 @@
import java.util.TreeMap;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
@@ -36,7 +35,7 @@ class MapToMap implements ConversionExecutor {
private TypeDescriptor targetType;
- private ConversionService conversionService;
+ private GenericConversionService conversionService;
private EntryConverter entryConverter;
@@ -46,7 +45,7 @@ class MapToMap implements ConversionExecutor {
* @param targetType the target map type
* @param conversionService the conversion service
*/
- public MapToMap(TypeDescriptor sourceType, TypeDescriptor targetType, ConversionService conversionService) {
+ public MapToMap(TypeDescriptor sourceType, TypeDescriptor targetType, GenericConversionService conversionService) {
this.sourceType = sourceType;
this.targetType = targetType;
this.conversionService = conversionService;
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java
index 817731724939..086eb3330be5 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/NoOpConversionExecutor.java
@@ -16,7 +16,6 @@
package org.springframework.core.convert.service;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
/**
* Conversion executor that does nothing. Access singleton at {@link #INSTANCE}.s
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java
index 857d7d3dc27f..be3b767a9aaf 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticConversionExecutor.java
@@ -16,7 +16,6 @@
package org.springframework.core.convert.service;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.style.ToStringCreator;
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java
index 58241e9f615d..e1f1303391ca 100644
--- a/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java
+++ b/org.springframework.core/src/main/java/org/springframework/core/convert/service/StaticSuperConversionExecutor.java
@@ -16,7 +16,6 @@
package org.springframework.core.convert.service;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.SuperConverter;
import org.springframework.core.style.ToStringCreator;
diff --git a/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java b/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java
index dd96160956ad..201ca828855e 100644
--- a/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java
+++ b/org.springframework.core/src/test/java/org/springframework/core/convert/service/GenericConversionServiceTests.java
@@ -31,8 +31,7 @@
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.core.convert.ConversionExecutionException;
-import org.springframework.core.convert.ConversionExecutor;
-import org.springframework.core.convert.ConversionExecutorNotFoundException;
+import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.NumberToNumber;
@@ -84,9 +83,9 @@ public void convertReverseIndex() {
@Test
public void convertExecutorNotFound() {
try {
- service.getConversionExecutor(String.class, type(Integer.class));
+ service.executeConversion("3", type(Integer.class));
fail("Should have thrown an exception");
- } catch (ConversionExecutorNotFoundException e) {
+ } catch (ConverterNotFoundException e) {
}
}
@@ -161,9 +160,9 @@ public CharSequence convertBack(Number target) throws Exception {
}
});
try {
- ConversionExecutor executor = service.getConversionExecutor(String.class, type(Integer.class));
+ service.executeConversion("3", type(Integer.class));
fail("Should have failed");
- } catch (ConversionExecutorNotFoundException e) {
+ } catch (ConverterNotFoundException e) {
}
}
diff --git a/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java b/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java
index e1f4bfa5d428..3b11b06081b2 100644
--- a/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java
+++ b/org.springframework.expression/src/main/java/org/springframework/expression/spel/support/StandardTypeConverter.java
@@ -17,7 +17,7 @@
package org.springframework.expression.spel.support;
import org.springframework.core.convert.ConversionException;
-import org.springframework.core.convert.ConversionExecutorNotFoundException;
+import org.springframework.core.convert.ConverterNotFoundException;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.service.DefaultConversionService;
@@ -53,7 +53,7 @@ public <T> T convertValue(Object value, Class<T> targetType) throws EvaluationEx
public Object convertValue(Object value, TypeDescriptor typeDescriptor) throws EvaluationException {
try {
return conversionService.executeConversion(value, typeDescriptor);
- } catch (ConversionExecutorNotFoundException cenfe) {
+ } catch (ConverterNotFoundException cenfe) {
throw new SpelException(cenfe, SpelMessages.TYPE_CONVERSION_ERROR, value.getClass(), typeDescriptor.asString());
} catch (ConversionException ce) {
throw new SpelException(ce, SpelMessages.TYPE_CONVERSION_ERROR, value.getClass(), typeDescriptor.asString());
diff --git a/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java b/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java
index 2215acb3a4ff..d3920f8b6d62 100644
--- a/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java
+++ b/org.springframework.expression/src/test/java/org/springframework/expression/spel/ExpressionTestsUsingCoreConversionService.java
@@ -19,7 +19,6 @@
import java.util.ArrayList;
import java.util.List;
-import org.springframework.core.convert.ConversionExecutor;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.service.DefaultConversionService;
import org.springframework.core.convert.service.GenericConversionService;
@@ -65,17 +64,14 @@ public void testConversionsAvailable() throws Exception {
// ArrayList containing List<Integer> to List<String>
Class<?> clazz = typeDescriptorForListOfString.getElementType();
assertEquals(String.class,clazz);
- ConversionExecutor executor = tcs.getConversionExecutor(ArrayList.class, typeDescriptorForListOfString);
- assertNotNull(executor);
- List l = (List)executor.execute(listOfInteger);
+ List l = (List) tcs.executeConversion(listOfInteger, typeDescriptorForListOfString);
assertNotNull(l);
// ArrayList containing List<String> to List<Integer>
clazz = typeDescriptorForListOfInteger.getElementType();
assertEquals(Integer.class,clazz);
- executor = tcs.getConversionExecutor(ArrayList.class, typeDescriptorForListOfInteger);
- assertNotNull(executor);
- l = (List)executor.execute(listOfString);
+
+ l = (List) tcs.executeConversion(listOfString, typeDescriptorForListOfString);
assertNotNull(l);
}
|
ace77ef53fafa3194ce3c18d1cf00237f82a1dbc
|
restlet-framework-java
|
Removed Representation-getDigester* methods. There- is no reason to favor this way to wrap a Representation.--
|
p
|
https://github.com/restlet/restlet-framework-java
|
diff --git a/modules/org.restlet.test/pom.xml b/modules/org.restlet.test/pom.xml
index 849374dbdd..85ae717822 100644
--- a/modules/org.restlet.test/pom.xml
+++ b/modules/org.restlet.test/pom.xml
@@ -108,6 +108,12 @@
<artifactId>org.restlet.ext.netty</artifactId>
<version>2.0-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.restlet.dev</groupId>
+ <artifactId>org.restlet.ext.odata</artifactId>
+ <version>2.0-SNAPSHOT</version>
+
</dependency>
<dependency>
<groupId>org.restlet.dev</groupId>
diff --git a/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java b/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java
index 0a376810f9..0f272a5476 100644
--- a/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/representation/DigestTestCase.java
@@ -70,28 +70,26 @@ public Restlet createInboundRoot() {
@Override
public void handle(Request request, Response response) {
Representation rep = request.getEntity();
- DigesterRepresentation digester = rep.getDigester();
try {
// Such representation computes the digest while
// consuming the wrapped representation.
+ DigesterRepresentation digester = new DigesterRepresentation(
+ rep);
digester.exhaust();
- } catch (IOException e1) {
- }
- if (digester.checkDigest()) {
- response.setStatus(Status.SUCCESS_OK);
- StringRepresentation f = new StringRepresentation(
- "9876543210");
- digester = f.getDigester();
- try {
+ if (digester.checkDigest()) {
+ response.setStatus(Status.SUCCESS_OK);
+ StringRepresentation f = new StringRepresentation(
+ "9876543210");
+ digester = new DigesterRepresentation(f);
// Consume first
digester.exhaust();
- } catch (IOException e) {
+ // Set the digest
+ digester.setDigest(digester.computeDigest());
+ response.setEntity(digester);
+ } else {
+ response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
}
- // Set the digest
- digester.setDigest(digester.computeDigest());
- response.setEntity(digester);
- } else {
- response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
+ } catch (Exception e1) {
}
}
@@ -126,19 +124,23 @@ public void testGet() throws IOException, NoSuchAlgorithmException {
Request request = new Request(Method.PUT, "http://localhost:"
+ TEST_PORT + "/");
StringRepresentation rep = new StringRepresentation("0123456789");
- DigesterRepresentation digester = rep.getDigester();
- // Such representation computes the digest while
- // consuming the wrapped representation.
- digester.exhaust();
- // Set the digest with the computed one
- digester.setDigest(digester.computeDigest());
- request.setEntity(digester);
+ try {
+ DigesterRepresentation digester = new DigesterRepresentation(rep);
+ // Such representation computes the digest while
+ // consuming the wrapped representation.
+ digester.exhaust();
+ // Set the digest with the computed one
+ digester.setDigest(digester.computeDigest());
+ request.setEntity(digester);
- Response response = client.handle(request);
+ Response response = client.handle(request);
- assertEquals(Status.SUCCESS_OK, response.getStatus());
- digester = response.getEntity().getDigester();
- digester.exhaust();
- assertTrue(digester.checkDigest());
+ assertEquals(Status.SUCCESS_OK, response.getStatus());
+ digester = new DigesterRepresentation(response.getEntity());
+ digester.exhaust();
+ assertTrue(digester.checkDigest());
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
}
}
|
a46fd1eeab3746ce993bb67780ea0b0784467816
|
ismavatar$lateralgm
|
Changed the library system:
* Easier access
* Removed unecessary functions
* Modified affected classes
Action now references a LibAction, rather than copying all the properties from one
Created the ActionContainer class to provide common functionality to Moment and Event
git-svn-id: https://lateralgm.svn.sourceforge.net/svnroot/lateralgm@75 8f422083-7f27-0410-bc82-93e204be8cd2
|
p
|
https://github.com/ismavatar/lateralgm
|
diff --git a/LateralGM/org/lateralgm/file/Gm6File.java b/LateralGM/org/lateralgm/file/Gm6File.java
index 1adfe0f73..0d9fed91c 100644
--- a/LateralGM/org/lateralgm/file/Gm6File.java
+++ b/LateralGM/org/lateralgm/file/Gm6File.java
@@ -60,6 +60,8 @@
import org.lateralgm.resources.Sound;
import org.lateralgm.resources.Sprite;
import org.lateralgm.resources.Timeline;
+import org.lateralgm.resources.library.LibAction;
+import org.lateralgm.resources.library.LibManager;
import org.lateralgm.resources.sub.Action;
import org.lateralgm.resources.sub.Argument;
import org.lateralgm.resources.sub.BackgroundDef;
@@ -584,21 +586,35 @@ public void readGm6File(String fileName, ResNode root) throws Gm6FormatException
{
in.skip(4);
Action act = mom.addAction();
- act.libraryId = in.readi();
- act.libActionId = in.readi();
- act.actionKind = (byte) in.readi();
- act.allowRelative = in.readBool();
- act.question = in.readBool();
- act.canApplyTo = in.readBool();
- act.execType = (byte) in.readi();
- act.execFunction = in.readStr();
- act.execCode = in.readStr();
- act.noArguments = in.readi();
+ int libid = in.readi();
+ int actid = in.readi();
+ act.libAction = LibManager.getLibAction(libid,actid);
+ //The libAction will have a null parent, among other things
+ if (act.libAction == null)
+ {
+ act.libAction = new LibAction();
+ act.libAction.id = actid;
+ act.libAction.parentId = libid;
+ act.libAction.actionKind = (byte) in.readi();
+ act.libAction.allowRelative = in.readBool();
+ act.libAction.question = in.readBool();
+ act.libAction.canApplyTo = in.readBool();
+ act.libAction.execType = (byte) in.readi();
+ act.libAction.execFunction = in.readStr();
+ act.libAction.execCode = in.readStr();
+ }
+ else
+ {
+ in.skip(20);
+ in.skip(in.readi());
+ in.skip(in.readi());
+ }
+ act.arguments = new Argument[in.readi()];
int[] argkinds = new int[in.readi()];
- for (int l = 0; l < argkinds.length; l++)
- argkinds[l] = in.readi();
- int id = in.readi();
- switch (id)
+ for (int x : argkinds)
+ x = in.readi();
+ int appliesTo = in.readi();
+ switch (appliesTo)
{
case -1:
act.appliesTo = GmObject.OBJECT_SELF;
@@ -607,16 +623,18 @@ public void readGm6File(String fileName, ResNode root) throws Gm6FormatException
act.appliesTo = GmObject.OBJECT_OTHER;
break;
default:
- act.appliesTo = objids.get(id);
+ act.appliesTo = objids.get(appliesTo);
}
act.relative = in.readBool();
int actualnoargs = in.readi();
for (int l = 0; l < actualnoargs; l++)
{
- if (l < act.noArguments)
+ if (l < act.arguments.length)
{
+ act.arguments[l] = new Argument();
act.arguments[l].kind = (byte) argkinds[l];
+
String strval = in.readStr();
Resource res = tag;
switch (argkinds[l])
@@ -719,16 +737,30 @@ public void readGm6File(String fileName, ResNode root) throws Gm6FormatException
{
in.skip(4);
Action act = ev.addAction();
- act.libraryId = in.readi();
- act.libActionId = in.readi();
- act.actionKind = (byte) in.readi();
- act.allowRelative = in.readBool();
- act.question = in.readBool();
- act.canApplyTo = in.readBool();
- act.execType = (byte) in.readi();
- act.execFunction = in.readStr();
- act.execCode = in.readStr();
- act.noArguments = in.readi();
+ int libid = in.readi();
+ int actid = in.readi();
+ act.libAction = LibManager.getLibAction(libid,actid);
+ //The libAction will have a null parent, among other things
+ if (act.libAction == null)
+ {
+ act.libAction = new LibAction();
+ act.libAction.id = actid;
+ act.libAction.parentId = libid;
+ act.libAction.actionKind = (byte) in.readi();
+ act.libAction.allowRelative = in.readBool();
+ act.libAction.question = in.readBool();
+ act.libAction.canApplyTo = in.readBool();
+ act.libAction.execType = (byte) in.readi();
+ act.libAction.execFunction = in.readStr();
+ act.libAction.execCode = in.readStr();
+ }
+ else
+ {
+ in.skip(20);
+ in.skip(in.readi());
+ in.skip(in.readi());
+ }
+ act.arguments = new Argument[in.readi()];
int[] argkinds = new int[in.readi()];
for (int l = 0; l < argkinds.length; l++)
argkinds[l] = in.readi();
@@ -748,8 +780,9 @@ public void readGm6File(String fileName, ResNode root) throws Gm6FormatException
int actualnoargs = in.readi();
for (int l = 0; l < actualnoargs; l++)
{
- if (l < act.noArguments)
+ if (l < act.arguments.length)
{
+ act.arguments[l] = new Argument();
act.arguments[l].kind = (byte) argkinds[l];
String strval = in.readStr();
Resource res = tag; // see before Timeline
@@ -1241,24 +1274,21 @@ public void writeGm6File(String fileName, ResNode root)
{
Action act = mom.getAction(k);
out.writei(440);
- out.writei(act.libraryId);
- out.writei(act.libActionId);
- out.writei(act.actionKind);
- out.writeBool(act.allowRelative);
- out.writeBool(act.question);
- out.writeBool(act.canApplyTo);
- out.writei(act.execType);
- out.writeStr(act.execFunction);
- out.writeStr(act.execCode);
- out.writei(act.noArguments);
- out.writei(8);
- for (int l = 0; l < 8; l++)
- {
- if (l < act.noArguments)
- out.writei(act.arguments[l].kind);
- else
- out.writei(0);
- }
+ out.writei(act.libAction.parent != null ? act.libAction.parent.id : act.libAction.parentId);
+ out.writei(act.libAction.id);
+ out.writei(act.libAction.actionKind);
+ out.writeBool(act.libAction.allowRelative);
+ out.writeBool(act.libAction.question);
+ out.writeBool(act.libAction.canApplyTo);
+ out.writei(act.libAction.execType);
+ out.writeStr(act.libAction.execFunction);
+ out.writeStr(act.libAction.execCode);
+ out.writei(act.arguments.length);
+
+ out.writei(act.arguments.length);
+ for (Argument arg : act.arguments)
+ out.writei(arg.kind);
+
if (act.appliesTo != null)
{
if (act.appliesTo.getValue() >= 0)
@@ -1270,32 +1300,27 @@ public void writeGm6File(String fileName, ResNode root)
else
out.writei(-100);
out.writeBool(act.relative);
- out.writei(8);
- for (int l = 0; l < 8; l++)
- {
- if (l < act.noArguments)
+
+ out.writei(act.arguments.length);
+ for (Argument arg : act.arguments)
+ switch (arg.kind)
+
{
- switch (act.arguments[l].kind)
- {
- case Argument.ARG_SPRITE:
- case Argument.ARG_SOUND:
- case Argument.ARG_BACKGROUND:
- case Argument.ARG_PATH:
- case Argument.ARG_SCRIPT:
- case Argument.ARG_GMOBJECT:
- case Argument.ARG_ROOM:
- case Argument.ARG_FONT:
- case Argument.ARG_TIMELINE:
- out.writeIdStr(act.arguments[l].res,act.arguments[l].kind,this);
- break;
- default:
- out.writeStr(act.arguments[l].val);
- break;
- }
+ case Argument.ARG_SPRITE:
+ case Argument.ARG_SOUND:
+ case Argument.ARG_BACKGROUND:
+ case Argument.ARG_PATH:
+ case Argument.ARG_SCRIPT:
+ case Argument.ARG_GMOBJECT:
+ case Argument.ARG_ROOM:
+ case Argument.ARG_FONT:
+ case Argument.ARG_TIMELINE:
+ out.writeIdStr(arg.res,arg.kind,this);
+ break;
+ default:
+ out.writeStr(arg.val);
+ break;
}
- else
- out.writeStr(""); //$NON-NLS-1$
- }
out.writeBool(act.not);
}
}
@@ -1336,24 +1361,21 @@ public void writeGm6File(String fileName, ResNode root)
{
Action act = ev.getAction(l);
out.writei(440);
- out.writei(act.libraryId);
- out.writei(act.libActionId);
- out.writei(act.actionKind);
- out.writeBool(act.allowRelative);
- out.writeBool(act.question);
- out.writeBool(act.canApplyTo);
- out.writei(act.execType);
- out.writeStr(act.execFunction);
- out.writeStr(act.execCode);
- out.writei(act.noArguments);
- out.writei(8);
- for (int m = 0; m < 8; m++)
- {
- if (m < act.noArguments)
- out.writei(act.arguments[m].kind);
- else
- out.writei(0);
- }
+ out.writei(act.libAction.parent != null ? act.libAction.parent.id : act.libAction.parentId);
+ out.writei(act.libAction.id);
+ out.writei(act.libAction.actionKind);
+ out.writeBool(act.libAction.allowRelative);
+ out.writeBool(act.libAction.question);
+ out.writeBool(act.libAction.canApplyTo);
+ out.writei(act.libAction.execType);
+ out.writeStr(act.libAction.execFunction);
+ out.writeStr(act.libAction.execCode);
+ out.writei(act.arguments.length);
+
+ out.writei(act.arguments.length);
+ for (Argument arg : act.arguments)
+ out.writei(arg.kind);
+
if (act.appliesTo != null)
{
if (act.appliesTo.getValue() >= 0)
@@ -1365,32 +1387,26 @@ public void writeGm6File(String fileName, ResNode root)
else
out.writei(-100);
out.writeBool(act.relative);
- out.writei(8);
- for (int m = 0; m < 8; m++)
- {
- if (m < act.noArguments)
+ out.writei(act.arguments.length);
+ for (Argument arg : act.arguments)
+ switch (arg.kind)
+
{
- switch (act.arguments[m].kind)
- {
- case Argument.ARG_SPRITE:
- case Argument.ARG_SOUND:
- case Argument.ARG_BACKGROUND:
- case Argument.ARG_PATH:
- case Argument.ARG_SCRIPT:
- case Argument.ARG_GMOBJECT:
- case Argument.ARG_ROOM:
- case Argument.ARG_FONT:
- case Argument.ARG_TIMELINE:
- out.writeIdStr(act.arguments[m].res,act.arguments[m].kind,this);
- break;
- default:
- out.writeStr(act.arguments[m].val);
- break;
- }
+ case Argument.ARG_SPRITE:
+ case Argument.ARG_SOUND:
+ case Argument.ARG_BACKGROUND:
+ case Argument.ARG_PATH:
+ case Argument.ARG_SCRIPT:
+ case Argument.ARG_GMOBJECT:
+ case Argument.ARG_ROOM:
+ case Argument.ARG_FONT:
+ case Argument.ARG_TIMELINE:
+ out.writeIdStr(arg.res,arg.kind,this);
+ break;
+ default:
+ out.writeStr(arg.val);
+ break;
}
- else
- out.writeStr(""); //$NON-NLS-1$
- }
out.writeBool(act.not);
}
}
diff --git a/LateralGM/org/lateralgm/resources/GmObject.java b/LateralGM/org/lateralgm/resources/GmObject.java
index 548583e3e..3f754f8ac 100644
--- a/LateralGM/org/lateralgm/resources/GmObject.java
+++ b/LateralGM/org/lateralgm/resources/GmObject.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -11,6 +11,7 @@
import org.lateralgm.file.ResourceList;
import org.lateralgm.main.Prefs;
import org.lateralgm.resources.sub.Action;
+import org.lateralgm.resources.sub.Argument;
import org.lateralgm.resources.sub.Event;
import org.lateralgm.resources.sub.MainEvent;
@@ -61,25 +62,12 @@ public GmObject copy(boolean update, ResourceList src)
{
Action act = ev.getAction(k);
Action act2 = ev2.addAction();
- act2.libraryId = act.libraryId;
- act2.libActionId = act.libActionId;
- act2.actionKind = act.actionKind;
- act2.allowRelative = act.allowRelative;
- act2.question = act.question;
- act2.canApplyTo = act.canApplyTo;
- act2.execType = act.execType;
- act2.execFunction = act.execFunction;
- act2.execCode = act.execCode;
act2.relative = act.relative;
act2.not = act.not;
act2.appliesTo = act.appliesTo;
- act2.noArguments = act.noArguments;
- for (int l = 0; l < act.noArguments; l++)
- {
- act2.arguments[k].kind = act.arguments[k].kind;
- act2.arguments[k].res = act.arguments[k].res;
- act2.arguments[k].val = act.arguments[k].val;
- }
+ act2.arguments=new Argument[act.arguments.length];
+ for (int l = 0; l < act.arguments.length; l++)
+ act2.arguments[l] = new Argument(act.arguments[l].kind,act.arguments[l].val,act.arguments[l].res);
}
}
}
diff --git a/LateralGM/org/lateralgm/resources/Timeline.java b/LateralGM/org/lateralgm/resources/Timeline.java
index 989b5b6bc..20dda70f0 100644
--- a/LateralGM/org/lateralgm/resources/Timeline.java
+++ b/LateralGM/org/lateralgm/resources/Timeline.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -13,6 +13,7 @@
import org.lateralgm.file.ResourceList;
import org.lateralgm.main.Prefs;
import org.lateralgm.resources.sub.Action;
+import org.lateralgm.resources.sub.Argument;
import org.lateralgm.resources.sub.Moment;
public class Timeline extends Resource
@@ -84,25 +85,12 @@ public Timeline copy(boolean update, ResourceList src)
{
Action act = mom.getAction(j);
Action act2 = mom2.addAction();
- act2.libraryId = act.libraryId;
- act2.libActionId = act.libActionId;
- act2.actionKind = act.actionKind;
- act2.allowRelative = act.allowRelative;
- act2.question = act.question;
- act2.canApplyTo = act.canApplyTo;
- act2.execType = act.execType;
- act2.execFunction = act.execFunction;
- act2.execCode = act.execCode;
act2.relative = act.relative;
act2.not = act.not;
act2.appliesTo = act.appliesTo;
- act2.noArguments = act.noArguments;
- for (int k = 0; k < act.noArguments; k++)
- {
- act2.arguments[k].kind = act.arguments[k].kind;
- act2.arguments[k].res = act.arguments[k].res;
- act2.arguments[k].val = act.arguments[k].val;
- }
+ act2.arguments = new Argument[act.arguments.length];
+ for (int k = 0; k < act.arguments.length; k++)
+ act2.arguments[k] = new Argument(act.arguments[k].kind,act.arguments[k].val,act.arguments[k].res);
}
}
if (update)
diff --git a/LateralGM/org/lateralgm/resources/library/LibAction.java b/LateralGM/org/lateralgm/resources/library/LibAction.java
index 657205dcf..f3e930b26 100644
--- a/LateralGM/org/lateralgm/resources/library/LibAction.java
+++ b/LateralGM/org/lateralgm/resources/library/LibAction.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -12,7 +12,6 @@
import org.lateralgm.resources.sub.Action;
-
public class LibAction
{
public static final byte INTERFACE_NORMAL = 0;
@@ -22,6 +21,8 @@ public class LibAction
public static final byte INTERFACE_TEXT = 4;
public int id = 0;
+ public int parentId = -1;//Preserves the id when library is unknown
+ public Library parent = null;
public BufferedImage actImage;
public boolean hidden = false;
public boolean advanced = false;
@@ -37,14 +38,5 @@ public class LibAction
public byte execType = Action.EXEC_FUNCTION;
public String execFunction = "";
public String execCode = "";
- public int noLibArguments = 0;
- public LibArgument[] libArguments = new LibArgument[6];
-
- public LibAction()
- {
- for (int i = 0; i < 6; i++)
- {
- libArguments[i] = new LibArgument();
- }
- }
+ public LibArgument[] libArguments;
}
\ No newline at end of file
diff --git a/LateralGM/org/lateralgm/resources/library/LibManager.java b/LateralGM/org/lateralgm/resources/library/LibManager.java
index a8b124b89..e6649a74f 100644
--- a/LateralGM/org/lateralgm/resources/library/LibManager.java
+++ b/LateralGM/org/lateralgm/resources/library/LibManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -21,7 +21,6 @@
import org.lateralgm.file.GmStreamDecoder;
import org.lateralgm.messages.Messages;
-
public class LibManager
{
public static class libFilenameFilter implements FilenameFilter
@@ -32,94 +31,33 @@ public boolean accept(File dir, String name)
}
}
- private static ArrayList<Library> libs = new ArrayList<Library>();
-
- public static int NoLibs()
- {
- return libs.size();
- }
-
- private static LibAction getLibAction(int LibraryId, int LibActionId)
- {
- int no = noLibraries(LibraryId);
- for (int i = 0; i < no; i++)
- {
-// int ListIndex = LibActionIndex(LibActionId);
-// if (ListIndex != -1) return libActions.get(ListIndex);
-// return null;
-
- LibAction act = getLibrary(LibraryId,i).getLibAction(LibActionId);
- if (act != null) return act;
- }
- return null;
- }
-
- public static Library addLibrary()
- {
- Library lib = new Library();
- libs.add(lib);
- return lib;
- }
-
- public static Library getLibrary(int id, int n)
- {
- int ListIndex = LibraryIndex(id,n);
- if (ListIndex != -1) return libs.get(ListIndex);
- return null;
- }
-
- public static Library getLibraryList(int ListIndex)
- {
- if (ListIndex >= 0 && ListIndex < NoLibs()) return libs.get(ListIndex);
- return null;
- }
-
- public static int noLibraries(int id)
- {
- int nofound = 0;
- for (int i = 0; i < NoLibs(); i++)
- {
- if (getLibraryList(i).id == id)
- {
- nofound++;
- }
- }
- return nofound;
- }
+ public static ArrayList<Library> libs = new ArrayList<Library>();
- private static int LibraryIndex(int id, int n)
+ public static LibAction getLibAction(int libraryId, int libActionId)
{
- int nofound = 0;
- for (int i = 0; i < NoLibs(); i++)
+ for(Library l : libs)
{
- if (getLibraryList(i).id == id)
+ if(l.id==libraryId)
{
- if (nofound == n)
- {
- return i;
- }
- nofound++;
+ LibAction act=l.getLibAction(libActionId);
+ if(act!=null) return act;
}
}
- return -1;
- }
-
- public static void clearLibraries()
- {
- libs.clear();
+ return null;
}
+ //XXX : Maybe place the lib finding code here
public static void autoLoad(String libdir)
{
File[] files = new File(libdir).listFiles(new libFilenameFilter());
Arrays.sort(files);// listFiles does not guarantee a particular order
- for (int i = 0; i < files.length; i++)
+ for (File f : files)
{
- System.out.printf(Messages.getString("LibManager.LOADING"),files[i].getPath()); //$NON-NLS-1$
+ System.out.printf(Messages.getString("LibManager.LOADING"),f.getPath()); //$NON-NLS-1$
System.out.println();
try
{
- LoadLibFile(files[i].getPath());
+ LoadLibFile(f.getPath());
}
catch (LibFormatException ex)
{
@@ -141,21 +79,19 @@ public static Library LoadLibFile(String FileName) throws LibFormatException
throw new LibFormatException(String.format(
Messages.getString("LibManager.ERROR_INVALIDFILE"),FileName)); //$NON-NLS-1$
}
- // System.out.println("GM version: "+version);
lib = new Library();
- lib.tabCaption = in.readStr();// System.out.println("tab caption is: "+lib.TabCaption);
- lib.id = in.readi();// System.out.println("lib id is: "+lib.Id);
- in.skip(in.readi());// Author
- in.skip(4);// lib version
- in.skip(8);// last changed
- in.skip(in.readi());// info
- in.skip(in.readi());// initialisation code
- lib.advanced = in.readBool();// System.out.println("advanced lib: "+lib.Advanced);
+ lib.tabCaption = in.readStr();
+ lib.id = in.readi();
+ in.skip(in.readi());
+ in.skip(4);
+ in.skip(8);
+ in.skip(in.readi());
+ in.skip(in.readi());
+ lib.advanced = in.readBool();
in.skip(4);// no of actions/official lib identifier thingy
- int noacts = in.readi();// System.out.println("no of actions: "+noacts);
+ int noacts = in.readi();
for (int j = 0; j < noacts; j++)
{
- // System.out.println("Action Entry "+j+"------------------");
int ver = in.readi();
if (ver != 520)
{
@@ -164,58 +100,49 @@ public static Library LoadLibFile(String FileName) throws LibFormatException
}
LibAction act = new LibAction();
+ act.parent = lib;
lib.libActions.add(act);
in.skip(in.readi());// name
- act.id = in.readi();// System.out.println("Action id is: "+act.Id);
+ act.id = in.readi();
byte[] data = new byte[in.readi()];
in.read(data);
act.actImage = ImageIO.read(new ByteArrayInputStream(data));
- act.hidden = in.readBool();// System.out.println("hidden: "+act.Hidden);
- act.advanced = in.readBool();// System.out.println("advanced: "+act.Advanced);
- act.registeredOnly = in.readBool();// System.out.println("registered only: "+act.RegisteredOnly);
- act.description = in.readStr();// System.out.println("description: "+act.Description);
- act.listText = in.readStr();// System.out.println("list text: "+act.ListText);
- act.hintText = in.readStr();// System.out.println("hint text :"+act.HintText);
- act.actionKind = (byte) in.readi();// System.out.println("action kind: "+act.ActionKind);
- act.interfaceKind = (byte) in.readi();// System.out.println("interface: "+act.InterfaceKind);
- act.question = in.readBool();// System.out.println("question: "+act.Question);
- act.canApplyTo = in.readBool();// System.out.println("show apply to: "+act.CanApplyTo);
- act.allowRelative = in.readBool();// System.out.println("show relative: "+act.AllowRelative);
- act.noLibArguments = in.readi();// System.out.println("no of arguments: "+act.NoLibArguments);
- // System.out.println("___________________");
+ act.hidden = in.readBool();
+ act.advanced = in.readBool();
+ act.registeredOnly = in.readBool();
+ act.description = in.readStr();
+ act.listText = in.readStr();
+ act.hintText = in.readStr();
+ act.actionKind = (byte) in.readi();
+ act.interfaceKind = (byte) in.readi();
+ act.question = in.readBool();
+ act.canApplyTo = in.readBool();
+ act.allowRelative = in.readBool();
+ act.libArguments = new LibArgument[in.readi()];
int noinsertions = in.readi();
for (int k = 0; k < noinsertions; k++)
{
- if (k < act.noLibArguments)
+ if (k < act.libArguments.length)
{
- LibArgument arg = act.libArguments[k];
- arg.caption = in.readStr();// System.out.println("argument "+k+" caption: "+arg.Caption);
- arg.kind = (byte) in.readi();// System.out.println("argument "+k+" kind: "+arg.Kind);
- arg.defaultVal = in.readStr();// System.out.println("argument "+k+" default value:
- // "+arg.DefaultVal);
+ LibArgument arg = act.libArguments[k] = new LibArgument();
+ arg.caption = in.readStr();
+ arg.kind = (byte) in.readi();
+ arg.defaultVal = in.readStr();
arg.menu = in.readStr();
- /*
- * if (arg.Kind==Argument.ARG_MENU) { System.out.println("argument "+k+" menu string is:
- * "+arg.Menu); } if (k==act.NoLibArguments-1) { System.out.println("___________________\n"); }
- * else { System.out.println("___________________"); }
- */
}
else
{
- in.skip(in.readi());// skip arg caption
- in.skip(4);// skip argument kind
- in.skip(in.readi());// skip Default value
- in.skip(in.readi());// skip Menu string
+ in.skip(in.readi());
+ in.skip(4);
+ in.skip(in.readi());
+ in.skip(in.readi());
}
}
act.execType = (byte) in.readi();
- // System.out.println("read in exec type: "+act.ExecType);
act.execFunction = in.readStr();
- // System.out.println("read in exec function str: "+act.ExecFunction);
act.execCode = in.readStr();
- // System.out.println("read in exec code: "+act.ExecCode);
}
}
catch (FileNotFoundException ex)
diff --git a/LateralGM/org/lateralgm/resources/library/Library.java b/LateralGM/org/lateralgm/resources/library/Library.java
index de4513bfe..549e3ea77 100644
--- a/LateralGM/org/lateralgm/resources/library/Library.java
+++ b/LateralGM/org/lateralgm/resources/library/Library.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -17,14 +17,14 @@ public class Library
public boolean advanced = false;
public ArrayList<LibAction> libActions = new ArrayList<LibAction>();
- private LibAction addLibAction2()
+ private LibAction addLibAction()
{
LibAction act = new LibAction();
libActions.add(act);
return act;
}
- private LibAction getLibAction(int id)
+ public LibAction getLibAction(int id)
{
for (int i = 0; i < libActions.size(); i++)
if (libActions.get(i).id == id)
diff --git a/LateralGM/org/lateralgm/resources/sub/Action.java b/LateralGM/org/lateralgm/resources/sub/Action.java
index 4d41fdbe4..5a0042186 100644
--- a/LateralGM/org/lateralgm/resources/sub/Action.java
+++ b/LateralGM/org/lateralgm/resources/sub/Action.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -10,6 +10,7 @@
import org.lateralgm.resources.GmObject;
import org.lateralgm.resources.ResId;
+import org.lateralgm.resources.library.LibAction;
import org.lateralgm.resources.library.Library;
public class Action
@@ -30,30 +31,13 @@ public class Action
public static final byte EXEC_FUNCTION = 1;
public static final byte EXEC_CODE = 2;
- // LibAction properties for resave
- public Library library = null;
- public int libActionId = 101;
- public byte actionKind = ACT_NORMAL;
- public boolean allowRelative = false;
- public boolean question = false;
- public boolean canApplyTo = false;
- public byte execType = EXEC_FUNCTION;
- public String execFunction = "";
- public String execCode = "";
+
+ public LibAction libAction;
// The actual Action properties
public boolean relative = false;
public boolean not = false;
public ResId appliesTo = GmObject.OBJECT_SELF;
- public int noArguments = 0;
- public Argument[] arguments = new Argument[6];
-
- public Action()
- {
- for (int j = 0; j < 6; j++)
- {
- arguments[j] = new Argument();
- }
- }
+ public Argument[] arguments;
}
\ No newline at end of file
diff --git a/LateralGM/org/lateralgm/resources/sub/ActionContainer.java b/LateralGM/org/lateralgm/resources/sub/ActionContainer.java
new file mode 100644
index 000000000..0e353736b
--- /dev/null
+++ b/LateralGM/org/lateralgm/resources/sub/ActionContainer.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2007 Clam <[email protected]>
+ *
+ * This file is part of Lateral GM.
+ * Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
+ * See LICENSE for details.
+ */
+
+package org.lateralgm.resources.sub;
+
+import java.util.ArrayList;
+
+import org.lateralgm.resources.library.LibAction;
+
+public abstract class ActionContainer
+ {
+ private ArrayList<Action> actions = new ArrayList<Action>();
+
+ public int NoActions()
+ {
+ return actions.size();
+ }
+
+ public Action addAction()
+ {
+ Action act = new Action();
+ actions.add(act);
+ return act;
+ }
+
+ // adds an action set to the properties of given LibAction
+ public Action addAction(LibAction libAction)
+ {
+ Action act = new Action();
+ for (int i = 0; i < libAction.libArguments.length; i++)
+ {
+ act.arguments[i].kind = libAction.libArguments[i].kind;
+ switch (act.arguments[i].kind)
+ {
+ case Argument.ARG_SPRITE:
+ case Argument.ARG_SOUND:
+ case Argument.ARG_BACKGROUND:
+ case Argument.ARG_PATH:
+ case Argument.ARG_SCRIPT:
+ case Argument.ARG_GMOBJECT:
+ case Argument.ARG_ROOM:
+ case Argument.ARG_FONT:
+ case Argument.ARG_TIMELINE:
+ act.arguments[i].res = null;
+ break;
+ default:
+ act.arguments[i].val = libAction.libArguments[i].defaultVal;
+ break;
+ }
+ }
+ actions.add(act);
+ return act;
+ }
+
+ public Action getAction(int ListIndex)
+ {
+ if (ListIndex >= 0 && ListIndex < NoActions()) return actions.get(ListIndex);
+ return null;
+ }
+
+ public void removeAction(int ListIndex)
+ {
+ if (ListIndex >= 0 && ListIndex < NoActions()) actions.remove(ListIndex);
+ }
+
+ public void clearActions()
+ {
+ actions.clear();
+ }
+ }
diff --git a/LateralGM/org/lateralgm/resources/sub/Argument.java b/LateralGM/org/lateralgm/resources/sub/Argument.java
index 623156c9f..4fb79e72b 100644
--- a/LateralGM/org/lateralgm/resources/sub/Argument.java
+++ b/LateralGM/org/lateralgm/resources/sub/Argument.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -33,4 +33,15 @@ public class Argument
public byte kind = ARG_EXPRESSION;
public String val = "";
public ResId res = null;// for references to Resources
+
+ public Argument(byte kind, String val, ResId res)
+ {
+ this.kind = kind;
+ this.val = val;
+ this.res = res;
+ }
+
+ public Argument()
+ {
+ }
}
\ No newline at end of file
diff --git a/LateralGM/org/lateralgm/resources/sub/Event.java b/LateralGM/org/lateralgm/resources/sub/Event.java
index 0376ee75c..4b1155ce9 100644
--- a/LateralGM/org/lateralgm/resources/sub/Event.java
+++ b/LateralGM/org/lateralgm/resources/sub/Event.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -8,13 +8,9 @@
package org.lateralgm.resources.sub;
-import java.util.ArrayList;
-
import org.lateralgm.resources.ResId;
-import org.lateralgm.resources.library.LibAction;
-import org.lateralgm.resources.library.LibManager;
-public class Event
+public class Event extends ActionContainer
{
// mouse event types
public static final byte EV_LEFT_BUTTON = 0;
@@ -107,76 +103,4 @@ public class Event
public int id = 0;
public ResId other = null;// For collision Events
- private ArrayList<Action> actions = new ArrayList<Action>();
-
- public int NoActions()
- {
- return actions.size();
- }
-
- public Action addAction()
- {
- Action act = new Action();
- actions.add(act);
- return act;
- }
-
- // adds an action preset to the properties of given LibAction
- public Action addAction(int LibId, LibAction lact)
- {
- Action act = new Action();
- LibAction lact = LibManager.getLibAction(LibId,libActionId);
- if (lact != null)
- {
- act.libActionId = lact.id;
- act.library = LibId;
- act.actionKind = lact.actionKind;
- act.question = lact.question;
- act.canApplyTo = lact.canApplyTo;
- act.allowRelative = lact.allowRelative;
- act.execType = lact.execType;
- act.execFunction = lact.execFunction;
- act.execCode = lact.execCode;
- act.noArguments = lact.noLibArguments;
- for (int i = 0; i < lact.noLibArguments; i++)
- {
- act.arguments[i].kind = lact.libArguments[i].kind;
- switch (act.arguments[i].kind)
- {
- case Argument.ARG_SPRITE:
- case Argument.ARG_SOUND:
- case Argument.ARG_BACKGROUND:
- case Argument.ARG_PATH:
- case Argument.ARG_SCRIPT:
- case Argument.ARG_GMOBJECT:
- case Argument.ARG_ROOM:
- case Argument.ARG_FONT:
- case Argument.ARG_TIMELINE:
- act.arguments[i].res = null;
- break;
- default:
- act.arguments[i].val = lact.libArguments[i].defaultVal;
- break;
- }
- }
- }
- actions.add(act);
- return act;
- }
-
- public Action getAction(int ListIndex)
- {
- if (ListIndex >= 0 && ListIndex < NoActions()) return actions.get(ListIndex);
- return null;
- }
-
- public void removeAction(int ListIndex)
- {
- if (ListIndex >= 0 && ListIndex < NoActions()) actions.remove(ListIndex);
- }
-
- public void clearActions()
- {
- actions.clear();
- }
}
diff --git a/LateralGM/org/lateralgm/resources/sub/Moment.java b/LateralGM/org/lateralgm/resources/sub/Moment.java
index 7bf93b2d1..425956d36 100644
--- a/LateralGM/org/lateralgm/resources/sub/Moment.java
+++ b/LateralGM/org/lateralgm/resources/sub/Moment.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2006 Clam <[email protected]>
+ * Copyright (C) 2006, 2007 Clam <[email protected]>
*
* This file is part of Lateral GM.
* Lateral GM is free software and comes with ABSOLUTELY NO WARRANTY.
@@ -8,84 +8,7 @@
package org.lateralgm.resources.sub;
-import java.util.ArrayList;
-
-import org.lateralgm.resources.library.LibAction;
-import org.lateralgm.resources.library.LibManager;
-
-public class Moment
+public class Moment extends ActionContainer
{
- private ArrayList<Action> actions = new ArrayList<Action>();
public int stepNo = 0;
-
- public int NoActions()
- {
- return actions.size();
- }
-
- public Action addAction()
- {
- Action act = new Action();
- actions.add(act);
- return act;
- }
-
- // adds an action set to the properties of given LibAction
- public Action addAction(int LibId, int LibActionId)
- {
- Action act = new Action();
- LibAction lact = LibManager.getLibAction(LibId,LibActionId);
- if (lact != null)
- {
- act.libActionId = LibActionId;
- act.libraryId = LibId;
- act.actionKind = lact.actionKind;
- act.question = lact.question;
- act.canApplyTo = lact.canApplyTo;
- act.allowRelative = lact.allowRelative;
- act.execType = lact.execType;
- act.execFunction = lact.execFunction;
- act.execCode = lact.execCode;
- act.noArguments = lact.noLibArguments;
- for (int i = 0; i < lact.noLibArguments; i++)
- {
- act.arguments[i].kind = lact.libArguments[i].kind;
- switch (act.arguments[i].kind)
- {
- case Argument.ARG_SPRITE:
- case Argument.ARG_SOUND:
- case Argument.ARG_BACKGROUND:
- case Argument.ARG_PATH:
- case Argument.ARG_SCRIPT:
- case Argument.ARG_GMOBJECT:
- case Argument.ARG_ROOM:
- case Argument.ARG_FONT:
- case Argument.ARG_TIMELINE:
- act.arguments[i].res = null;
- break;
- default:
- act.arguments[i].val = lact.libArguments[i].defaultVal;
- break;
- }
- }
- }
- actions.add(act);
- return act;
- }
-
- public Action getAction(int ListIndex)
- {
- if (ListIndex >= 0 && ListIndex < NoActions()) return actions.get(ListIndex);
- return null;
- }
-
- public void removeAction(int ListIndex)
- {
- if (ListIndex >= 0 && ListIndex < NoActions()) actions.remove(ListIndex);
- }
-
- public void clearActions()
- {
- actions.clear();
- }
}
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.