conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
try {
SubMonitor subMonitor = SubMonitor.convert(monitor,
Messages.bind(Messages.importRewrite_processDescription), 2);
if (!hasRecordedChanges()) {
this.createdImports= CharOperation.NO_STRINGS;
this.createdStaticImports= CharOperation.NO_STRINGS;
return new MultiTextEdit();
}
CompilationUnit usedAstRoot= this.astRoot;
if (usedAstRoot == null) {
ASTParser parser= ASTParser.newParser(AST.JLS9);
parser.setSource(this.compilationUnit);
parser.setFocalPosition(0); // reduced AST
parser.setResolveBindings(false);
usedAstRoot= (CompilationUnit) parser.createAST(subMonitor.split(1));
}
ImportRewriteConfiguration config= buildImportRewriteConfiguration();
ImportRewriteAnalyzer computer=
new ImportRewriteAnalyzer(this.compilationUnit, usedAstRoot, config);
for (String addedImport : this.addedImports) {
boolean isStatic = STATIC_PREFIX == addedImport.charAt(0);
String qualifiedName = addedImport.substring(1);
computer.addImport(isStatic, qualifiedName);
}
for (String removedImport : this.removedImports) {
boolean isStatic = STATIC_PREFIX == removedImport.charAt(0);
String qualifiedName = removedImport.substring(1);
computer.removeImport(isStatic, qualifiedName);
}
for (String typeExplicitSimpleName : this.typeExplicitSimpleNames) {
computer.requireExplicitImport(false, typeExplicitSimpleName);
}
for (String staticExplicitSimpleName : this.staticExplicitSimpleNames) {
computer.requireExplicitImport(true, staticExplicitSimpleName);
}
ImportRewriteAnalyzer.RewriteResult result= computer.analyzeRewrite(subMonitor.split(1));
this.createdImports= result.getCreatedImports();
this.createdStaticImports= result.getCreatedStaticImports();
return result.getTextEdit();
} finally {
if (monitor != null) {
monitor.done();
}
=======
SubMonitor subMonitor = SubMonitor.convert(monitor,
Messages.bind(Messages.importRewrite_processDescription), 2);
if (!hasRecordedChanges()) {
this.createdImports= CharOperation.NO_STRINGS;
this.createdStaticImports= CharOperation.NO_STRINGS;
return new MultiTextEdit();
}
CompilationUnit usedAstRoot= this.astRoot;
if (usedAstRoot == null) {
ASTParser parser= ASTParser.newParser(AST.JLS8);
parser.setSource(this.compilationUnit);
parser.setFocalPosition(0); // reduced AST
parser.setResolveBindings(false);
usedAstRoot= (CompilationUnit) parser.createAST(subMonitor.split(1));
}
ImportRewriteConfiguration config= buildImportRewriteConfiguration();
ImportRewriteAnalyzer computer=
new ImportRewriteAnalyzer(this.compilationUnit, usedAstRoot, config);
for (String addedImport : this.addedImports) {
boolean isStatic = STATIC_PREFIX == addedImport.charAt(0);
String qualifiedName = addedImport.substring(1);
computer.addImport(isStatic, qualifiedName);
}
for (String removedImport : this.removedImports) {
boolean isStatic = STATIC_PREFIX == removedImport.charAt(0);
String qualifiedName = removedImport.substring(1);
computer.removeImport(isStatic, qualifiedName);
}
for (String typeExplicitSimpleName : this.typeExplicitSimpleNames) {
computer.requireExplicitImport(false, typeExplicitSimpleName);
}
for (String staticExplicitSimpleName : this.staticExplicitSimpleNames) {
computer.requireExplicitImport(true, staticExplicitSimpleName);
>>>>>>>
SubMonitor subMonitor = SubMonitor.convert(monitor,
Messages.bind(Messages.importRewrite_processDescription), 2);
if (!hasRecordedChanges()) {
this.createdImports= CharOperation.NO_STRINGS;
this.createdStaticImports= CharOperation.NO_STRINGS;
return new MultiTextEdit();
}
CompilationUnit usedAstRoot= this.astRoot;
if (usedAstRoot == null) {
ASTParser parser= ASTParser.newParser(AST.JLS9);
parser.setSource(this.compilationUnit);
parser.setFocalPosition(0); // reduced AST
parser.setResolveBindings(false);
usedAstRoot= (CompilationUnit) parser.createAST(subMonitor.split(1));
}
ImportRewriteConfiguration config= buildImportRewriteConfiguration();
ImportRewriteAnalyzer computer=
new ImportRewriteAnalyzer(this.compilationUnit, usedAstRoot, config);
for (String addedImport : this.addedImports) {
boolean isStatic = STATIC_PREFIX == addedImport.charAt(0);
String qualifiedName = addedImport.substring(1);
computer.addImport(isStatic, qualifiedName);
}
for (String removedImport : this.removedImports) {
boolean isStatic = STATIC_PREFIX == removedImport.charAt(0);
String qualifiedName = removedImport.substring(1);
computer.removeImport(isStatic, qualifiedName);
}
for (String typeExplicitSimpleName : this.typeExplicitSimpleNames) {
computer.requireExplicitImport(false, typeExplicitSimpleName);
}
for (String staticExplicitSimpleName : this.staticExplicitSimpleNames) {
computer.requireExplicitImport(true, staticExplicitSimpleName); |
<<<<<<<
/*
/**********************************************************************
/* Immutable config, factories
/**********************************************************************
*/
=======
private final static long DEFAULT_MAPPER_FEATURES = MapperFeature.collectLongDefaults();
>>>>>>>
/*
/**********************************************************************
/* Immutable config, factories
/**********************************************************************
*/
<<<<<<<
protected final TypeFactory _typeFactory;
=======
private final static long AUTO_DETECT_MASK =
MapperFeature.AUTO_DETECT_FIELDS.getLongMask()
| MapperFeature.AUTO_DETECT_GETTERS.getLongMask()
| MapperFeature.AUTO_DETECT_IS_GETTERS.getLongMask()
| MapperFeature.AUTO_DETECT_SETTERS.getLongMask()
| MapperFeature.AUTO_DETECT_CREATORS.getLongMask()
;
>>>>>>>
protected final TypeFactory _typeFactory;
<<<<<<<
_typeFactory = src._typeFactory;
_classIntrospector = src._classIntrospector;
_typeResolverProvider = src._typeResolverProvider;
=======
_mixIns = src._mixIns;
_subtypeResolver = src._subtypeResolver;
_rootNames = src._rootNames;
_rootName = src._rootName;
_view = src._view;
_attributes = src._attributes;
_configOverrides = src._configOverrides;
}
protected MapperConfigBase(MapperConfigBase<CFG,T> src, long mapperFeatures)
{
super(src, mapperFeatures);
_mixIns = src._mixIns;
>>>>>>>
_typeFactory = src._typeFactory;
_classIntrospector = src._classIntrospector;
_typeResolverProvider = src._typeResolverProvider;
<<<<<<<
=======
/**
* @since 2.9 (in this case, demoted from sub-classes)
*/
protected abstract T _withMapperFeatures(long mapperFeatures);
/*
/**********************************************************
/* Additional shared fluent factory methods; features
/**********************************************************
*/
/**
* Fluent factory method that will construct and return a new configuration
* object instance with specified features enabled.
*/
@SuppressWarnings("unchecked")
@Override
public final T with(MapperFeature... features)
{
long newMapperFlags = _mapperFeatures;
for (MapperFeature f : features) {
newMapperFlags |= f.getLongMask();
}
if (newMapperFlags == _mapperFeatures) {
return (T) this;
}
return _withMapperFeatures(newMapperFlags);
}
/**
* Fluent factory method that will construct and return a new configuration
* object instance with specified features disabled.
*/
@SuppressWarnings("unchecked")
@Override
public final T without(MapperFeature... features)
{
long newMapperFlags = _mapperFeatures;
for (MapperFeature f : features) {
newMapperFlags &= ~f.getLongMask();
}
if (newMapperFlags == _mapperFeatures) {
return (T) this;
}
return _withMapperFeatures(newMapperFlags);
}
@SuppressWarnings("unchecked")
@Override
public final T with(MapperFeature feature, boolean state)
{
long newMapperFlags;
if (state) {
newMapperFlags = _mapperFeatures | feature.getLongMask();
} else {
newMapperFlags = _mapperFeatures & ~feature.getLongMask();
}
if (newMapperFlags == _mapperFeatures) {
return (T) this;
}
return _withMapperFeatures(newMapperFlags);
}
>>>>>>> |
<<<<<<<
static int[] RestrictedIdentifierSealedRule;
static int[] RestrictedIdentifierPermitsRule;
=======
static int SwitchLabelCaseLhsRule = 0;
>>>>>>>
static int SwitchLabelCaseLhsRule = 0;
static int[] RestrictedIdentifierSealedRule;
static int[] RestrictedIdentifierPermitsRule;
<<<<<<<
static Goal RestrictedIdentifierSealedGoal;
static Goal RestrictedIdentifierPermitsGoal;
static int[] RestrictedIdentifierSealedFollow = { TokenNameclass, TokenNameinterface,
TokenNameenum, TokenNameRestrictedIdentifierrecord };// Note: enum/record allowed as error flagging rules.
static int[] RestrictedIdentifierPermitsFollow = { TokenNameLBRACE };
=======
static Goal SwitchLabelCaseLhsGoal;
>>>>>>>
static Goal SwitchLabelCaseLhsGoal;
static Goal RestrictedIdentifierSealedGoal;
static Goal RestrictedIdentifierPermitsGoal;
static int[] RestrictedIdentifierSealedFollow = { TokenNameclass, TokenNameinterface,
TokenNameenum, TokenNameRestrictedIdentifierrecord };// Note: enum/record allowed as error flagging rules.
static int[] RestrictedIdentifierPermitsFollow = { TokenNameLBRACE };
<<<<<<<
else
if ("Modifiersopt".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
ridSealed.add(i);
else
if ("PermittedSubclasses".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
ridPermits.add(i);
=======
else
if ("SwitchLabelCaseLhs".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
SwitchLabelCaseLhsRule = i;
>>>>>>>
else
if ("Modifiersopt".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
ridSealed.add(i);
else
if ("PermittedSubclasses".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
ridPermits.add(i);
else
if ("SwitchLabelCaseLhs".equals(Parser.name[Parser.non_terminal_index[Parser.lhs[i]]])) //$NON-NLS-1$
SwitchLabelCaseLhsRule = i;
<<<<<<<
RestrictedIdentifierSealedGoal = new Goal(TokenNameRestrictedIdentifiersealed, RestrictedIdentifierSealedFollow, RestrictedIdentifierSealedRule);
RestrictedIdentifierPermitsGoal = new Goal(TokenNameRestrictedIdentifierpermits, RestrictedIdentifierPermitsFollow, RestrictedIdentifierPermitsRule);
=======
SwitchLabelCaseLhsGoal = new Goal(TokenNameARROW, new int [0], SwitchLabelCaseLhsRule);
>>>>>>>
SwitchLabelCaseLhsGoal = new Goal(TokenNameARROW, new int [0], SwitchLabelCaseLhsRule);
RestrictedIdentifierSealedGoal = new Goal(TokenNameRestrictedIdentifiersealed, RestrictedIdentifierSealedFollow, RestrictedIdentifierSealedRule);
RestrictedIdentifierPermitsGoal = new Goal(TokenNameRestrictedIdentifierpermits, RestrictedIdentifierPermitsFollow, RestrictedIdentifierPermitsRule);
<<<<<<<
int disambiguatesRestrictedIdentifierWithLookAhead(Predicate<Integer> checkPrecondition, int restrictedIdentifierToken, Goal goal) {
if (checkPrecondition.test(restrictedIdentifierToken)) {
VanguardParser vp = getNewVanguardParser();
VanguardScanner vs = (VanguardScanner) vp.scanner;
vs.resetTo(this.currentPosition, this.eofPosition - 1);
if (vp.parse(goal) == VanguardParser.SUCCESS)
return restrictedIdentifierToken;
}
return TokenNameIdentifier;
}
=======
private VanguardScanner getNewVanguardScanner(char[] src) {
VanguardScanner vs = new VanguardScanner(this.sourceLevel, this.complianceLevel, this.previewEnabled);
vs.setSource(src);
vs.resetTo(0, src.length, isInModuleDeclaration(), this.scanContext);
return vs;
}
private VanguardParser getNewVanguardParser(char[] src) {
VanguardScanner vs = getNewVanguardScanner(src);
VanguardParser vp = new VanguardParser(vs);
vs.setActiveParser(vp);
return vp;
}
>>>>>>>
int disambiguatesRestrictedIdentifierWithLookAhead(Predicate<Integer> checkPrecondition, int restrictedIdentifierToken, Goal goal) {
if (checkPrecondition.test(restrictedIdentifierToken)) {
VanguardParser vp = getNewVanguardParser();
VanguardScanner vs = (VanguardScanner) vp.scanner;
vs.resetTo(this.currentPosition, this.eofPosition - 1);
if (vp.parse(goal) == VanguardParser.SUCCESS)
return restrictedIdentifierToken;
}
return TokenNameIdentifier;
}
private VanguardScanner getNewVanguardScanner(char[] src) {
VanguardScanner vs = new VanguardScanner(this.sourceLevel, this.complianceLevel, this.previewEnabled);
vs.setSource(src);
vs.resetTo(0, src.length, isInModuleDeclaration(), this.scanContext);
return vs;
}
private VanguardParser getNewVanguardParser(char[] src) {
VanguardScanner vs = getNewVanguardScanner(src);
VanguardParser vp = new VanguardParser(vs);
vs.setActiveParser(vp);
return vp;
} |
<<<<<<<
@Override
=======
public TypeBinding patchType(TypeBinding newType) {
// Perform upwards projection on type wrt mentioned type variables
TypeBinding[] mentionedTypeVariables= findCapturedTypeVariables(newType);
if (mentionedTypeVariables != null && mentionedTypeVariables.length > 0) {
newType = newType.upwardsProjection(this.binding.declaringScope, mentionedTypeVariables);
}
this.type.resolvedType = newType;
if (this.binding != null) {
this.binding.type = newType;
this.binding.markInitialized();
}
return this.type.resolvedType;
}
private TypeVariableBinding[] findCapturedTypeVariables(TypeBinding typeBinding) {
final Set<TypeVariableBinding> mentioned = new HashSet<>();
TypeBindingVisitor.visit(new TypeBindingVisitor() {
@Override
public boolean visit(TypeVariableBinding typeVariable) {
if (typeVariable.isCapture())
mentioned.add(typeVariable);
return super.visit(typeVariable);
}
}, typeBinding);
if (mentioned.isEmpty()) return null;
return mentioned.toArray(new TypeVariableBinding[mentioned.size()]);
}
private static Expression findPolyExpression(Expression e) {
// This is simpler than using an ASTVisitor, since we only care about a very few select cases.
if (e instanceof FunctionalExpression) {
return e;
}
if (e instanceof ConditionalExpression) {
ConditionalExpression ce = (ConditionalExpression)e;
Expression candidate = findPolyExpression(ce.valueIfTrue);
if (candidate == null) {
candidate = findPolyExpression(ce.valueIfFalse);
}
if (candidate != null) return candidate;
}
return null;
}
>>>>>>>
public TypeBinding patchType(TypeBinding newType) {
// Perform upwards projection on type wrt mentioned type variables
TypeBinding[] mentionedTypeVariables= findCapturedTypeVariables(newType);
if (mentionedTypeVariables != null && mentionedTypeVariables.length > 0) {
newType = newType.upwardsProjection(this.binding.declaringScope, mentionedTypeVariables);
}
this.type.resolvedType = newType;
if (this.binding != null) {
this.binding.type = newType;
this.binding.markInitialized();
}
return this.type.resolvedType;
}
private TypeVariableBinding[] findCapturedTypeVariables(TypeBinding typeBinding) {
final Set<TypeVariableBinding> mentioned = new HashSet<>();
TypeBindingVisitor.visit(new TypeBindingVisitor() {
@Override
public boolean visit(TypeVariableBinding typeVariable) {
if (typeVariable.isCapture())
mentioned.add(typeVariable);
return super.visit(typeVariable);
}
}, typeBinding);
if (mentioned.isEmpty()) return null;
return mentioned.toArray(new TypeVariableBinding[mentioned.size()]);
}
private static Expression findPolyExpression(Expression e) {
// This is simpler than using an ASTVisitor, since we only care about a very few select cases.
if (e instanceof FunctionalExpression) {
return e;
}
if (e instanceof ConditionalExpression) {
ConditionalExpression ce = (ConditionalExpression)e;
Expression candidate = findPolyExpression(ce.valueIfTrue);
if (candidate == null) {
candidate = findPolyExpression(ce.valueIfFalse);
}
if (candidate != null) return candidate;
}
return null;
}
@Override
<<<<<<<
@Override
=======
/*
* Checks the initializer for simple errors, and reports an error as needed. If error is found,
* returns a reasonable match for further type checking.
*/
private TypeBinding checkInferredLocalVariableInitializer(BlockScope scope) {
TypeBinding errorType = null;
if (this.initialization instanceof ArrayInitializer) {
scope.problemReporter().varLocalCannotBeArrayInitalizers(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1); // Treat as array of anything
} else {
// Catch-22: isPolyExpression() is not reliable BEFORE resolveType, so we need to peek to suppress the errors
Expression polyExpression = findPolyExpression(this.initialization);
if (polyExpression instanceof ReferenceExpression) {
scope.problemReporter().varLocalCannotBeMethodReference(this);
errorType = TypeBinding.NULL;
} else if (polyExpression != null) { // Should be instanceof LambdaExpression, but this is safer
scope.problemReporter().varLocalCannotBeLambda(this);
errorType = TypeBinding.NULL;
}
}
if (this.type.dimensions() > 0 || this.type.extraDimensions() > 0) {
scope.problemReporter().varLocalCannotBeArray(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1); // This is just to quell some warnings
}
if ((this.bits & ASTNode.IsAdditionalDeclarator) != 0) {
scope.problemReporter().varLocalMultipleDeclarators(this);
errorType = this.initialization.resolveType(scope);
}
return errorType;
}
>>>>>>>
/*
* Checks the initializer for simple errors, and reports an error as needed. If error is found,
* returns a reasonable match for further type checking.
*/
private TypeBinding checkInferredLocalVariableInitializer(BlockScope scope) {
TypeBinding errorType = null;
if (this.initialization instanceof ArrayInitializer) {
scope.problemReporter().varLocalCannotBeArrayInitalizers(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1); // Treat as array of anything
} else {
// Catch-22: isPolyExpression() is not reliable BEFORE resolveType, so we need to peek to suppress the errors
Expression polyExpression = findPolyExpression(this.initialization);
if (polyExpression instanceof ReferenceExpression) {
scope.problemReporter().varLocalCannotBeMethodReference(this);
errorType = TypeBinding.NULL;
} else if (polyExpression != null) { // Should be instanceof LambdaExpression, but this is safer
scope.problemReporter().varLocalCannotBeLambda(this);
errorType = TypeBinding.NULL;
}
}
if (this.type.dimensions() > 0 || this.type.extraDimensions() > 0) {
scope.problemReporter().varLocalCannotBeArray(this);
errorType = scope.createArrayType(scope.getJavaLangObject(), 1); // This is just to quell some warnings
}
if ((this.bits & ASTNode.IsAdditionalDeclarator) != 0) {
scope.problemReporter().varLocalMultipleDeclarators(this);
errorType = this.initialization.resolveType(scope);
}
return errorType;
}
@Override |
<<<<<<<
expectedProblemAttributes.put("VarIsNotAllowedHere", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarIsReserved", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarIsReservedInFuture", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArray", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArrayInitalizers", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalCannotBeLambda", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalCannotBeMethodReference", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalInitializedToNull", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalInitializedToVoid", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalMultipleDeclarators", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalReferencesItself", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArray", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalWithoutInitizalier", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
=======
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionConstructor", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionField", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionMethod", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionType", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
>>>>>>>
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionConstructor", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionField", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionMethod", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("UsingTerminallyDeprecatedSinceVersionType", new ProblemAttributes(CategorizedProblem.CAT_DEPRECATION));
expectedProblemAttributes.put("VarIsNotAllowedHere", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarIsReserved", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarIsReservedInFuture", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArray", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArrayInitalizers", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalCannotBeLambda", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalCannotBeMethodReference", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalInitializedToNull", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalInitializedToVoid", new ProblemAttributes(CategorizedProblem.CAT_TYPE));
expectedProblemAttributes.put("VarLocalMultipleDeclarators", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalReferencesItself", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalCannotBeArray", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX));
expectedProblemAttributes.put("VarLocalWithoutInitizalier", new ProblemAttributes(CategorizedProblem.CAT_SYNTAX)); |
<<<<<<<
// TODO(sxenos): the old code always passed null as the third argument to setupExternalAnnotationProvider,
// but this looks like a bug. I've preserved it for now but we need to figure out what was supposed to go
// there.
if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
JavaProject javaProject = (JavaProject) getAncestor(IJavaElement.JAVA_PROJECT);
IClasspathEntry entry = javaProject.getClasspathEntryFor(getPath());
if (entry != null) {
PackageFragment pkg = (PackageFragment) getParent();
String entryName = Util.concatWith(pkg.names, getElementName(), '/');
entryName = new String(CharArrayUtils.concat(
JavaNames.fieldDescriptorToBinaryName(descriptor.fieldDescriptor), SuffixConstants.SUFFIX_CLASS));
IProject project = javaProject.getProject();
IPath externalAnnotationPath = ClasspathEntry.getExternalAnnotationPath(entry, project, false); // unresolved for use in ExternalAnnotationTracker
if (externalAnnotationPath != null) {
result = setupExternalAnnotationProvider(project, externalAnnotationPath, null, result,
=======
PackageFragment pkg = (PackageFragment) getParent();
IJavaElement grandparent = pkg.getParent();
if (grandparent instanceof JarPackageFragmentRoot) {
JarPackageFragmentRoot root = (JarPackageFragmentRoot) grandparent;
if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
JavaProject javaProject = (JavaProject) getAncestor(IJavaElement.JAVA_PROJECT);
IClasspathEntry entry = javaProject.getClasspathEntryFor(getPath());
if (entry != null) {
String entryName = new String(CharArrayUtils.concat(
JavaNames.fieldDescriptorToBinaryName(descriptor.fieldDescriptor), SuffixConstants.SUFFIX_CLASS));
IProject project = javaProject.getProject();
IPath externalAnnotationPath = ClasspathEntry.getExternalAnnotationPath(entry, project, false); // unresolved for use in ExternalAnnotationTracker
if (externalAnnotationPath != null) {
result = setupExternalAnnotationProvider(project, externalAnnotationPath, result,
>>>>>>>
if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
JavaProject javaProject = (JavaProject) getAncestor(IJavaElement.JAVA_PROJECT);
IClasspathEntry entry = javaProject.getClasspathEntryFor(getPath());
if (entry != null) {
PackageFragment pkg = (PackageFragment) getParent();
String entryName = Util.concatWith(pkg.names, getElementName(), '/');
entryName = new String(CharArrayUtils.concat(
JavaNames.fieldDescriptorToBinaryName(descriptor.fieldDescriptor), SuffixConstants.SUFFIX_CLASS));
IProject project = javaProject.getProject();
IPath externalAnnotationPath = ClasspathEntry.getExternalAnnotationPath(entry, project, false); // unresolved for use in ExternalAnnotationTracker
if (externalAnnotationPath != null) {
result = setupExternalAnnotationProvider(project, externalAnnotationPath, result, |
<<<<<<<
* Copyright (c) 2006, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
=======
* Copyright (c) 2006, 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
>>>>>>>
* Copyright (c) 2006, 2018 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0 |
<<<<<<<
if (this.isJimage) return false; // TODO: Revisit
return this.zipFile.getEntry(qualifiedTypeName+'.'+ExternalAnnotationProvider.ANNOTION_FILE_EXTENSION) != null;
=======
return this.zipFile.getEntry(qualifiedTypeName+ExternalAnnotationProvider.ANNOTATION_FILE_SUFFIX) != null;
>>>>>>>
if (this.isJimage) return false; // TODO: Revisit
return this.zipFile.getEntry(qualifiedTypeName+ExternalAnnotationProvider.ANNOTATION_FILE_SUFFIX) != null; |
<<<<<<<
import java.io.IOException;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.SerializerProvider;
=======
>>>>>>>
<<<<<<<
super(handledType);
}
@Override
public boolean isEmpty(SerializerProvider prov, Object value) {
return value.toString().isEmpty();
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider)
throws IOException
{
gen.writeString(value.toString());
}
/* 01-Mar-2011, tatu: We were serializing as "raw" String; but generally that
* is not what we want, since lack of type information would imply real
* String type.
*/
/**
* Default implementation will write type prefix, call regular serialization
* method (since assumption is that value itself does not need JSON
* Array or Object start/end markers), and then write type suffix.
* This should work for most cases; some sub-classes may want to
* change this behavior.
*/
@Override
public void serializeWithType(Object value, JsonGenerator g, SerializerProvider provider,
TypeSerializer typeSer)
throws IOException
{
WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
typeSer.typeId(value, JsonToken.VALUE_STRING));
serialize(value, g, provider);
typeSer.writeTypeSuffix(g, typeIdDef);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
visitStringFormat(visitor, typeHint);
=======
super(handledType);
}
@Override
public final String valueToString(Object value) {
return value.toString();
>>>>>>>
super(handledType);
}
@Override
public String valueToString(Object value) {
return value.toString(); |
<<<<<<<
=======
import com.fasterxml.jackson.databind.util.ArrayBuilders;
import com.fasterxml.jackson.databind.util.ClassUtil;
>>>>>>>
import com.fasterxml.jackson.databind.util.ClassUtil;
<<<<<<<
ctxt.reportBadDefinition(_beanType, String.format(
"Invalid Object Id definition for %s: cannot find property with name '%s'",
handledType().getName(), propName));
=======
provider.reportBadDefinition(_beanType, String.format(
"Invalid Object Id definition for %s: cannot find property with name %s",
ClassUtil.nameOf(handledType()), ClassUtil.name(propName)));
>>>>>>>
ctxt.reportBadDefinition(_beanType, String.format(
"Invalid Object Id definition for %s: cannot find property with name %s",
ClassUtil.getTypeDescription(_beanType), ClassUtil.name(propName))); |
<<<<<<<
=======
import java.util.Arrays;
import java.util.List;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
>>>>>>>
import org.eclipse.jdt.core.IJavaElement;
<<<<<<<
=======
import org.eclipse.jdt.internal.compiler.env.IModule.IModuleReference;
import org.eclipse.jdt.internal.core.AbstractModule;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.PackageFragmentRoot;
>>>>>>>
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jdt.internal.core.PackageFragmentRoot; |
<<<<<<<
* Copyright (c) 2006, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
=======
* Copyright (c) 2006, 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
>>>>>>>
* Copyright (c) 2006, 2018 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0 |
<<<<<<<
* Copyright (c) 2000, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
=======
* Copyright (c) 2000, 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
>>>>>>>
* Copyright (c) 2000, 2018 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0 |
<<<<<<<
public void test528818a() throws CoreException, IOException {
if (!AbstractJavaModelTests.isJRE9) {
return;
}
try {
IJavaProject project = createJava9Project("P");
waitForAutoBuild();
IType type = project.findType("java.lang.annotation.Target");
assertNotNull("Type should not be null", type);
String[][] resolveType = type.resolveType("java.lang.Object");
assertNotNull("Type should not be null", resolveType);
} finally {
deleteProject("P");
}
}
=======
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=479963
public void test531046a() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args[0];\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.indexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046b() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args[0];\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046c() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args;\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "[Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046d() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = new java.util.HashMap<String, Object>();\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.util.HashMap<Ljava.lang.String;Ljava.lang.Object;>;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046e() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = new java.util.HashMap<String, Object>();\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "var";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
assertEquals("should not be empty", 1, elements.length);
IType type = (IType) elements[0];
assertEquals("incorrect type", "java.util.HashMap<java.lang.String,java.lang.Object>", type.getFullyQualifiedParameterizedName());
} finally {
deleteProject("P");
}
}
>>>>>>>
public void test528818a() throws CoreException, IOException {
if (!AbstractJavaModelTests.isJRE9) {
return;
}
try {
IJavaProject project = createJava9Project("P");
waitForAutoBuild();
IType type = project.findType("java.lang.annotation.Target");
assertNotNull("Type should not be null", type);
String[][] resolveType = type.resolveType("java.lang.Object");
assertNotNull("Type should not be null", resolveType);
} finally {
deleteProject("P");
}
}
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=479963
public void test531046a() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args[0];\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.indexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046b() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args[0];\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046c() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = args;\n"
+ " System.out.println(s1);\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "[Ljava.lang.String;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046d() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = new java.util.HashMap<String, Object>();\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "s1";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
ILocalVariable variable = (ILocalVariable) elements[0];
elements = unit.findElements(variable);
assertNotNull("Should not be null", elements);
assertEquals("incorrect type", "Ljava.util.HashMap<Ljava.lang.String;Ljava.lang.Object;>;", variable.getTypeSignature());
} finally {
deleteProject("P");
}
}
public void test531046e() throws CoreException, IOException {
if (!isJRE9) return;
try {
createJava10Project("P", new String[] {"src"});
String source = "package p;\n"
+ "public class X {\n"
+ " public static void main(java.lang.String[] args) {\n"
+ " var s1 = new java.util.HashMap<String, Object>();\n"
+ " }\n"
+ "}\n";
createFolder("/P/src/p");
createFile("/P/src/p/X.java", source);
waitForAutoBuild();
ICompilationUnit unit = getCompilationUnit("/P/src/p/X.java");
String select = "var";
IJavaElement[] elements = unit.codeSelect(source.lastIndexOf(select), select.length());
assertEquals("should not be empty", 1, elements.length);
IType type = (IType) elements[0];
assertEquals("incorrect type", "java.util.HashMap<java.lang.String,java.lang.Object>", type.getFullyQualifiedParameterizedName());
} finally {
deleteProject("P");
}
} |
<<<<<<<
this.env = env;
=======
if (externalAnnotationPath != null)
this.externalAnnotationPath = externalAnnotationPath.toOSString();
>>>>>>>
this.env = env;
if (externalAnnotationPath != null)
this.externalAnnotationPath = externalAnnotationPath.toOSString();
<<<<<<<
reader.moduleName = this.module == null ? null : this.module.name();
=======
String fileNameWithoutExtension = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - SuffixConstants.SUFFIX_CLASS.length);
if (this.externalAnnotationPath != null) {
try {
this.annotationZipFile = reader.setExternalAnnotationProvider(this.externalAnnotationPath, fileNameWithoutExtension, this.annotationZipFile, null);
} catch (IOException e) {
// don't let error on annotations fail class reading
}
}
>>>>>>>
reader.moduleName = this.module == null ? null : this.module.name();
String fileNameWithoutExtension = qualifiedBinaryFileName.substring(0, qualifiedBinaryFileName.length() - SuffixConstants.SUFFIX_CLASS.length);
if (this.externalAnnotationPath != null) {
try {
this.annotationZipFile = reader.setExternalAnnotationProvider(this.externalAnnotationPath, fileNameWithoutExtension, this.annotationZipFile, null);
} catch (IOException e) {
// don't let error on annotations fail class reading
}
} |
<<<<<<<
return new ResourceCompilationUnit(file, null) {
=======
return new ResourceCompilationUnit(file) {
@Override
>>>>>>>
return new ResourceCompilationUnit(file, null) {
@Override |
<<<<<<<
@Override
=======
/*
* @see ASTVisitor#visit(ModuleModifier)
* @since 3.14
*/
>>>>>>>
@Override
/*
* @see ASTVisitor#visit(ModuleModifier)
* @since 3.14
*/ |
<<<<<<<
@Override
=======
public boolean visit(
LocalDeclaration localDeclaration, BlockScope scope) {
if (localDeclaration.type instanceof SingleTypeReference && ((SingleTypeReference)localDeclaration.type).token == assistIdentifier)
throw new SelectionNodeFound(localDeclaration.binding.type);
return true; // do nothing by default, keep traversing
}
>>>>>>>
@Override
public boolean visit(
LocalDeclaration localDeclaration, BlockScope scope) {
if (localDeclaration.type instanceof SingleTypeReference && ((SingleTypeReference)localDeclaration.type).token == assistIdentifier)
throw new SelectionNodeFound(localDeclaration.binding.type);
return true; // do nothing by default, keep traversing
}
@Override
<<<<<<<
IOrdinaryClassFile iClassFile = context.getClassFile();
if (iClassFile instanceof ClassFile) {
ClassFile classFile = (ClassFile) iClassFile;
ClassFileReader reader = null;
if (classFile.getPackageFragmentRoot() instanceof JrtPackageFragmentRoot) {
IBinaryType binaryTypeInfo = classFile.getBinaryTypeInfo();
if (binaryTypeInfo instanceof ClassFileReader) {
reader = (ClassFileReader) binaryTypeInfo;
}
} else {
BinaryTypeDescriptor descriptor = BinaryTypeFactory.createDescriptor(classFile);
try {
reader = BinaryTypeFactory.rawReadType(descriptor, false/*don't fully initialize so as to keep constant pool (used below)*/);
} catch (ClassFormatException e) {
if (JavaCore.getPlugin().isDebugging()) {
e.printStackTrace(System.err);
}
}
=======
IClassFile iClassFile = context.getClassFile();
if (iClassFile instanceof ClassFile) {
ClassFile classFile = (ClassFile) iClassFile;
BinaryTypeDescriptor descriptor = BinaryTypeFactory.createDescriptor(classFile);
ClassFileReader reader = null;
try {
reader = BinaryTypeFactory.rawReadType(descriptor, false/*don't fully initialize so as to keep constant pool (used below)*/);
} catch (ClassFormatException e) {
if (JavaCore.getPlugin().isDebugging()) {
e.printStackTrace(System.err);
}
>>>>>>>
IOrdinaryClassFile iClassFile = context.getClassFile();
if (iClassFile instanceof ClassFile) {
ClassFile classFile = (ClassFile) iClassFile;
ClassFileReader reader = null;
if (classFile.getPackageFragmentRoot() instanceof JrtPackageFragmentRoot) {
IBinaryType binaryTypeInfo = classFile.getBinaryTypeInfo();
if (binaryTypeInfo instanceof ClassFileReader) {
reader = (ClassFileReader) binaryTypeInfo;
}
} else {
BinaryTypeDescriptor descriptor = BinaryTypeFactory.createDescriptor(classFile);
try {
reader = BinaryTypeFactory.rawReadType(descriptor, false/*don't fully initialize so as to keep constant pool (used below)*/);
} catch (ClassFormatException e) {
if (JavaCore.getPlugin().isDebugging()) {
e.printStackTrace(System.err);
}
} |
<<<<<<<
* Copyright (c) 2000, 2017 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
=======
* Copyright (c) 2000, 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
>>>>>>>
* Copyright (c) 2000, 2018 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0 |
<<<<<<<
import java.util.HashMap;
=======
import java.util.Arrays;
>>>>>>>
import java.util.HashMap;
import java.util.Arrays;
<<<<<<<
char[] sourceArray;
private IRegion[] formatRegions;
=======
private char[] sourceArray;
private List<IRegion> formatRegions;
>>>>>>>
char[] sourceArray;
private List<IRegion> formatRegions;
<<<<<<<
List<Token> prepareFormattedCode(String source, int kind) {
if (!init(source, kind))
=======
List<Token> prepareFormattedCode(String source) {
this.formatRegions = Arrays.asList(new Region(0, source.length()));
return prepareFormattedCode(source, CodeFormatter.K_UNKNOWN);
}
private List<Token> prepareFormattedCode(String source, int kind) {
if (!init(source))
>>>>>>>
List<Token> prepareFormattedCode(String source) {
this.formatRegions = Arrays.asList(new Region(0, source.length()));
return prepareFormattedCode(source, CodeFormatter.K_UNKNOWN);
}
private List<Token> prepareFormattedCode(String source, int kind) {
if (!init(source, kind)) |
<<<<<<<
=======
final boolean findImplicit;
>>>>>>>
final boolean findImplicit;
<<<<<<<
CreatorCollectionState ccState)
throws JsonMappingException
=======
CreatorCollectionState ccState, boolean findImplicit)
throws JsonMappingException
>>>>>>>
CreatorCollectionState ccState, boolean findImplicit)
throws JsonMappingException
<<<<<<<
boolean visible = (ctor.getParameterCount() == 1)
? vchecker.isScalarConstructorVisible(ctor)
: vchecker.isCreatorVisible(ctor);
if (visible) {
ccState.addImplicitConstructorCandidate(CreatorCandidate.construct(config,
=======
if (findImplicit && vchecker.isCreatorVisible(ctor)) {
ccState.addImplicitConstructorCandidate(CreatorCandidate.construct(intr,
>>>>>>>
boolean visible = (ctor.getParameterCount() == 1)
? vchecker.isScalarConstructorVisible(ctor)
: vchecker.isCreatorVisible(ctor);
if (visible) {
ccState.addImplicitConstructorCandidate(CreatorCandidate.construct(config,
<<<<<<<
if ((argCount == 1) && vchecker.isCreatorVisible(factory)) {
ccState.addImplicitFactoryCandidate(CreatorCandidate.construct(config, factory, null));
=======
if (findImplicit && (argCount == 1) && vchecker.isCreatorVisible(factory)) {
ccState.addImplicitFactoryCandidate(CreatorCandidate.construct(intr, factory, null));
>>>>>>>
if (findImplicit && (argCount == 1) && vchecker.isCreatorVisible(factory)) {
ccState.addImplicitFactoryCandidate(CreatorCandidate.construct(config, factory, null)); |
<<<<<<<
updateNestInfo();
=======
FieldDeclaration[] fieldsDecls = this.fields;
if (fieldsDecls != null) {
for (FieldDeclaration fieldDeclaration : fieldsDecls)
fieldDeclaration.resolveJavadoc(this.initializerScope);
}
AbstractMethodDeclaration[] methodDecls = this.methods;
if (methodDecls != null) {
for (AbstractMethodDeclaration methodDeclaration : methodDecls)
methodDeclaration.resolveJavadoc();
}
>>>>>>>
updateNestInfo();
FieldDeclaration[] fieldsDecls = this.fields;
if (fieldsDecls != null) {
for (FieldDeclaration fieldDeclaration : fieldsDecls)
fieldDeclaration.resolveJavadoc(this.initializerScope);
}
AbstractMethodDeclaration[] methodDecls = this.methods;
if (methodDecls != null) {
for (AbstractMethodDeclaration methodDeclaration : methodDecls)
methodDeclaration.resolveJavadoc();
} |
<<<<<<<
if (packageBinding == null) { // have not looked for it before
if ((packageBinding = findPackage(name, mod)) != null) {
return packageBinding;
}
if (referenceBinding != null && referenceBinding != LookupEnvironment.TheNotFoundType) {
return referenceBinding; // found cached missing type - check if package conflict
}
addNotFoundPackage(name);
}
=======
>>>>>>>
<<<<<<<
//This call (to askForType) should be the last option to call, because the call is very expensive regarding performance
// (a search for secondary types may get triggered which requires to parse all classes of a package).
if ((referenceBinding = this.environment.askForType(this, name, mod)) != null) {
=======
if ((referenceBinding = this.environment.askForType(this, name)) != null) {
>>>>>>>
if ((referenceBinding = this.environment.askForType(this, name, mod)) != null) { |
<<<<<<<
import org.junit.Assert;
=======
import org.junit.AfterClass;
import org.junit.BeforeClass;
>>>>>>>
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass; |
<<<<<<<
import io.joynr.messaging.mqtt.settings.LimitAndBackpressureSettings;
=======
import io.joynr.messaging.mqtt.statusmetrics.MqttStatusReceiver;
>>>>>>>
import io.joynr.messaging.mqtt.settings.LimitAndBackpressureSettings;
import io.joynr.messaging.mqtt.statusmetrics.MqttStatusReceiver; |
<<<<<<<
String replyToMqttAddress = message.getReplyTo();
=======
String replyToMqttAddress = message.getHeaderValue(JoynrMessage.HEADER_NAME_REPLY_CHANNELID);
// because the message is received via global transport, isGloballyVisible must be true
final boolean isGloballyVisible = true;
>>>>>>>
String replyToMqttAddress = message.getReplyTo();
// because the message is received via global transport, isGloballyVisible must be true
final boolean isGloballyVisible = true;
<<<<<<<
messageRouter.addNextHop(message.getSender(), RoutingTypesUtil.fromAddressString(replyToMqttAddress));
=======
messageRouter.addNextHop(message.getFrom(),
RoutingTypesUtil.fromAddressString(replyToMqttAddress),
isGloballyVisible);
>>>>>>>
messageRouter.addNextHop(message.getSender(),
RoutingTypesUtil.fromAddressString(replyToMqttAddress),
isGloballyVisible); |
<<<<<<<
Mockito.doAnswer(new Answer<Object>() { //TODO simulate resolve here ! subscription reply bastern ... handle subscriptionreply ausführen..
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
BroadcastSubscribeInvocation request = (BroadcastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
})
.when(subscriptionManager)
.registerBroadcastSubscription(any(String.class),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
Mockito.any(BroadcastSubscribeInvocation.class));
=======
Mockito.doAnswer(new Answer<Object>() { //TODO simulate resolve here ! subscription reply bastern ... handle subscriptionreply ausführen..
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
BroadcastSubscribeInvocation request = (BroadcastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
}).when(subscriptionManager).registerBroadcastSubscription(any(String.class),
(Set<String>) argThat(contains(toParticipantId)),
Mockito.any(BroadcastSubscribeInvocation.class));
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
MulticastSubscribeInvocation request = (MulticastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
}).when(subscriptionManager).registerMulticastSubscription(any(String.class),
(Set<String>) argThat(contains(toParticipantId)),
Mockito.any(MulticastSubscribeInvocation.class));
domain = "TestDomain";
>>>>>>>
Mockito.doAnswer(new Answer<Object>() { //TODO simulate resolve here ! subscription reply bastern ... handle subscriptionreply ausführen..
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
BroadcastSubscribeInvocation request = (BroadcastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
})
.when(subscriptionManager)
.registerBroadcastSubscription(any(String.class),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
Mockito.any(BroadcastSubscribeInvocation.class));
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
MulticastSubscribeInvocation request = (MulticastSubscribeInvocation) args[2];
if (request.getSubscriptionId() == null) {
request.setSubscriptionId(UUID.randomUUID().toString());
}
request.getFuture().resolve(request.getSubscriptionId());
return null;
}
})
.when(subscriptionManager)
.registerMulticastSubscription(any(String.class),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
Mockito.any(MulticastSubscribeInvocation.class));
<<<<<<<
verify(subscriptionManager, times(1)).registerBroadcastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
=======
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<String>) argThat(contains(toParticipantId)),
>>>>>>>
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
<<<<<<<
verify(subscriptionManager, times(1)).registerBroadcastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
=======
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<String>) argThat(contains(toParticipantId)),
>>>>>>>
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
<<<<<<<
verify(subscriptionManager, times(1)).registerBroadcastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries),
=======
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<String>) argThat(contains(toParticipantId)),
>>>>>>>
verify(subscriptionManager, times(1)).registerMulticastSubscription(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
// eq(toDiscoveryEntries), |
<<<<<<<
import static com.google.inject.util.Modules.override;
=======
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
>>>>>>>
import static com.google.inject.util.Modules.override;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
<<<<<<<
injector = Guice.createInjector(override(new MqttPahoModule()).with(new AbstractModule() {
@Override
protected void configure() {
if (mqttStatusReceiver != null) {
bind(MqttStatusReceiver.class).toInstance(mqttStatusReceiver);
}
}
}), new JoynrPropertiesModule(properties), new AbstractModule() {
@Override
protected void configure() {
bind(MessageRouter.class).toInstance(mockMessageRouter);
bind(ScheduledExecutorService.class).annotatedWith(Names.named(MessageRouter.SCHEDULEDTHREADPOOL))
.toInstance(Executors.newScheduledThreadPool(10));
bind(RawMessagingPreprocessor.class).to(NoOpRawMessagingPreprocessor.class);
Multibinder.newSetBinder(binder(), new TypeLiteral<JoynrMessageProcessor>() {
});
}
});
=======
private JoynrMqttClient createMqttClientInternal() {
injector = Guice.createInjector(new MqttPahoModule(),
new JoynrPropertiesModule(properties),
new AbstractModule() {
@Override
protected void configure() {
bind(MessageRouter.class).toInstance(mockMessageRouter);
bind(ScheduledExecutorService.class).annotatedWith(Names.named(MessageRouter.SCHEDULEDTHREADPOOL))
.toInstance(Executors.newScheduledThreadPool(10));
bind(RawMessagingPreprocessor.class).to(NoOpRawMessagingPreprocessor.class);
Multibinder.newSetBinder(binder(),
new TypeLiteral<JoynrMessageProcessor>() {
});
}
});
>>>>>>>
private JoynrMqttClient createMqttClientInternal(final MqttStatusReceiver mqttStatusReceiver) {
injector = Guice.createInjector(override(new MqttPahoModule()).with(new AbstractModule() {
@Override
protected void configure() {
if (mqttStatusReceiver != null) {
bind(MqttStatusReceiver.class).toInstance(mqttStatusReceiver);
}
}
}), new JoynrPropertiesModule(properties), new AbstractModule() {
@Override
protected void configure() {
bind(MessageRouter.class).toInstance(mockMessageRouter);
bind(ScheduledExecutorService.class).annotatedWith(Names.named(MessageRouter.SCHEDULEDTHREADPOOL))
.toInstance(Executors.newScheduledThreadPool(10));
bind(RawMessagingPreprocessor.class).to(NoOpRawMessagingPreprocessor.class);
Multibinder.newSetBinder(binder(), new TypeLiteral<JoynrMessageProcessor>() {
});
}
});
<<<<<<<
// This test was disabled, because it runs perfectly on a local machine but not in the CI.
// Further investigations are required to stabilize this test.
@Test
@Ignore
public void testClientNotifiesStatusReceiverAboutBrokerDisconnect() throws Exception {
final MqttStatusReceiver mqttStatusReceiver = mock(MqttStatusReceiver.class);
@SuppressWarnings("unused")
final JoynrMqttClient mqttClient = createMqttClientWithoutSubscription(false, mqttStatusReceiver);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
stopBroker();
Thread.sleep(1000);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.NOT_CONNECTED);
startBroker();
Thread.sleep(2000);
verify(mqttStatusReceiver, times(2)).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
}
@Test
public void testClientNotifiesStatusReceiverAboutShutdownDisconnect() throws Exception {
final MqttStatusReceiver mqttStatusReceiver = mock(MqttStatusReceiver.class);
final JoynrMqttClient mqttClient = createMqttClientWithoutSubscription(false, mqttStatusReceiver);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
mqttClient.shutdown();
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.NOT_CONNECTED);
}
=======
@Test
public void mqttClientTestShutdownIfDisconnectFromMQTT() throws Exception {
properties.put(MqttModule.PROPERTY_KEY_MQTT_BROKER_URI, "tcp://localhost:1111");
properties.put(MqttModule.PROPERTY_KEY_MQTT_RECONNECT_SLEEP_MS, "100");
// create and start client
final JoynrMqttClient client = createMqttClientInternal();
final Semaphore semaphoreBeforeStartMethod = new Semaphore(0);
final Semaphore semaphoreAfterStartMethod = new Semaphore(0);
final int timeout = 500;
Runnable myRunnable = new Runnable() {
@Override
public void run() {
semaphoreBeforeStartMethod.release();
client.start();
semaphoreAfterStartMethod.release();
}
};
new Thread(myRunnable).start();
assertTrue(semaphoreBeforeStartMethod.tryAcquire(timeout, TimeUnit.MILLISECONDS));
// At this level semaphore supposed to be not released
// because when we call shutdown we are still in start()
assertFalse(semaphoreAfterStartMethod.tryAcquire());
client.shutdown();
assertTrue(semaphoreAfterStartMethod.tryAcquire(timeout, TimeUnit.MILLISECONDS));
}
>>>>>>>
// This test was disabled, because it runs perfectly on a local machine but not in the CI.
// Further investigations are required to stabilize this test.
@Test
@Ignore
public void testClientNotifiesStatusReceiverAboutBrokerDisconnect() throws Exception {
final MqttStatusReceiver mqttStatusReceiver = mock(MqttStatusReceiver.class);
@SuppressWarnings("unused")
final JoynrMqttClient mqttClient = createMqttClientWithoutSubscription(false, mqttStatusReceiver);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
stopBroker();
Thread.sleep(1000);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.NOT_CONNECTED);
startBroker();
Thread.sleep(2000);
verify(mqttStatusReceiver, times(2)).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
}
@Test
public void testClientNotifiesStatusReceiverAboutShutdownDisconnect() throws Exception {
final MqttStatusReceiver mqttStatusReceiver = mock(MqttStatusReceiver.class);
final JoynrMqttClient mqttClient = createMqttClientWithoutSubscription(false, mqttStatusReceiver);
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.CONNECTED);
mqttClient.shutdown();
verify(mqttStatusReceiver).notifyConnectionStatusChanged(MqttStatusReceiver.ConnectionStatus.NOT_CONNECTED);
}
@Test
public void mqttClientTestShutdownIfDisconnectFromMQTT() throws Exception {
properties.put(MqttModule.PROPERTY_KEY_MQTT_BROKER_URI, "tcp://localhost:1111");
properties.put(MqttModule.PROPERTY_KEY_MQTT_RECONNECT_SLEEP_MS, "100");
// create and start client
final JoynrMqttClient client = createMqttClientInternal(mock(MqttStatusReceiver.class));
final Semaphore semaphoreBeforeStartMethod = new Semaphore(0);
final Semaphore semaphoreAfterStartMethod = new Semaphore(0);
final int timeout = 500;
Runnable myRunnable = new Runnable() {
@Override
public void run() {
semaphoreBeforeStartMethod.release();
client.start();
semaphoreAfterStartMethod.release();
}
};
new Thread(myRunnable).start();
assertTrue(semaphoreBeforeStartMethod.tryAcquire(timeout, TimeUnit.MILLISECONDS));
// At this level semaphore supposed to be not released
// because when we call shutdown we are still in start()
assertFalse(semaphoreAfterStartMethod.tryAcquire());
client.shutdown();
assertTrue(semaphoreAfterStartMethod.tryAcquire(timeout, TimeUnit.MILLISECONDS));
} |
<<<<<<<
private final MqttClientFactory mqttClientFactory;
private final MqttAddress ownAddress;
private final ConcurrentMap<String, AtomicInteger> multicastSubscriptionCount;
private final MqttTopicPrefixProvider mqttTopicPrefixProvider;
private final RawMessagingPreprocessor rawMessagingPreprocessor;
private final Set<JoynrMessageProcessor> messageProcessors;
private final Set<String> incomingMqttRequests;
private final AtomicLong droppedMessagesCount;
=======
private MqttClientFactory mqttClientFactory;
private MqttAddress ownAddress;
private ConcurrentMap<String, AtomicInteger> multicastSubscriptionCount = Maps.newConcurrentMap();
private MqttTopicPrefixProvider mqttTopicPrefixProvider;
private RawMessagingPreprocessor rawMessagingPreprocessor;
private Set<JoynrMessageProcessor> messageProcessors;
private Set<String> incomingMqttRequests;
private AtomicLong droppedMessagesCount;
private MqttStatusReceiver mqttStatusReceiver;
>>>>>>>
private final MqttClientFactory mqttClientFactory;
private final MqttAddress ownAddress;
private final ConcurrentMap<String, AtomicInteger> multicastSubscriptionCount;
private final MqttTopicPrefixProvider mqttTopicPrefixProvider;
private final RawMessagingPreprocessor rawMessagingPreprocessor;
private final Set<JoynrMessageProcessor> messageProcessors;
private final Set<String> incomingMqttRequests;
private final AtomicLong droppedMessagesCount;
private MqttStatusReceiver mqttStatusReceiver;
<<<<<<<
this.multicastSubscriptionCount = Maps.newConcurrentMap();
=======
this.mqttStatusReceiver = mqttStatusReceiver;
>>>>>>>
this.multicastSubscriptionCount = Maps.newConcurrentMap();
this.mqttStatusReceiver = mqttStatusReceiver; |
<<<<<<<
import java.util.LinkedHashSet;
=======
import java.util.Set;
>>>>>>>
import java.util.LinkedHashSet;
import java.util.Set;
<<<<<<<
import io.joynr.statusmetrics.MessageWorkerStatus;
import io.joynr.statusmetrics.StatusReceiver;
=======
import io.joynr.runtime.ShutdownNotifier;
>>>>>>>
import io.joynr.statusmetrics.MessageWorkerStatus;
import io.joynr.statusmetrics.StatusReceiver;
import io.joynr.runtime.ShutdownNotifier;
<<<<<<<
@Mock
private StatusReceiver statusReceiver;
=======
@Mock
private ShutdownNotifier shutdownNotifier;
>>>>>>>
@Mock
private StatusReceiver statusReceiver;
@Mock
private ShutdownNotifier shutdownNotifier;
<<<<<<<
@Test
public void testMessageWorkerStatusUpdatedWhenMessageWasQueued() throws Exception {
ArgumentCaptor<MessageWorkerStatus> messageWorkerStatusCaptor = ArgumentCaptor.forClass(MessageWorkerStatus.class);
messageRouter.route(joynrMessage.getImmutableMessage());
Thread.sleep(250);
verify(statusReceiver, atLeast(1)).updateMessageWorkerStatus(eq(0), messageWorkerStatusCaptor.capture());
// Workaround: At the beginning, the abstract message router queues two initial updates ("waiting for message") with the
// same timestamp. Remove this duplicate by inserting all values into a LinkedHashSet which preserves the order of insertion.
LinkedHashSet<MessageWorkerStatus> uniqueStatusUpdates = new LinkedHashSet<MessageWorkerStatus>(messageWorkerStatusCaptor.getAllValues());
MessageWorkerStatus[] statusUpdates = uniqueStatusUpdates.toArray(new MessageWorkerStatus[0]);
assertEquals(3, statusUpdates.length);
assertEquals(true, statusUpdates[0].isWaitingForMessage());
assertEquals(false, statusUpdates[1].isWaitingForMessage());
assertEquals(true, statusUpdates[2].isWaitingForMessage());
}
=======
@Test
public void testScheduleMessage() throws InterruptedException {
final DelayQueue<DelayableImmutableMessage> messageQueue = spy(new DelayQueue<DelayableImmutableMessage>());
Module messageQueueSpyModule = Modules.override(testModule).with(new AbstractModule() {
@Override
protected void configure() {
bind(new TypeLiteral<DelayQueue<DelayableImmutableMessage>>() {
}).toInstance(messageQueue);
}
});
messageRouter = Guice.createInjector(messageQueueSpyModule).getInstance(MessageRouter.class);
Address address = new Address();
ImmutableMessage message = Mockito.mock(ImmutableMessage.class);
when(message.isTtlAbsolute()).thenReturn(true);
when(message.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(60000L).getValue());
when(message.getRecipient()).thenReturn("to");
when(routingTable.get("to")).thenReturn(address);
messageRouter.route(message);
ArgumentCaptor<DelayableImmutableMessage> passedDelaybleMessage = ArgumentCaptor.forClass(DelayableImmutableMessage.class);
verify(messageQueue, atLeast(1)).put(passedDelaybleMessage.capture());
assertEquals(message, passedDelaybleMessage.getAllValues().get(0).getMessage());
assertTrue(passedDelaybleMessage.getAllValues().get(0).getDelay(TimeUnit.MILLISECONDS) <= 0);
}
@Test
public void testShutdown() throws InterruptedException {
verify(shutdownNotifier).registerForShutdown((CcMessageRouter) messageRouter);
}
@Test(timeout = 3000)
public void testFailedTransmitDoesNotLeadToThreadStarvation() throws Exception {
final int MESSAGE_LOAD = 10;
ImmutableMessage failingMessage = mock(ImmutableMessage.class);
when(failingMessage.isTtlAbsolute()).thenReturn(true);
when(failingMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
when(failingMessage.getRecipient()).thenReturn("to");
when(routingTable.get("to")).thenReturn(channelAddress);
Set<Address> addressSet = new HashSet<>();
addressSet.add(channelAddress);
Mockito.doReturn(addressSet).when(addressManager).getAddresses(failingMessage);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertEquals(invocation.getArguments().length, 3);
FailureAction failureAction = (FailureAction) invocation.getArguments()[2];
failureAction.execute(new Exception("Some error"));
return null;
}
}).when(messagingStubMock).transmit(eq(failingMessage), any(SuccessAction.class), any(FailureAction.class));
for (int i = 0; i < MESSAGE_LOAD; i++) {
messageRouter.route(failingMessage);
}
Thread.sleep(2000);
verify(messagingStubMock, atLeast(MESSAGE_LOAD * 3)).transmit(eq(failingMessage),
any(SuccessAction.class),
any(FailureAction.class));
ImmutableMessage anotherMessage = mock(ImmutableMessage.class);
when(anotherMessage.isTtlAbsolute()).thenReturn(true);
when(anotherMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
when(anotherMessage.getRecipient()).thenReturn("to");
Mockito.doReturn(addressSet).when(addressManager).getAddresses(anotherMessage);
final Semaphore semaphore = new Semaphore(0);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertEquals(invocation.getArguments().length, 3);
SuccessAction successAction = (SuccessAction) invocation.getArguments()[1];
successAction.execute();
semaphore.release();
return null;
}
}).when(messagingStubMock).transmit(eq(anotherMessage), any(SuccessAction.class), any(FailureAction.class));
messageRouter.route(anotherMessage);
assertTrue(semaphore.tryAcquire(100, TimeUnit.MILLISECONDS));
}
>>>>>>>
@Test
public void testMessageWorkerStatusUpdatedWhenMessageWasQueued() throws Exception {
ArgumentCaptor<MessageWorkerStatus> messageWorkerStatusCaptor = ArgumentCaptor.forClass(MessageWorkerStatus.class);
messageRouter.route(joynrMessage.getImmutableMessage());
Thread.sleep(250);
verify(statusReceiver, atLeast(1)).updateMessageWorkerStatus(eq(0), messageWorkerStatusCaptor.capture());
// Workaround: At the beginning, the abstract message router queues two initial updates ("waiting for message") with the
// same timestamp. Remove this duplicate by inserting all values into a LinkedHashSet which preserves the order of insertion.
LinkedHashSet<MessageWorkerStatus> uniqueStatusUpdates = new LinkedHashSet<MessageWorkerStatus>(messageWorkerStatusCaptor.getAllValues());
MessageWorkerStatus[] statusUpdates = uniqueStatusUpdates.toArray(new MessageWorkerStatus[0]);
assertEquals(3, statusUpdates.length);
assertEquals(true, statusUpdates[0].isWaitingForMessage());
assertEquals(false, statusUpdates[1].isWaitingForMessage());
assertEquals(true, statusUpdates[2].isWaitingForMessage());
}
public void testScheduleMessage() throws InterruptedException {
final DelayQueue<DelayableImmutableMessage> messageQueue = spy(new DelayQueue<DelayableImmutableMessage>());
Module messageQueueSpyModule = Modules.override(testModule).with(new AbstractModule() {
@Override
protected void configure() {
bind(new TypeLiteral<DelayQueue<DelayableImmutableMessage>>() {
}).toInstance(messageQueue);
}
});
messageRouter = Guice.createInjector(messageQueueSpyModule).getInstance(MessageRouter.class);
Address address = new Address();
ImmutableMessage message = Mockito.mock(ImmutableMessage.class);
when(message.isTtlAbsolute()).thenReturn(true);
when(message.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(60000L).getValue());
when(message.getRecipient()).thenReturn("to");
when(routingTable.get("to")).thenReturn(address);
messageRouter.route(message);
ArgumentCaptor<DelayableImmutableMessage> passedDelaybleMessage = ArgumentCaptor.forClass(DelayableImmutableMessage.class);
verify(messageQueue, atLeast(1)).put(passedDelaybleMessage.capture());
assertEquals(message, passedDelaybleMessage.getAllValues().get(0).getMessage());
assertTrue(passedDelaybleMessage.getAllValues().get(0).getDelay(TimeUnit.MILLISECONDS) <= 0);
}
@Test
public void testShutdown() throws InterruptedException {
verify(shutdownNotifier).registerForShutdown((CcMessageRouter) messageRouter);
}
@Test(timeout = 3000)
public void testFailedTransmitDoesNotLeadToThreadStarvation() throws Exception {
final int MESSAGE_LOAD = 10;
ImmutableMessage failingMessage = mock(ImmutableMessage.class);
when(failingMessage.isTtlAbsolute()).thenReturn(true);
when(failingMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
when(failingMessage.getRecipient()).thenReturn("to");
when(routingTable.get("to")).thenReturn(channelAddress);
Set<Address> addressSet = new HashSet<>();
addressSet.add(channelAddress);
Mockito.doReturn(addressSet).when(addressManager).getAddresses(failingMessage);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertEquals(invocation.getArguments().length, 3);
FailureAction failureAction = (FailureAction) invocation.getArguments()[2];
failureAction.execute(new Exception("Some error"));
return null;
}
}).when(messagingStubMock).transmit(eq(failingMessage), any(SuccessAction.class), any(FailureAction.class));
for (int i = 0; i < MESSAGE_LOAD; i++) {
messageRouter.route(failingMessage);
}
Thread.sleep(2000);
verify(messagingStubMock, atLeast(MESSAGE_LOAD * 3)).transmit(eq(failingMessage),
any(SuccessAction.class),
any(FailureAction.class));
ImmutableMessage anotherMessage = mock(ImmutableMessage.class);
when(anotherMessage.isTtlAbsolute()).thenReturn(true);
when(anotherMessage.getTtlMs()).thenReturn(ExpiryDate.fromRelativeTtl(1000L).getValue());
when(anotherMessage.getRecipient()).thenReturn("to");
Mockito.doReturn(addressSet).when(addressManager).getAddresses(anotherMessage);
final Semaphore semaphore = new Semaphore(0);
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
assertEquals(invocation.getArguments().length, 3);
SuccessAction successAction = (SuccessAction) invocation.getArguments()[1];
successAction.execute();
semaphore.release();
return null;
}
}).when(messagingStubMock).transmit(eq(anotherMessage), any(SuccessAction.class), any(FailureAction.class));
messageRouter.route(anotherMessage);
assertTrue(semaphore.tryAcquire(100, TimeUnit.MILLISECONDS));
} |
<<<<<<<
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.eq;
=======
import static org.junit.Assert.fail;
>>>>>>>
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
<<<<<<<
Promise<DeferredVoid> assertMessageContextActive();
=======
Promise<Deferred<Object[]>> testMultiOutMethod();
>>>>>>>
Promise<DeferredVoid> assertMessageContextActive();
Promise<Deferred<Object[]>> testMultiOutMethod();
<<<<<<<
void assertMessageContextActive();
=======
public class MultiOutResult implements MultiReturnValuesContainer {
public Object[] getValues() {
return new Object[]{ "one", "two" };
}
}
MultiOutResult testMultiOutMethod();
>>>>>>>
void assertMessageContextActive();
public class MultiOutResult implements MultiReturnValuesContainer {
public Object[] getValues() {
return new Object[]{ "one", "two" };
}
}
MultiOutResult testMultiOutMethod();
<<<<<<<
@Override
public void assertMessageContextActive() {
assertTrue(JoynrJeeMessageContext.getInstance().isActive());
}
@Override
public void setSubscriptionPublisher(SubscriptionPublisher subscriptionPublisher) {
assertFalse(JoynrJeeMessageContext.getInstance().isActive());
}
=======
@Override
public MultiOutResult testMultiOutMethod() {
return new MultiOutResult();
}
>>>>>>>
@Override
public void assertMessageContextActive() {
assertTrue(JoynrJeeMessageContext.getInstance().isActive());
}
@Override
public void setSubscriptionPublisher(SubscriptionPublisher subscriptionPublisher) {
assertFalse(JoynrJeeMessageContext.getInstance().isActive());
}
public MultiOutResult testMultiOutMethod() {
return new MultiOutResult();
} |
<<<<<<<
CreatorCandidate.construct(config, ctor, creatorParams.get(ctor)));
=======
CreatorCandidate.construct(intr, ctor, creatorParams.get(ctor)),
ctxt.getConfig().getConstructorDetector());
>>>>>>>
CreatorCandidate.construct(config, ctor, creatorParams.get(ctor)),
ctxt.getConfig().getConstructorDetector());
<<<<<<<
=======
protected void _addDeserializerFactoryMethods
(DeserializationContext ctxt, BeanDescription beanDesc, VisibilityChecker<?> vchecker,
AnnotationIntrospector intr, CreatorCollector creators,
Map<AnnotatedWithParams,BeanPropertyDefinition[]> creatorParams)
throws JsonMappingException
{
List<CreatorCandidate> nonAnnotated = new LinkedList<>();
int explCount = 0;
// 21-Sep-2017, tatu: First let's handle explicitly annotated ones
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
JsonCreator.Mode creatorMode = intr.findCreatorAnnotation(ctxt.getConfig(), factory);
final int argCount = factory.getParameterCount();
if (creatorMode == null) {
// Only potentially accept 1-argument factory methods
if ((argCount == 1) && vchecker.isCreatorVisible(factory)) {
nonAnnotated.add(CreatorCandidate.construct(intr, factory, null));
}
continue;
}
if (creatorMode == Mode.DISABLED) {
continue;
}
// zero-arg method factory methods fine, as long as explicit
if (argCount == 0) {
creators.setDefaultCreator(factory);
continue;
}
switch (creatorMode) {
case DELEGATING:
_addExplicitDelegatingCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, null));
break;
case PROPERTIES:
_addExplicitPropertyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)));
break;
case DEFAULT:
default:
_addExplicitAnyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)),
// 13-Sep-2020, tatu: Factory methods do not follow config settings
// (as of Jackson 2.12)
ConstructorDetector.DEFAULT);
break;
}
++explCount;
}
// And only if and when those handled, consider potentially visible ones
if (explCount > 0) { // TODO: split method into two since we could have expl factories
return;
}
// And then implicitly found
for (CreatorCandidate candidate : nonAnnotated) {
final int argCount = candidate.paramCount();
AnnotatedWithParams factory = candidate.creator();
final BeanPropertyDefinition[] propDefs = creatorParams.get(factory);
// some single-arg factory methods (String, number) are auto-detected
if (argCount != 1) {
continue; // 2 and more args? Must be explicit, handled earlier
}
BeanPropertyDefinition argDef = candidate.propertyDef(0);
boolean useProps = _checkIfCreatorPropertyBased(intr, factory, argDef);
if (!useProps) { // not property based but delegating
/*boolean added=*/ _handleSingleArgumentCreator(creators,
factory, false, vchecker.isCreatorVisible(factory));
// 23-Sep-2016, tatu: [databind#1383]: Need to also sever link to avoid possible
// later problems with "unresolved" constructor property
if (argDef != null) {
((POJOPropertyBuilder) argDef).removeConstructors();
}
continue;
}
AnnotatedParameter nonAnnotatedParam = null;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int implicitNameCount = 0;
int explicitNameCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = factory.getParameter(i);
BeanPropertyDefinition propDef = (propDefs == null) ? null : propDefs[i];
JacksonInject.Value injectable = intr.findInjectableValue(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
if (injectable != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
_reportUnwrappedCreatorProperty(ctxt, beanDesc, param);
/*
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++implicitNameCount;
*/
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
/*
if (isCreator) {
if (name != null && !name.isEmpty()) {
++implicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
}
*/
/* 25-Sep-2014, tatu: Actually, we may end up "losing" naming due to higher-priority constructor
* (see TestCreators#testConstructorCreator() test). And just to avoid running into that problem,
* let's add one more work around
*/
/*
PropertyName name2 = _findExplicitParamName(param, intr);
if (name2 != null && !name2.isEmpty()) {
// Hmmh. Ok, fine. So what are we to do with it... ?
// For now... skip. May need to revisit this, should this become problematic
continue main_loop;
}
*/
if (nonAnnotatedParam == null) {
nonAnnotatedParam = param;
}
}
final int namedCount = explicitNameCount + implicitNameCount;
// Ok: if named or injectable, we have more work to do
if (explicitNameCount > 0 || injectCount > 0) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(factory, false, properties);
} else if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(factory, false, properties, 0);
} else { // otherwise, epic fail
ctxt.reportBadTypeDefinition(beanDesc,
"Argument #%d of factory method %s has no property name annotation; must have name when multiple-parameter constructor annotated as Creator",
nonAnnotatedParam.getIndex(), factory);
}
}
}
}
>>>>>>> |
<<<<<<<
private final ShutdownNotifier shutdownNotifier;
=======
private final StatelessAsyncCallbackDirectory statelessAsyncCallbackDirectory;
>>>>>>>
private final ShutdownNotifier shutdownNotifier;
private final StatelessAsyncCallbackDirectory statelessAsyncCallbackDirectory;
<<<<<<<
ShutdownNotifier shutdownNotifier,
=======
StatelessAsyncCallbackDirectory statelessAsyncCallbackDirectory,
>>>>>>>
ShutdownNotifier shutdownNotifier,
StatelessAsyncCallbackDirectory statelessAsyncCallbackDirectory,
<<<<<<<
this.shutdownNotifier = shutdownNotifier;
=======
this.statelessAsyncCallbackDirectory = statelessAsyncCallbackDirectory;
>>>>>>>
this.shutdownNotifier = shutdownNotifier;
this.statelessAsyncCallbackDirectory = statelessAsyncCallbackDirectory;
<<<<<<<
shutdownNotifier,
=======
statelessAsyncCallbackDirectory,
>>>>>>>
shutdownNotifier,
statelessAsyncCallbackDirectory, |
<<<<<<<
import joynr.types.DiscoveryEntryWithMetaInfo;
=======
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
>>>>>>>
import joynr.types.DiscoveryEntryWithMetaInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
<<<<<<<
verify(dispatcher, times(1)).sendSubscriptionRequest(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
any(SubscriptionRequest.class),
any(MessagingQos.class),
eq(true));
=======
verify(dispatcher).sendSubscriptionRequest(eq(fromParticipantId),
(Set<String>) argThat(contains(toParticipantId)),
any(SubscriptionRequest.class),
any(MessagingQos.class));
>>>>>>>
verify(dispatcher).sendSubscriptionRequest(eq(fromParticipantId),
(Set<DiscoveryEntryWithMetaInfo>) argThat(contains(toDiscoveryEntry)),
any(SubscriptionRequest.class),
any(MessagingQos.class)); |
<<<<<<<
// test that assertThat runs at least once
verify(messagingStubMock, Mockito.atLeast(10)).transmit(eq(immutableMessage),
any(SuccessAction.class),
any(FailureAction.class));
=======
// test that the mock is called multiple times which means that
// the assert inside is multiple times correct
verify(messagingStubMock, Mockito.atLeast(10)).transmit(eq(immutableMessage), any(FailureAction.class));
>>>>>>>
// test that the mock is called multiple times which means that
// the assert inside is multiple times correct
verify(messagingStubMock, Mockito.atLeast(10)).transmit(eq(immutableMessage),
any(SuccessAction.class),
any(FailureAction.class));
<<<<<<<
// make sure that there are retries
verify(messagingStubMock, Mockito.atLeast(5)).transmit(eq(immutableMessage),
any(SuccessAction.class),
any(FailureAction.class));
=======
// make sure that the stub is called at least few times
// but not too often which means that the average retry interval
// is much higher then initially set in sendMsgRetryIntervalMs
verify(messagingStubMock, Mockito.atLeast(5)).transmit(eq(immutableMessage), any(FailureAction.class));
>>>>>>>
// make sure that the stub is called at least few times
// but not too often which means that the average retry interval
// is much higher then initially set in sendMsgRetryIntervalMs
verify(messagingStubMock, Mockito.atLeast(5)).transmit(eq(immutableMessage),
any(SuccessAction.class),
any(FailureAction.class)); |
<<<<<<<
=======
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
}
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY, event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
/**
* Drops a sign item and removes a sign.
*
* @param block
*/
private void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(Material.SIGN, 1));
}
/**
* Remove water around a sponge.
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void clearSpongeWater(World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
}
/**
* Add water around a sponge.
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void addSpongeWater(World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
// The negative x edge
int cx = ox - wcfg.spongeRadius - 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx + 1, cy, cz);
}
}
}
// The positive x edge
cx = ox + wcfg.spongeRadius + 1;
for (int cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx - 1, cy, cz);
}
}
}
// The negative y edge
int cy = oy - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy + 1, cz);
}
}
}
// The positive y edge
cy = oy + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (int cz = oz - wcfg.spongeRadius - 1; cz <= oz + wcfg.spongeRadius + 1; cz++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy - 1, cz);
}
}
}
// The negative z edge
int cz = oz - wcfg.spongeRadius - 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz + 1);
}
}
}
// The positive z edge
cz = oz + wcfg.spongeRadius + 1;
for (cx = ox - wcfg.spongeRadius - 1; cx <= ox + wcfg.spongeRadius + 1; cx++) {
for (cy = oy - wcfg.spongeRadius - 1; cy <= oy + wcfg.spongeRadius + 1; cy++) {
if (isBlockWater(world, cx, cy, cz)) {
setBlockToWater(world, cx, cy, cz - 1);
}
}
}
}
/**
* Sets the given block to fluid water.
* Used by addSpongeWater()
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void setBlockToWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 0) {
block.setTypeId(8);
}
}
/**
* Checks if the given block is water
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private boolean isBlockWater(World world, int ox, int oy, int oz) {
Block block = world.getBlockAt(ox, oy, oz);
int id = block.getTypeId();
if (id == 8 || id == 9) {
return true;
} else {
return false;
}
}
>>>>>>>
@Override
public void onLeavesDecay(LeavesDecayEvent event) {
if (event.isCancelled()) {
return;
}
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.LEAF_DECAY, event.getBlock().getLocation())) {
event.setCancelled(true);
}
}
/**
* Drops a sign item and removes a sign.
*
* @param block
*/
private void dropSign(Block block) {
block.setTypeId(0);
block.getWorld().dropItemNaturally(block.getLocation(),
new ItemStack(Material.SIGN, 1));
}
/**
* Remove water around a sponge.
*
* @param world
* @param ox
* @param oy
* @param oz
*/
private void clearSpongeWater(World world, int ox, int oy, int oz) {
ConfigurationManager cfg = plugin.getGlobalConfiguration();
WorldConfiguration wcfg = cfg.get(world);
for (int cx = -wcfg.spongeRadius; cx <= wcfg.spongeRadius; cx++) {
for (int cy = -wcfg.spongeRadius; cy <= wcfg.spongeRadius; cy++) {
for (int cz = -wcfg.spongeRadius; cz <= wcfg.spongeRadius; cz++) {
if (isBlockWater(world, ox + cx, oy + cy, oz + cz)) {
world.getBlockAt(ox + cx, oy + cy, oz + cz).setTypeId(0);
}
}
}
}
} |
<<<<<<<
if (points.size() < 3) {
logger.warning(String.format("Invalid polygonal region '%s': region only has %d point(s). Ignoring.", id, points.size()));
continue;
}
=======
closeResource(poly2dVectorResultSet);
>>>>>>>
if (points.size() < 3) {
logger.warning(String.format("Invalid polygonal region '%s': region only has %d point(s). Ignoring.", id, points.size()));
continue;
}
closeResource(poly2dVectorResultSet);
<<<<<<<
PreparedStatement clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
clearPoly2dPointsForRegionStatement.execute();
PreparedStatement insertPoly2dPointStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
String lowerId = region.getId().toLowerCase();
for (BlockVector2D point : region.getPoints()) {
insertPoly2dPointStatement.setString(1, lowerId);
insertPoly2dPointStatement.setInt(2, point.getBlockZ());
insertPoly2dPointStatement.setInt(3, point.getBlockX());
insertPoly2dPointStatement.execute();
=======
PreparedStatement clearPoly2dPointsForRegionStatement = null;
PreparedStatement insertPoly2dPointStatement = null;
try {
clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
clearPoly2dPointsForRegionStatement.execute();
insertPoly2dPointStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
String lowerId = region.getId();
for (BlockVector2D point : region.getPoints()) {
insertPoly2dPointStatement.setString(1, lowerId);
insertPoly2dPointStatement.setInt(2, point.getBlockZ());
insertPoly2dPointStatement.setInt(3, point.getBlockX());
insertPoly2dPointStatement.execute();
}
} finally {
closeResource(clearPoly2dPointsForRegionStatement);
closeResource(insertPoly2dPointStatement);
>>>>>>>
PreparedStatement clearPoly2dPointsForRegionStatement = null;
PreparedStatement insertPoly2dPointStatement = null;
try {
clearPoly2dPointsForRegionStatement = this.conn.prepareStatement(
"DELETE FROM `region_poly2d_point` " +
"WHERE `region_id` = ? " +
"AND `world_id` = " + this.worldDbId
);
clearPoly2dPointsForRegionStatement.setString(1, region.getId().toLowerCase());
clearPoly2dPointsForRegionStatement.execute();
insertPoly2dPointStatement = this.conn.prepareStatement(
"INSERT INTO `region_poly2d_point` (" +
"`id`, " +
"`region_id`, " +
"`world_id`, " +
"`z`, " +
"`x` " +
") VALUES (null, ?, " + this.worldDbId + ", ?, ?)"
);
String lowerId = region.getId().toLowerCase();
for (BlockVector2D point : region.getPoints()) {
insertPoly2dPointStatement.setString(1, lowerId);
insertPoly2dPointStatement.setInt(2, point.getBlockZ());
insertPoly2dPointStatement.setInt(3, point.getBlockX());
insertPoly2dPointStatement.execute();
}
} finally {
closeResource(clearPoly2dPointsForRegionStatement);
closeResource(insertPoly2dPointStatement); |
<<<<<<<
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER,
NOTIFY_LEAVE, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE, SNOW_FALL,
=======
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_GREET,
NOTIFY_FAREWELL, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE, SNOW_FALL, LEAF_DECAY,
>>>>>>>
USE, PLACE_VEHICLE, GREET_MESSAGE, FAREWELL_MESSAGE, NOTIFY_ENTER,
NOTIFY_LEAVE, DENY_SPAWN, HEAL_DELAY, HEAL_AMOUNT, TELE_LOC,
TELE_PERM, SPAWN_LOC, SPAWN_PERM, BUYABLE, PRICE, SNOW_FALL, LEAF_DECAY, |
<<<<<<<
/**
* No matter how formatter tries to add linewrapping there is none in the formatted result.
*
* @see PPFormatter#assignmentExpressionConfiguration(FormattingConfig c)
*/
public void test_Format_AssignmentExpression() throws Exception {
String code = "$a = 1\n$b = 2\n";
XtextResource r = getResourceFromString(code);
String s = serializeFormatted(r.getContents().get(0));
assertEquals("serialization should produce specified result", code, s);
}
=======
>>>>>>>
/**
* No matter how formatter tries to add linewrapping there is none in the formatted result.
*
* @see PPFormatter#assignmentExpressionConfiguration(FormattingConfig c)
*/
public void test_Format_AssignmentExpression() throws Exception {
String code = "$a = 1\n$b = 2\n";
XtextResource r = getResourceFromString(code);
String s = serializeFormatted(r.getContents().get(0));
assertEquals("serialization should produce specified result", code, s);
} |
<<<<<<<
public ReadableMap headers;
=======
public float progressDivider;
>>>>>>>
public ReadableMap headers;
public float progressDivider; |
<<<<<<<
* Get a {@link FullJid} constructed from a {@link BareJid} and a {@link Resourcepart}.
*
* @param bareJid a entity bare JID.
* @param resource a resourcepart.
* @return a full JID.
*/
public static FullJid fullFrom(BareJid bareJid, Resourcepart resource) {
if (bareJid.isEntityBareJid()) {
EntityBareJid entityBareJid = (EntityBareJid) bareJid;
return new LocalDomainAndResourcepartJid(entityBareJid, resource);
} else {
DomainBareJid domainBareJid = (DomainBareJid) bareJid;
return new DomainAndResourcepartJid(domainBareJid, resource);
}
}
/**
=======
* Get a {@link FullJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
*
* @param cs the input {@link CharSequence}
* @return a JID or {@code null}
*/
public static FullJid fullFromOrNull(CharSequence cs) {
try {
return fullFrom(cs);
} catch (XmppStringprepException e) {
return null;
}
}
/**
>>>>>>>
* Get a {@link FullJid} constructed from a {@link BareJid} and a {@link Resourcepart}.
*
* @param bareJid a entity bare JID.
* @param resource a resourcepart.
* @return a full JID.
*/
public static FullJid fullFrom(BareJid bareJid, Resourcepart resource) {
if (bareJid.isEntityBareJid()) {
EntityBareJid entityBareJid = (EntityBareJid) bareJid;
return new LocalDomainAndResourcepartJid(entityBareJid, resource);
} else {
DomainBareJid domainBareJid = (DomainBareJid) bareJid;
return new DomainAndResourcepartJid(domainBareJid, resource);
}
}
/**
* Get a {@link FullJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
*
* @param cs the input {@link CharSequence}
* @return a JID or {@code null}
*/
public static FullJid fullFromOrNull(CharSequence cs) {
try {
return fullFrom(cs);
} catch (XmppStringprepException e) {
return null;
}
}
/**
<<<<<<<
=======
* Get a {@link DomainBareJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
*
* @param cs the input {@link CharSequence}
* @return a JID or {@code null}
*/
public static DomainBareJid domainBareFromOrNull(CharSequence cs) {
try {
return domainBareFrom(cs);
} catch (XmppStringprepException e) {
return null;
}
}
/**
* Deprecated.
*
* @param jid the JID.
* @return a DomainFullJid
* @throws XmppStringprepException if an error happens.
* @deprecated use {@link #domainFullFrom(String)} instead
*/
@Deprecated
public static DomainFullJid serverFullFrom(String jid) throws XmppStringprepException {
return donmainFullFrom(jid);
}
/**
* Get a domain full JID from the given String.
*
* @param jid the JID.
* @return a DomainFullJid.
* @throws XmppStringprepException if an error happens.
* @deprecated use {@link #domainFullFrom(String)} instead.
*/
@Deprecated
public static DomainFullJid donmainFullFrom(String jid) throws XmppStringprepException {
return domainFullFrom(jid);
}
/**
>>>>>>>
* Get a {@link DomainBareJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
*
* @param cs the input {@link CharSequence}
* @return a JID or {@code null}
*/
public static DomainBareJid domainBareFromOrNull(CharSequence cs) {
try {
return domainBareFrom(cs);
} catch (XmppStringprepException e) {
return null;
}
}
/** |
<<<<<<<
=======
import org.jclouds.vcloud.director.v1_5.domain.UsersList;
import org.jclouds.vcloud.director.v1_5.domain.Vdcs;
import org.jclouds.vcloud.director.v1_5.features.admin.GroupClient;
>>>>>>>
import org.jclouds.vcloud.director.v1_5.features.admin.AdminOrgClient;
<<<<<<<
assertEquals(client.getAdminOrgClient().getOrg(orgRef.getHref()), expected);
}
public static final AdminOrg adminOrg() {
return AdminOrg.builder()
.name("JClouds")
.id("urn:vcloud:org:6f312e42-cd2b-488d-a2bb-97519cd57ed0")
.type("application/vnd.vmware.admin.organization+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.link(Link.builder()
.rel("down")
.type("application/vnd.vmware.vcloud.tasksList+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/tasksList/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("down")
.type("application/vnd.vmware.vcloud.metadata+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/metadata"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.catalog+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/catalogs"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.user+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/users"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.group+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/groups"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.orgNetwork+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/networks"))
.build())
.link(Link.builder()
.rel("edit")
.type("application/vnd.vmware.admin.organization+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("remove")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("alternate")
.type("application/vnd.vmware.vcloud.org+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.description("")
.fullName("JClouds")
.isEnabled(true)
.settings(settings())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/672ebb67-d8ff-4201-9c1b-c1be869e526c"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/8c360b93-ed25-4c9a-8e24-d48cd9966d93"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/967d317c-4273-4a95-b8a4-bf63b78e9c69"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/ae75edd2-12de-414c-8e85-e6ea10442c08"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/e9eb1b29-0404-4c5e-8ef7-e584acc51da9"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("QunyingTestCatalog")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/7212e451-76e1-4631-b2de-ba1dfd8080e4"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("Public")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/9e08c2f6-077a-42ce-bece-d5332e2ebb5c"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("dantest")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/b542aff4-9f97-4f51-a126-4330fbf62f02"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("test")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/b7289d54-4ca4-497f-9a93-2d4afc97e3da"))
.build())
.vdc(Reference.builder()
.type("application/vnd.vmware.vcloud.vdc+xml")
.name("Cluster01-JClouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/vdc/d16d333b-e3c0-4176-845d-a5ee6392df07"))
.build())
.network(Reference.builder()
.type("application/vnd.vmware.admin.network+xml")
.name("ilsolation01-Jclouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/network/f3ba8256-6f48-4512-aad6-600e85b4dc38"))
.build())
.network(Reference.builder()
.type("application/vnd.vmware.admin.network+xml")
.name("internet01-Jclouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/network/55a677cf-ab3f-48ae-b880-fab90421980c"))
.build())
.build();
=======
assertEquals(client.getOrgClient().getOrg(orgRef.getHref()), expected);
>>>>>>>
assertEquals(client.getOrgClient().getOrg(orgRef.getHref()), expected);
}
public static final AdminOrg adminOrg() {
return AdminOrg.builder()
.name("JClouds")
.id("urn:vcloud:org:6f312e42-cd2b-488d-a2bb-97519cd57ed0")
.type("application/vnd.vmware.admin.organization+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.link(Link.builder()
.rel("down")
.type("application/vnd.vmware.vcloud.tasksList+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/tasksList/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("down")
.type("application/vnd.vmware.vcloud.metadata+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/metadata"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.catalog+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/catalogs"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.user+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/users"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.group+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/groups"))
.build())
.link(Link.builder()
.rel("add")
.type("application/vnd.vmware.admin.orgNetwork+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0/networks"))
.build())
.link(Link.builder()
.rel("edit")
.type("application/vnd.vmware.admin.organization+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("remove")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.link(Link.builder()
.rel("alternate")
.type("application/vnd.vmware.vcloud.org+xml")
.href(URI.create("https://vcloudbeta.bluelock.com/api/org/6f312e42-cd2b-488d-a2bb-97519cd57ed0"))
.build())
.description("")
.fullName("JClouds")
.isEnabled(true)
.settings(settings())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/672ebb67-d8ff-4201-9c1b-c1be869e526c"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/8c360b93-ed25-4c9a-8e24-d48cd9966d93"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/967d317c-4273-4a95-b8a4-bf63b78e9c69"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/ae75edd2-12de-414c-8e85-e6ea10442c08"))
.build())
.user(Reference.builder()
.type("application/vnd.vmware.admin.user+xml")
.name("[email protected]")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/user/e9eb1b29-0404-4c5e-8ef7-e584acc51da9"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("QunyingTestCatalog")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/7212e451-76e1-4631-b2de-ba1dfd8080e4"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("Public")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/9e08c2f6-077a-42ce-bece-d5332e2ebb5c"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("dantest")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/b542aff4-9f97-4f51-a126-4330fbf62f02"))
.build())
.catalog(Reference.builder()
.type("application/vnd.vmware.admin.catalog+xml")
.name("test")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/catalog/b7289d54-4ca4-497f-9a93-2d4afc97e3da"))
.build())
.vdc(Reference.builder()
.type("application/vnd.vmware.vcloud.vdc+xml")
.name("Cluster01-JClouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/vdc/d16d333b-e3c0-4176-845d-a5ee6392df07"))
.build())
.network(Reference.builder()
.type("application/vnd.vmware.admin.network+xml")
.name("ilsolation01-Jclouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/network/f3ba8256-6f48-4512-aad6-600e85b4dc38"))
.build())
.network(Reference.builder()
.type("application/vnd.vmware.admin.network+xml")
.name("internet01-Jclouds")
.href(URI.create("https://vcloudbeta.bluelock.com/api/admin/network/55a677cf-ab3f-48ae-b880-fab90421980c"))
.build())
.build(); |
<<<<<<<
import java.io.File;
import java.io.IOException;
=======
>>>>>>>
import java.io.IOException; |
<<<<<<<
=======
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
>>>>>>>
import java.util.*;
import java.util.concurrent.atomic.AtomicReference; |
<<<<<<<
final FilePath cache = Cache.fromURL(source, credentials).repositoryCache(inst, node, launcher, listener, true);
=======
FilePath cache = Cache.fromURL(source, credentials, inst.getMasterCacheRoot()).repositoryCache(inst, node, launcher, listener, true);
>>>>>>>
final FilePath cache = Cache.fromURL(source, credentials, inst.getMasterCacheRoot()).repositoryCache(inst, node, launcher, listener, true); |
<<<<<<<
public void onClick() {
openHTMLPage(config.webHomePage);
=======
public void onClick(boolean b) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(config.webHomePage)));
>>>>>>>
public void onClick(boolean b) {
openHTMLPage(config.webHomePage); |
<<<<<<<
import org.apache.commons.lang.StringUtils;
=======
import com.google.code.morphia.query.CriteriaContainer;
import com.google.code.morphia.query.CriteriaContainerImpl;
>>>>>>>
import org.apache.commons.lang.StringUtils;
import com.google.code.morphia.query.CriteriaContainer;
import com.google.code.morphia.query.CriteriaContainerImpl;
<<<<<<<
if (!StringUtil.isEmpty(seeds))
mongo_ = connect_(seeds, options);
=======
if (!StringUtil.isEmpty(url)) {
MongoURI mongoURI = new MongoURI(url);
mongo_ = connect_(mongoURI);
}
else if (!StringUtil.isEmpty(seeds)) {
mongo_ = connect_(seeds);
}
>>>>>>>
if (!StringUtil.isEmpty(url)) {
MongoURI mongoURI = new MongoURI(url);
mongo_ = connect_(mongoURI);
}
else if (!StringUtil.isEmpty(seeds)) {
mongo_ = connect_(seeds);
}
<<<<<<<
private static MongoOptions readMongoOptions(Properties c) {
MongoOptions options = new MongoOptions();
for (Field field : options.getClass().getFields()) {
String property = c.getProperty("mongo." + field.getName());
if (StringUtils.isEmpty(property))
continue;
Class<?> fieldType = field.getType();
Object value = null;
try {
if (fieldType == int.class)
value = Integer.parseInt(property);
else if (fieldType == long.class)
value = Long.parseLong(property);
else if (fieldType == String.class)
value = property;
else if (fieldType == Double.class)
value = Double.parseDouble(property);
else if (fieldType == boolean.class)
value = Boolean.parseBoolean(property);
field.set(options, value);
} catch (Exception e) {
error(e, "error setting mongo option " + field.getName());
}
}
return options;
}
=======
>>>>>>>
private static MongoOptions readMongoOptions(Properties c) {
MongoOptions options = new MongoOptions();
for (Field field : options.getClass().getFields()) {
String property = c.getProperty("mongo." + field.getName());
if (StringUtils.isEmpty(property))
continue;
Class<?> fieldType = field.getType();
Object value = null;
try {
if (fieldType == int.class)
value = Integer.parseInt(property);
else if (fieldType == long.class)
value = Long.parseLong(property);
else if (fieldType == String.class)
value = property;
else if (fieldType == Double.class)
value = Double.parseDouble(property);
else if (fieldType == boolean.class)
value = Boolean.parseBoolean(property);
field.set(options, value);
} catch (Exception e) {
error(e, "error setting mongo option " + field.getName());
}
}
return options;
} |
<<<<<<<
ApiDefinitionExecResult selectMaxResultByResourceIdAndType(String resourceId, String type);
@Select({
"SELECT count(id) AS countNumber FROM api_definition_exec_result ",
"WHERE resource_id IN ( ",
"SELECT testCase.id FROM api_test_case testCase ",
"WHERE testCase.project_id = #{projectId}) ",
"and start_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp} "
})
=======
>>>>>>>
ApiDefinitionExecResult selectMaxResultByResourceIdAndType(String resourceId, String type);
@Select({
"SELECT count(id) AS countNumber FROM api_definition_exec_result ",
"WHERE resource_id IN ( ",
"SELECT testCase.id FROM api_test_case testCase ",
"WHERE testCase.project_id = #{projectId}) ",
"and start_time BETWEEN #{firstDayTimestamp} AND #{lastDayTimestamp} "
}) |
<<<<<<<
private HistoricalDataUpgradeService historicalDataUpgradeService;
=======
private APIReportService apiReportService;
@Resource
private PerformanceTestService performanceTestService;
@Resource
private CheckPermissionService checkPermissionService;
>>>>>>>
private APIReportService apiReportService;
@Resource
private PerformanceTestService performanceTestService;
@Resource
private CheckPermissionService checkPermissionService;
@Resource
private HistoricalDataUpgradeService historicalDataUpgradeService;
<<<<<<<
// long api_executedInThisWeekCountNumber = apiReportService.countByProjectIdAndCreateInThisWeek(projectId);
long executedInThisWeekCountNumber = apiScenarioReportService.countByProjectIdAndCreateAndByScheduleInThisWeek(projectId);
// long executedInThisWeekCountNumber = api_executedInThisWeekCountNumber+scene_executedInThisWeekCountNumber;
=======
long api_executedInThisWeekCountNumber = apiReportService.countByProjectIdAndCreateInThisWeek(projectId);
long scene_executedInThisWeekCountNumber = apiScenarioReportService.countByProjectIdAndCreateAndByScheduleInThisWeek(projectId);
long executedInThisWeekCountNumber = api_executedInThisWeekCountNumber + scene_executedInThisWeekCountNumber;
>>>>>>>
// long api_executedInThisWeekCountNumber = apiReportService.countByProjectIdAndCreateInThisWeek(projectId);
long executedInThisWeekCountNumber = apiScenarioReportService.countByProjectIdAndCreateAndByScheduleInThisWeek(projectId);
// long executedInThisWeekCountNumber = api_executedInThisWeekCountNumber+scene_executedInThisWeekCountNumber;
<<<<<<<
dataDTO.setTestPlanDTOList(selectData.getTestPlanDTOList());
}else {
=======
} else {
>>>>>>>
dataDTO.setTestPlanDTOList(selectData.getTestPlanDTOList());
}else {
<<<<<<<
@PostMapping(value = "/historicalDataUpgrade")
public String historicalDataUpgrade(@RequestBody SaveHistoricalDataUpgrade request) {
return historicalDataUpgradeService.upgrade(request);
}
=======
@PostMapping(value = "/genPerformanceTestXml", consumes = {"multipart/form-data"})
public JmxInfoDTO genPerformanceTest(@RequestPart("request") RunDefinitionRequest runRequest, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
HashTree hashTree = runRequest.getTestElement().generateHashTree();
String jmxString = runRequest.getTestElement().getJmx(hashTree);
JmxInfoDTO dto = new JmxInfoDTO();
dto.setName(runRequest.getName()+".JMX");
dto.setXml(jmxString);
return dto;
}
>>>>>>>
@PostMapping(value = "/historicalDataUpgrade")
public String historicalDataUpgrade(@RequestBody SaveHistoricalDataUpgrade request) {
return historicalDataUpgradeService.upgrade(request);
}
@PostMapping(value = "/genPerformanceTestXml", consumes = {"multipart/form-data"})
public JmxInfoDTO genPerformanceTest(@RequestPart("request") RunDefinitionRequest runRequest, @RequestPart(value = "files") List<MultipartFile> bodyFiles) {
HashTree hashTree = runRequest.getTestElement().generateHashTree();
String jmxString = runRequest.getTestElement().getJmx(hashTree);
JmxInfoDTO dto = new JmxInfoDTO();
dto.setName(runRequest.getName()+".JMX");
dto.setXml(jmxString);
return dto;
} |
<<<<<<<
private String runMode;
private List<String> planCaseIds;
=======
private String reportUserID;
>>>>>>>
private String runMode;
private List<String> planCaseIds;
private String reportUserID; |
<<<<<<<
@Resource
private ScheduleService scheduleService;
=======
@Resource
private TestCaseMapper testCaseMapper;
>>>>>>>
@Resource
private ScheduleService scheduleService;
@Resource
private TestCaseMapper testCaseMapper; |
<<<<<<<
=======
@PostMapping(value = "/genPerformanceTestJmx")
public JmxInfoDTO genPerformanceTestJmx(@RequestBody RunScenarioRequest runRequest) {
runRequest.setExecuteType(ExecuteType.Completed.name());
return apiAutomationService.genPerformanceTestJmx(runRequest);
}
>>>>>>>
@PostMapping(value = "/genPerformanceTestJmx")
public JmxInfoDTO genPerformanceTestJmx(@RequestBody RunScenarioRequest runRequest) {
runRequest.setExecuteType(ExecuteType.Completed.name());
return apiAutomationService.genPerformanceTestJmx(runRequest);
} |
<<<<<<<
public void relevanceByApi(ApiCaseRelevanceRequest request) {
if (CollectionUtils.isEmpty(request.getSelectIds())) {
return;
}
ApiTestCaseExample example = new ApiTestCaseExample();
example.createCriteria().andApiDefinitionIdIn(request.getSelectIds());
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevance(apiTestCases, request);
}
public void relevanceByCase(ApiCaseRelevanceRequest request) {
List<String> ids = request.getSelectIds();
if (CollectionUtils.isEmpty(ids)) {
return;
}
ApiTestCaseExample example = new ApiTestCaseExample();
example.createCriteria().andIdIn(ids);
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevance(apiTestCases, request);
}
private void relevance(List<ApiTestCase> apiTestCases, ApiCaseRelevanceRequest request) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ExtTestPlanApiCaseMapper batchMapper = sqlSession.getMapper(ExtTestPlanApiCaseMapper.class);
apiTestCases.forEach(apiTestCase -> {
TestPlanApiCase testPlanApiCase = new TestPlanApiCase();
testPlanApiCase.setId(UUID.randomUUID().toString());
testPlanApiCase.setApiCaseId(apiTestCase.getId());
testPlanApiCase.setTestPlanId(request.getPlanId());
testPlanApiCase.setEnvironmentId(request.getEnvironmentId());
testPlanApiCase.setCreateTime(System.currentTimeMillis());
testPlanApiCase.setUpdateTime(System.currentTimeMillis());
batchMapper.insertIfNotExists(testPlanApiCase);
});
sqlSession.flushStatements();
}
public List<String> selectIdsNotExistsInPlan(String projectId, String planId) {
return extApiTestCaseMapper.selectIdsNotExistsInPlan(projectId, planId);
}
=======
public List<ApiDataCountResult> countProtocolByProjectID(String projectId) {
return extApiTestCaseMapper.countProtocolByProjectID(projectId);
}
public long countByProjectIDAndCreateInThisWeek(String projectId) {
Map<String, Date> startAndEndDateInWeek = DateUtils.getWeedFirstTimeAndLastTime(new Date());
Date firstTime = startAndEndDateInWeek.get("firstTime");
Date lastTime = startAndEndDateInWeek.get("lastTime");
if(firstTime==null || lastTime == null){
return 0;
}else {
return extApiTestCaseMapper.countByProjectIDAndCreateInThisWeek(projectId,firstTime.getTime(),lastTime.getTime());
}
}
>>>>>>>
public void relevanceByApi(ApiCaseRelevanceRequest request) {
if (CollectionUtils.isEmpty(request.getSelectIds())) {
return;
}
ApiTestCaseExample example = new ApiTestCaseExample();
example.createCriteria().andApiDefinitionIdIn(request.getSelectIds());
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevance(apiTestCases, request);
}
public void relevanceByCase(ApiCaseRelevanceRequest request) {
List<String> ids = request.getSelectIds();
if (CollectionUtils.isEmpty(ids)) {
return;
}
ApiTestCaseExample example = new ApiTestCaseExample();
example.createCriteria().andIdIn(ids);
List<ApiTestCase> apiTestCases = apiTestCaseMapper.selectByExample(example);
relevance(apiTestCases, request);
}
private void relevance(List<ApiTestCase> apiTestCases, ApiCaseRelevanceRequest request) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
ExtTestPlanApiCaseMapper batchMapper = sqlSession.getMapper(ExtTestPlanApiCaseMapper.class);
apiTestCases.forEach(apiTestCase -> {
TestPlanApiCase testPlanApiCase = new TestPlanApiCase();
testPlanApiCase.setId(UUID.randomUUID().toString());
testPlanApiCase.setApiCaseId(apiTestCase.getId());
testPlanApiCase.setTestPlanId(request.getPlanId());
testPlanApiCase.setEnvironmentId(request.getEnvironmentId());
testPlanApiCase.setCreateTime(System.currentTimeMillis());
testPlanApiCase.setUpdateTime(System.currentTimeMillis());
batchMapper.insertIfNotExists(testPlanApiCase);
});
sqlSession.flushStatements();
}
public List<String> selectIdsNotExistsInPlan(String projectId, String planId) {
return extApiTestCaseMapper.selectIdsNotExistsInPlan(projectId, planId);
}
public List<ApiDataCountResult> countProtocolByProjectID(String projectId) {
return extApiTestCaseMapper.countProtocolByProjectID(projectId);
}
public long countByProjectIDAndCreateInThisWeek(String projectId) {
Map<String, Date> startAndEndDateInWeek = DateUtils.getWeedFirstTimeAndLastTime(new Date());
Date firstTime = startAndEndDateInWeek.get("firstTime");
Date lastTime = startAndEndDateInWeek.get("lastTime");
if(firstTime==null || lastTime == null){
return 0;
}else {
return extApiTestCaseMapper.countByProjectIDAndCreateInThisWeek(projectId,firstTime.getTime(),lastTime.getTime());
}
} |
<<<<<<<
import java.util.List;
import java.util.Objects;
import java.util.UUID;
=======
import java.util.*;
>>>>>>>
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.*;
<<<<<<<
public void deleteByResourceId(String resourceId) {
ApiDefinitionExecResultExample example = new ApiDefinitionExecResultExample();
example.createCriteria().andResourceIdEqualTo(resourceId);
apiDefinitionExecResultMapper.deleteByExample(example);
}
public void deleteByResourceIds(List<String> ids) {
ApiDefinitionExecResultExample example = new ApiDefinitionExecResultExample();
example.createCriteria().andResourceIdIn(ids);
apiDefinitionExecResultMapper.deleteByExample(example);
}
=======
public long countByTestCaseIDInProjectAndExecutedInThisWeek(String projectId) {
Map<String, Date> startAndEndDateInWeek = DateUtils.getWeedFirstTimeAndLastTime(new Date());
Date firstTime = startAndEndDateInWeek.get("firstTime");
Date lastTime = startAndEndDateInWeek.get("lastTime");
if(firstTime==null || lastTime == null){
return 0;
}else {
return extApiDefinitionExecResultMapper.countByProjectIDAndCreateInThisWeek(projectId,firstTime.getTime(),lastTime.getTime());
}
}
public long countByTestCaseIDInProject(String projectId) {
return extApiDefinitionExecResultMapper.countByTestCaseIDInProject(projectId);
}
public List<ExecutedCaseInfoResult> findFaliureCaseInfoByProjectIDAndLimitNumberInSevenDays(String projectId, int limitNumber) {
//获取7天之前的日期
Date startDay = DateUtils.dateSum(new Date(),-6);
//将日期转化为 00:00:00 的时间戳
Date startTime = null;
try{
startTime = DateUtils.getDayStartTime(startDay);
}catch (Exception e){
}
if(startTime==null){
return new ArrayList<>(0);
}else {
return extApiDefinitionExecResultMapper.findFaliureCaseInfoByProjectIDAndExecuteTimeAndLimitNumber(projectId,startTime.getTime(),limitNumber);
}
}
>>>>>>>
public void deleteByResourceId(String resourceId) {
ApiDefinitionExecResultExample example = new ApiDefinitionExecResultExample();
example.createCriteria().andResourceIdEqualTo(resourceId);
apiDefinitionExecResultMapper.deleteByExample(example);
}
public void deleteByResourceIds(List<String> ids) {
ApiDefinitionExecResultExample example = new ApiDefinitionExecResultExample();
example.createCriteria().andResourceIdIn(ids);
apiDefinitionExecResultMapper.deleteByExample(example);
}
public long countByTestCaseIDInProjectAndExecutedInThisWeek(String projectId) {
Map<String, Date> startAndEndDateInWeek = DateUtils.getWeedFirstTimeAndLastTime(new Date());
Date firstTime = startAndEndDateInWeek.get("firstTime");
Date lastTime = startAndEndDateInWeek.get("lastTime");
if(firstTime==null || lastTime == null){
return 0;
}else {
return extApiDefinitionExecResultMapper.countByProjectIDAndCreateInThisWeek(projectId,firstTime.getTime(),lastTime.getTime());
}
}
public long countByTestCaseIDInProject(String projectId) {
return extApiDefinitionExecResultMapper.countByTestCaseIDInProject(projectId);
}
public List<ExecutedCaseInfoResult> findFaliureCaseInfoByProjectIDAndLimitNumberInSevenDays(String projectId, int limitNumber) {
//获取7天之前的日期
Date startDay = DateUtils.dateSum(new Date(),-6);
//将日期转化为 00:00:00 的时间戳
Date startTime = null;
try{
startTime = DateUtils.getDayStartTime(startDay);
}catch (Exception e){
}
if(startTime==null){
return new ArrayList<>(0);
}else {
return extApiDefinitionExecResultMapper.findFaliureCaseInfoByProjectIDAndExecuteTimeAndLimitNumber(projectId,startTime.getTime(),limitNumber);
}
} |
<<<<<<<
import io.metersphere.api.dto.scenario.request.HttpRequest;
=======
import io.metersphere.api.dto.scenario.Request;
import io.metersphere.api.dto.scenario.Scenario;
>>>>>>>
import io.metersphere.api.dto.scenario.Scenario;
import io.metersphere.api.dto.scenario.request.HttpRequest;
<<<<<<<
protected void addContentType(HttpRequest request, String contentType) {
=======
protected void setScenarioByRequest(Scenario scenario, ApiTestImportRequest request) {
if (request.getUseEnvironment()) {
scenario.setEnvironmentId(request.getEnvironmentId());
}
}
protected void addContentType(Request request, String contentType) {
>>>>>>>
protected void setScenarioByRequest(Scenario scenario, ApiTestImportRequest request) {
if (request.getUseEnvironment()) {
scenario.setEnvironmentId(request.getEnvironmentId());
}
}
protected void addContentType(HttpRequest request, String contentType) { |
<<<<<<<
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.npc.dNPC;
=======
>>>>>>>
import net.aufdemrand.denizen.flags.FlagManager;
<<<<<<<
=======
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.flags.FlagManager.Flag;
>>>>>>>
<<<<<<<
import org.bukkit.entity.Player;
=======
import net.aufdemrand.denizen.utilities.arguments.aH;
import net.aufdemrand.denizen.utilities.debugging.dB;
>>>>>>>
import net.aufdemrand.denizen.utilities.arguments.aH;
import net.aufdemrand.denizen.utilities.debugging.dB; |
<<<<<<<
package com.werb.pickphotosample;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.bumptech.glide.Glide;
import com.werb.pickphotoview.R;
import com.werb.pickphotoview.util.PickConfig;
import com.werb.pickphotoview.util.PickUtils;
import java.io.File;
import java.util.ArrayList;
/**
* Created by wanbo on 2016/12/31.
*/
public class SampleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<String> imagePaths;
private Context context;
public SampleAdapter(Context c, ArrayList<String> imagePaths) {
this.context = c;
this.imagePaths = imagePaths;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new GridImageViewHolder(LayoutInflater.from(context).inflate(R.layout.pick_item_grid_layout, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(imagePaths != null) {
String path = imagePaths.get(position);
GridImageViewHolder gridImageViewHolder = (GridImageViewHolder) holder;
gridImageViewHolder.bindItem(path);
}
}
@Override
public int getItemCount() {
if(imagePaths != null) {
return imagePaths.size();
}else {
return 0;
}
}
public void updateData(ArrayList<String> paths) {
imagePaths = paths;
notifyDataSetChanged();
}
// ViewHolder
private class GridImageViewHolder extends RecyclerView.ViewHolder {
private ImageView gridImage, selectImage;
private int scaleSize;
GridImageViewHolder(View itemView) {
super(itemView);
gridImage = (ImageView) itemView.findViewById(R.id.iv_grid);
selectImage = (ImageView) itemView.findViewById(R.id.iv_select);
selectImage.setVisibility(View.GONE);
int screenWidth = PickUtils.getInstance(context).getWidthPixels();
int space = PickUtils.getInstance(context).dp2px(PickConfig.ITEM_SPACE);
scaleSize = (screenWidth - (4 + 1) * space) / 4;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) gridImage.getLayoutParams();
params.width = scaleSize;
params.height = scaleSize;
}
void bindItem(final String path) {
gridImage.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
}
=======
package com.werb.pickphotosample;
import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.werb.pickphotoview.util.PickConfig;
import com.werb.pickphotoview.util.PickUtils;
import java.util.ArrayList;
/**
* Created by wanbo on 2016/12/31.
*/
public class SampleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<String> imagePaths;
private Context context;
public SampleAdapter(Context c, ArrayList<String> imagePaths) {
this.context = c;
this.imagePaths = imagePaths;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new GridImageViewHolder(LayoutInflater.from(context).inflate(R.layout.item_image, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(imagePaths != null) {
String path = imagePaths.get(position);
GridImageViewHolder gridImageViewHolder = (GridImageViewHolder) holder;
gridImageViewHolder.bindItem(path);
}
}
@Override
public int getItemCount() {
if(imagePaths != null) {
return imagePaths.size();
}else {
return 0;
}
}
public void updateData(ArrayList<String> paths) {
imagePaths = paths;
notifyDataSetChanged();
}
// ViewHolder
private class GridImageViewHolder extends RecyclerView.ViewHolder {
private ImageView gridImage;
private int scaleSize;
GridImageViewHolder(View itemView) {
super(itemView);
gridImage = itemView.findViewById(R.id.image);
int screenWidth = PickUtils.getInstance(context).getWidthPixels();
int space = PickUtils.getInstance(context).dp2px(PickConfig.INSTANCE.getITEM_SPACE());
scaleSize = (screenWidth - (4 + 1) * space) / 4;
ViewGroup.LayoutParams params = gridImage.getLayoutParams();
params.width = scaleSize;
params.height = scaleSize;
}
void bindItem(final String path) {
Glide.with(context).load(Uri.parse("file://" + path)).into(gridImage);
}
}
}
>>>>>>>
package com.werb.pickphotosample;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.werb.pickphotoview.util.PickConfig;
import com.werb.pickphotoview.util.PickUtils;
import java.util.ArrayList;
/**
* Created by wanbo on 2016/12/31.
*/
public class SampleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<String> imagePaths;
private Context context;
SampleAdapter(Context c, ArrayList<String> imagePaths) {
this.context = c;
this.imagePaths = imagePaths;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new GridImageViewHolder(LayoutInflater.from(context).inflate(R.layout.item_image, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(imagePaths != null) {
String path = imagePaths.get(position);
GridImageViewHolder gridImageViewHolder = (GridImageViewHolder) holder;
gridImageViewHolder.bindItem(path);
}
}
@Override
public int getItemCount() {
if(imagePaths != null) {
return imagePaths.size();
}else {
return 0;
}
}
public void updateData(ArrayList<String> paths) {
imagePaths = paths;
notifyDataSetChanged();
}
// ViewHolder
private class GridImageViewHolder extends RecyclerView.ViewHolder {
private ImageView gridImage;
private int scaleSize;
GridImageViewHolder(View itemView) {
super(itemView);
gridImage = itemView.findViewById(R.id.image);
int screenWidth = PickUtils.getInstance(context).getWidthPixels();
int space = PickUtils.getInstance(context).dp2px(PickConfig.INSTANCE.getITEM_SPACE());
scaleSize = (screenWidth - (4 + 1) * space) / 4;
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) gridImage.getLayoutParams();
params.width = scaleSize;
params.height = scaleSize;
}
void bindItem(final String path) {
gridImage.setImageBitmap(BitmapFactory.decodeFile(path));
}
}
} |
<<<<<<<
assertTrue(MAPPER.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
assertFalse(MAPPER.isEnabled(JsonParser.Feature.ALLOW_COMMENTS));
=======
public void testParserFeatures()
{
// and also for mapper
ObjectMapper mapper = new ObjectMapper();
assertTrue(mapper.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
assertFalse(mapper.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
mapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE,
JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
assertFalse(mapper.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
>>>>>>>
assertTrue(MAPPER.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE));
<<<<<<<
=======
// [databind#28]: ObjectMapper.copy()
public void testCopy() throws Exception
{
ObjectMapper m = new ObjectMapper();
assertTrue(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
InjectableValues inj = new InjectableValues.Std();
m.setInjectableValues(inj);
assertFalse(m.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
m.enable(JsonParser.Feature.IGNORE_UNDEFINED);
assertTrue(m.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
// // First: verify that handling of features is decoupled:
ObjectMapper m2 = m.copy();
assertFalse(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
m2.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
assertTrue(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertSame(inj, m2.getInjectableValues());
// but should NOT change the original
assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
// nor vice versa:
assertFalse(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
m.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
assertTrue(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
// // Also, underlying JsonFactory instances should be distinct
assertNotSame(m.getFactory(), m2.getFactory());
// [databind#122]: Need to ensure mix-ins are not shared
assertEquals(0, m.getSerializationConfig().mixInCount());
assertEquals(0, m2.getSerializationConfig().mixInCount());
assertEquals(0, m.getDeserializationConfig().mixInCount());
assertEquals(0, m2.getDeserializationConfig().mixInCount());
m.addMixIn(String.class, Integer.class);
assertEquals(1, m.getSerializationConfig().mixInCount());
assertEquals(0, m2.getSerializationConfig().mixInCount());
assertEquals(1, m.getDeserializationConfig().mixInCount());
assertEquals(0, m2.getDeserializationConfig().mixInCount());
// [databind#913]: Ensure JsonFactory Features copied
assertTrue(m2.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
}
>>>>>>>
<<<<<<<
=======
// For [databind#703], [databind#978]
public void testNonSerializabilityOfObject()
{
ObjectMapper m = new ObjectMapper();
assertFalse(m.canSerialize(Object.class));
// but this used to pass, incorrectly, second time around
assertFalse(m.canSerialize(Object.class));
// [databind#978]: Different answer if empty Beans ARE allowed
m = new ObjectMapper();
m.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
assertTrue(m.canSerialize(Object.class));
assertTrue(MAPPER.writer().without(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.canSerialize(Object.class));
assertFalse(MAPPER.writer().with(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.canSerialize(Object.class));
}
// for [databind#756]
public void testEmptyBeanSerializability()
{
// with default settings, error
assertFalse(MAPPER.writer().with(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.canSerialize(EmptyBean.class));
// but with changes
assertTrue(MAPPER.writer().without(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.canSerialize(EmptyBean.class));
}
// for [databind#898]
public void testSerializerProviderAccess() throws Exception
{
// ensure we have "fresh" instance, just in case
ObjectMapper mapper = new ObjectMapper();
JsonSerializer<?> ser = mapper.getSerializerProviderInstance()
.findValueSerializer(Bean.class);
assertNotNull(ser);
assertEquals(Bean.class, ser.handledType());
}
// for [databind#1074]
public void testCopyOfParserFeatures() throws Exception
{
// ensure we have "fresh" instance to start with
ObjectMapper mapper = new ObjectMapper();
assertFalse(mapper.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
assertTrue(mapper.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
ObjectMapper copy = mapper.copy();
assertTrue(copy.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
// also verify there's no back-linkage
copy.configure(JsonParser.Feature.IGNORE_UNDEFINED, false);
assertFalse(copy.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
assertTrue(mapper.isEnabled(JsonParser.Feature.IGNORE_UNDEFINED));
}
>>>>>>> |
<<<<<<<
import com.graphaware.nlp.ml.similarity.CosineSimilarity;
import com.graphaware.nlp.ml.similarity.Similarity;
import java.util.Arrays;
=======
>>>>>>>
import com.graphaware.nlp.ml.similarity.CosineSimilarity;
import com.graphaware.nlp.ml.similarity.Similarity;
import java.util.Arrays;
<<<<<<<
public float getFeatureCosine(long firstNode, long secondNode) {
float sim = 0;
sim = similarityFunction.getSimilarity(getTFMap(firstNode), getTFMap(secondNode));
LOG.debug("Sim (" + firstNode + ", " + secondNode + ") = " + sim);
return sim;
=======
public float getFeatureCosine(long firstNode, long secondNode, String query) {
return similarityFunction.getSimilarity(getTFMap(firstNode, query), getTFMap(secondNode, query));
>>>>>>>
public float getFeatureCosine(long firstNode, long secondNode, String query) {
return similarityFunction.getSimilarity(getTFMap(firstNode, query), getTFMap(secondNode, query));
<<<<<<<
if (cn5_depth==0)
tfMap = createFeatureMap(node);
else
tfMap = createFeatureMapWithCN5(node);
=======
tfMap = createFeatureMap(node, query);
>>>>>>>
if (cn5_depth==0)
tfMap = createFeatureMap(node);
else
tfMap = createFeatureMapWithCN5(node);
<<<<<<<
//if (secondNode != firstNodeId) {
if (secondNode>firstNode) { // this way, only one relationship between the same AnnotatedTexts will be stored (in direction: lower_id -> higher_id)
float similarity = getFeatureCosine(firstNodeId, secondNode);
=======
if (secondNode != firstNodeId) {
float similarity = getFeatureCosine(firstNodeId, secondNode, query);
>>>>>>>
//if (secondNode != firstNodeId) {
if (secondNode>firstNode) { // this way, only one relationship between the same AnnotatedTexts will be stored (in direction: lower_id -> higher_id)
float similarity = getFeatureCosine(firstNodeId, secondNode);
<<<<<<<
if (cn5_depth==0)
kNN.add(new SimilarityItem(firstNodeId, secondNode, similarity, Relationships.SIMILARITY_COSINE.name()));
else
kNN.add(new SimilarityItem(firstNodeId, secondNode, similarity, Relationships.SIMILARITY_COSINE_CN5.name()));
=======
kNN.add(new SimilarityItem(firstNodeId, secondNode, similarity, similarityType));
>>>>>>>
if (cn5_depth==0)
kNN.add(new SimilarityItem(firstNodeId, secondNode, similarity, Relationships.SIMILARITY_COSINE.name()));
else
kNN.add(new SimilarityItem(firstNodeId, secondNode, similarity, Relationships.SIMILARITY_COSINE_CN5.name())); |
<<<<<<<
public void testDoubleAsArray() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.build();
final double value = 0.016;
try {
mapper.readValue("{\"v\":[" + value + "]}", DoubleBean.class);
fail("Did not throw exception when reading a value from a single value array with the UNWRAP_SINGLE_VALUE_ARRAYS feature disabled");
} catch (JsonMappingException exp) {
//Correctly threw exception
}
mapper = jsonMapperBuilder()
.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.build();
DoubleBean result = mapper.readValue("{\"v\":[" + value + "]}",
DoubleBean.class);
assertEquals(value, result._v);
result = mapper.readValue("[{\"v\":[" + value + "]}]", DoubleBean.class);
assertEquals(value, result._v);
try {
mapper.readValue("[{\"v\":[" + value + "," + value + "]}]", DoubleBean.class);
fail("Did not throw exception while reading a value from a multi value array with UNWRAP_SINGLE_VALUE_ARRAY feature enabled");
} catch (MismatchedInputException exp) {
//threw exception as required
}
result = mapper.readValue("{\"v\":[null]}", DoubleBean.class);
assertNotNull(result);
assertEquals(0d, result._v);
double[] array = mapper.readValue("[ [ null ] ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(0d, array[0]);
}
public void testDoublePrimitiveNonNumeric() throws Exception
{
// first, simple case:
// bit tricky with binary fps but...
double value = Double.POSITIVE_INFINITY;
DoubleBean result = MAPPER.readValue("{\"v\":\""+value+"\"}", DoubleBean.class);
assertEquals(value, result._v);
// should work with arrays too..
double[] array = MAPPER.readValue("[ \"Infinity\" ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Double.POSITIVE_INFINITY, array[0]);
}
public void testDoubleSpecialValuesWithCoercionDisabled() throws Exception
{
// first, simple case:
double value = Double.POSITIVE_INFINITY;
DoubleBean result = MAPPER_NO_COERCION.readValue("{\"v\":\""+value+"\"}", DoubleBean.class);
assertEquals(value, result._v);
// should work with arrays too..
double[] array = MAPPER_NO_COERCION.readValue("[ \"Infinity\" ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Double.POSITIVE_INFINITY, array[0]);
try {
MAPPER_NO_COERCION.readValue("{\"v\":\"1.2\"}", DoubleBean.class);
fail("Expected a MismatchedInputException: string to double coercion should fail");
} catch (MismatchedInputException e) {
// expected
}
}
public void testFloatPrimitiveNonNumeric() throws Exception
{
// bit tricky with binary fps but...
float value = Float.POSITIVE_INFINITY;
FloatBean result = MAPPER.readValue("{\"v\":\""+value+"\"}", FloatBean.class);
assertEquals(value, result._v);
// should work with arrays too..
float[] array = MAPPER.readValue("[ \"Infinity\" ]", float[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(Float.POSITIVE_INFINITY, array[0]);
}
=======
>>>>>>>
public void testDoubleAsArray() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.build();
final double value = 0.016;
try {
mapper.readValue("{\"v\":[" + value + "]}", DoubleBean.class);
fail("Did not throw exception when reading a value from a single value array with the UNWRAP_SINGLE_VALUE_ARRAYS feature disabled");
} catch (JsonMappingException exp) {
//Correctly threw exception
}
mapper = jsonMapperBuilder()
.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
.build();
DoubleBean result = mapper.readValue("{\"v\":[" + value + "]}",
DoubleBean.class);
assertEquals(value, result._v);
result = mapper.readValue("[{\"v\":[" + value + "]}]", DoubleBean.class);
assertEquals(value, result._v);
try {
mapper.readValue("[{\"v\":[" + value + "," + value + "]}]", DoubleBean.class);
fail("Did not throw exception while reading a value from a multi value array with UNWRAP_SINGLE_VALUE_ARRAY feature enabled");
} catch (MismatchedInputException exp) {
//threw exception as required
}
result = mapper.readValue("{\"v\":[null]}", DoubleBean.class);
assertNotNull(result);
assertEquals(0d, result._v);
double[] array = mapper.readValue("[ [ null ] ]", double[].class);
assertNotNull(array);
assertEquals(1, array.length);
assertEquals(0d, array[0]);
} |
<<<<<<<
=======
case PULL_REQUEST_COMMENT:
return user.isSiteManager();
>>>>>>>
<<<<<<<
case COMMENT_THREAD:
case REVIEW_COMMENT:
return resource.getAuthorId().equals(user.id);
=======
case PULL_REQUEST:
case PULL_REQUEST_COMMENT:
return resource.isAuthoredBy(user);
>>>>>>>
case COMMENT_THREAD:
case REVIEW_COMMENT:
return resource.isAuthoredBy(user); |
<<<<<<<
=======
Attachment attachment = null;
List<Attachment> list = Attachment.findByContainer(Resource.USER_AVATAR, currentUser().id);
if(!list.isEmpty()) {
attachment = list.get(0);
user.avatarPath = attachment.id;
}
>>>>>>>
<<<<<<<
=======
List<Attachment> list = Attachment.findByContainer(Resource.USER_AVATAR, user.id);
if(!list.isEmpty()) {
Attachment attachment = list.get(0);
user.avatarPath = attachment.id;
}
>>>>>>>
<<<<<<<
=======
List<Attachment> list = Attachment.findByContainer(Resource.USER_AVATAR, user.id);
if(!list.isEmpty()) {
Attachment attachment = list.get(0);
user.avatarPath = attachment.id;
}
>>>>>>>
<<<<<<<
=======
Attachment.deleteAll(Resource.USER_AVATAR, currentUser().id);
Attachment.attachFiles(currentUser().id, null, Resource.USER_AVATAR, currentUser().id);
>>>>>>>
Attachment.deleteAll(Resource.USER_AVATAR, currentUser().id);
Attachment.attachFiles(currentUser().id, null, Resource.USER_AVATAR, currentUser().id); |
<<<<<<<
private static Finder<Long, Milestone> find = new Finder<Long, Milestone>(
Long.class, Milestone.class);
=======
public static Finder<Long, Milestone> find = new Finder<Long, Milestone>(
Long.class, Milestone.class);
>>>>>>>
private static Finder<Long, Milestone> find = new Finder<Long, Milestone>(
Long.class, Milestone.class);
<<<<<<<
private static int calculateCompletionRate(int numTotalIssues, int numClosedIssues) {
return new Double(((double) numClosedIssues / (double) numTotalIssues) * 100).intValue();
}
public static void delete(Long id) {
find.ref(id).delete();
=======
public static void delete(Milestone milestone) {
milestone.delete();
>>>>>>>
private static int calculateCompletionRate(int numTotalIssues, int numClosedIssues) {
return new Double(((double) numClosedIssues / (double) numTotalIssues) * 100).intValue();
}
public static void delete(Milestone milestone) {
milestone.delete(); |
<<<<<<<
/**
* 프로젝트 목록을 가져온다.
*
* when : 프로젝트명, 프로젝트 관리자, 공개여부로 프로젝트 목록 조회시
*
* 프로젝트명 / 관리자 아이디 / Overview 중 {@code query}를 포함하고
* 공개여부가 @{code state} 인 프로젝트 목록을 최근생성일로 정렬하여 페이징 형태로 가져온다.
*
* @param query 검색질의(프로젝트명 / 관리자 아이디 / Overview)
* @param pageNum 페이지번호
* @return 프로젝트명 또는 관리자 로그인 아이디가 {@code query}를 포함하고 공개여부가 @{code state} 인 프로젝트 목록
*/
=======
>>>>>>>
<<<<<<<
/**
* 프로젝트 정보를 JSON으로 가져온다.
*
* 프로젝트명 / 관리자 아이디 / Overview 중 {@code query} 가 포함되는 프로젝트 목록을 {@link #MAX_FETCH_PROJECTS} 만큼 가져오고
* JSON으로 변환하여 반환한다.
*
* @param query 검색질의(프로젝트명 / 관리자 / Overview)
* @return JSON 형태의 프로젝트 목록
*/
=======
>>>>>>>
<<<<<<<
* convert from some part of {@link models.Label} to {@link java.util.Map}
* @param label {@link models.Label} object
* @return label's map data
*/
private static Map<String, String> convertToMap(Label label) {
Map<String, String> tagMap = new HashMap<>();
tagMap.put("category", label.category);
tagMap.put("name", label.name);
return tagMap;
}
/**
* 프로젝트 설정 페이지에서 사용하며 새로운 태그를 추가하고 추가된 태그를 JSON으로 반환한다.<p />
*
* {@code ownerId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br />
* 업데이트 권한이 없을경우 forbidden을 반환한다.<br />
* 태그명 파라미터가 null일 경우 empty 데이터를 JSON으로 반환한다.<br />
* 프로젝트내 동일한 태그가 존재할 경우 empty 데이터를 JSON으로 반환한다.<br />
*
=======
>>>>>>>
* convert from some part of {@link models.Label} to {@link java.util.Map}
* @param label {@link models.Label} object
* @return label's map data
*/
private static Map<String, String> convertToMap(Label label) {
Map<String, String> tagMap = new HashMap<>();
tagMap.put("category", label.category);
tagMap.put("name", label.name);
return tagMap;
}
/** |
<<<<<<<
Ebean.save(all.get("Articles"));
=======
Ebean.save(all.get("issues"));
>>>>>>>
Ebean.save(all.get("Articles"));
Ebean.save(all.get("issues")); |
<<<<<<<
private Action<Void> getDefaultAction(final Http.Request request) {
=======
@SuppressWarnings("rawtypes")
private Action getDefaultAction(final Http.Request request) {
final long start = System.currentTimeMillis();
>>>>>>>
@SuppressWarnings("rawtypes")
private Action<Void> getDefaultAction(final Http.Request request) {
final long start = System.currentTimeMillis(); |
<<<<<<<
import com.avaje.ebean.Ebean;
=======
import models.enumeration.Resource;
>>>>>>>
import com.avaje.ebean.Ebean;
import models.enumeration.Resource;
<<<<<<<
*
* @param userId
=======
*
* @param ownerId
>>>>>>>
*
* @param userId
<<<<<<<
public static class SortByNameWithIgnoreCase implements Comparator<Object> {
public int compare(Object o1, Object o2) {
Project s1 = (Project) o1;
Project s2 = (Project) o2;
return s1.name.toLowerCase().compareTo(s2.name.toLowerCase());
}
}
public static class SortByNameWithIgnoreCaseDesc implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return -sortByNameWithIgnoreCase.compare(o1, o2);
}
}
public static class SortByDate implements Comparator<Object> {
public int compare(Object o1, Object o2) {
Project s1 = (Project) o1;
Project s2 = (Project) o2;
return s1.date.compareTo(s2.date);
}
}
public static class SortByDateDesc implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return -sortByDate.compare(o1, o2);
}
}
=======
public GlobalResource asResource() {
return new GlobalResource() {
@Override
public Long getId() {
return id;
}
@Override
public Resource getType() {
return Resource.PROJECT;
}
};
}
>>>>>>>
public static class SortByNameWithIgnoreCase implements Comparator<Object> {
public int compare(Object o1, Object o2) {
Project s1 = (Project) o1;
Project s2 = (Project) o2;
return s1.name.toLowerCase().compareTo(s2.name.toLowerCase());
}
}
public static class SortByNameWithIgnoreCaseDesc implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return -sortByNameWithIgnoreCase.compare(o1, o2);
}
}
public static class SortByDate implements Comparator<Object> {
public int compare(Object o1, Object o2) {
Project s1 = (Project) o1;
Project s2 = (Project) o2;
return s1.date.compareTo(s2.date);
}
}
public static class SortByDateDesc implements Comparator<Object> {
public int compare(Object o1, Object o2) {
return -sortByDate.compare(o1, o2);
}
}
public GlobalResource asResource() {
return new GlobalResource() {
@Override
public Long getId() {
return id;
}
@Override
public Resource getType() {
return Resource.PROJECT;
}
};
} |
<<<<<<<
final SwipeUpModel swipeUp = currentStory.getSwipeUp();
if (swipeUp != null) {
binding.swipeUp.setVisibility(View.VISIBLE);
binding.swipeUp.setText(swipeUp.getText());
binding.swipeUp.setTag(swipeUp.getUrl());
=======
swipeUp = currentStory.getSwipeUp();
if (swipeUp != null) {
binding.swipeUp.setVisibility(View.VISIBLE);
binding.swipeUp.setText(swipeUp.getText());
binding.swipeUp.setTag(swipeUp.getUrl());
} else binding.swipeUp.setVisibility(View.GONE);
>>>>>>>
final SwipeUpModel swipeUp = currentStory.getSwipeUp();
if (swipeUp != null) {
binding.swipeUp.setVisibility(View.VISIBLE);
binding.swipeUp.setText(swipeUp.getText());
binding.swipeUp.setTag(swipeUp.getUrl());
} else binding.swipeUp.setVisibility(View.GONE); |
<<<<<<<
viewModel = new ViewModelProvider(this).get(PostViewV2ViewModel.class);
=======
fragmentActivity = (MainActivity) getActivity();
mediaService = MediaService.getInstance();
final Bundle arguments = getArguments();
if (arguments == null) return;
final Serializable feedModelSerializable = arguments.getSerializable(ARG_FEED_MODEL);
if (feedModelSerializable == null) {
Log.e(TAG, "onCreate: feedModelSerializable is null");
return;
}
if (!(feedModelSerializable instanceof FeedModel)) {
return;
}
feedModel = (FeedModel) feedModelSerializable;
if (feedModel == null) return;
if (feedModel.getItemType() == MediaItemType.MEDIA_TYPE_SLIDER) {
sliderPosition = arguments.getInt(ARG_SLIDER_POSITION, 0);
}
captionState = settingsHelper.getBoolean(Constants.SHOW_CAPTIONS) ?
BottomSheetBehavior.STATE_COLLAPSED : BottomSheetBehavior.STATE_HIDDEN;
>>>>>>>
viewModel = new ViewModelProvider(this).get(PostViewV2ViewModel.class);
captionState = settingsHelper.getBoolean(Constants.SHOW_CAPTIONS) ?
BottomSheetBehavior.STATE_COLLAPSED : BottomSheetBehavior.STATE_HIDDEN;
<<<<<<<
}
private void handleTranslateCaptionResource(@NonNull final LiveData<Resource<String>> data) {
data.observe(getViewLifecycleOwner(), resource -> {
if (resource == null) return;
switch (resource.status) {
case SUCCESS:
binding.translate.setVisibility(View.GONE);
binding.caption.setText(resource.data);
break;
case ERROR:
binding.translate.setEnabled(true);
String message = resource.message;
if (TextUtils.isEmpty(resource.message)) {
message = getString(R.string.downloader_unknown_error);
}
final Snackbar snackbar = Snackbar.make(binding.getRoot(), message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.ok, null);
snackbar.show();
break;
case LOADING:
binding.translate.setEnabled(false);
break;
}
});
}
private void setupLocation(final Location location) {
if (location == null) {
binding.location.setVisibility(View.GONE);
return;
=======
if (sharedProfilePicElement == null || sharedMainPostElement == null) {
binding.getRoot().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
binding.getRoot().getViewTreeObserver().removeOnGlobalLayoutListener(this);
if (bottomSheetBehavior == null) return;
bottomSheetBehavior.setState(captionState);
}
});
>>>>>>>
}
private void handleTranslateCaptionResource(@NonNull final LiveData<Resource<String>> data) {
data.observe(getViewLifecycleOwner(), resource -> {
if (resource == null) return;
switch (resource.status) {
case SUCCESS:
binding.translate.setVisibility(View.GONE);
binding.caption.setText(resource.data);
break;
case ERROR:
binding.translate.setEnabled(true);
String message = resource.message;
if (TextUtils.isEmpty(resource.message)) {
message = getString(R.string.downloader_unknown_error);
}
final Snackbar snackbar = Snackbar.make(binding.getRoot(), message, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.ok, null);
snackbar.show();
break;
case LOADING:
binding.translate.setEnabled(false);
break;
}
});
}
private void setupLocation(final Location location) {
if (location == null) {
binding.location.setVisibility(View.GONE);
return; |
<<<<<<<
import awais.instagrabber.interfaces.FetchListener;
=======
>>>>>>> |
<<<<<<<
=======
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
>>>>>>>
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
<<<<<<<
final DialogInterface.OnClickListener onDialogListener = (dialogInterface, which) -> {
switch (which) {
case 0:
final DirectItemType itemType = directItemModel.getItemType();
switch (itemType) {
case MEDIA_SHARE:
startActivity(new Intent(requireContext(), PostViewer.class)
.putExtra(Constants.EXTRAS_POST, new PostModel(directItemModel.getMediaModel().getCode(), false)));
break;
case LINK:
Intent linkIntent = new Intent(Intent.ACTION_VIEW);
linkIntent.setData(Uri.parse(directItemModel.getLinkModel().getLinkContext().getLinkUrl()));
startActivity(linkIntent);
break;
case TEXT:
case REEL_SHARE:
Utils.copyText(requireContext(), directItemModel.getText());
Toast.makeText(requireContext(), R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
break;
case RAVEN_MEDIA:
case MEDIA:
final ProfileModel user = getUser(directItemModel.getUserId());
Utils.dmDownload(requireContext(), user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, Collections.singletonList(itemType == DirectItemType.MEDIA ? directItemModel.getMediaModel() : directItemModel.getRavenMediaModel().getMedia()));
Toast.makeText(requireContext(), R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
break;
case STORY_SHARE:
if (directItemModel.getReelShare() != null) {
StoryModel sm = new StoryModel(
directItemModel.getReelShare().getReelId(),
directItemModel.getReelShare().getMedia().getVideoUrl(),
directItemModel.getReelShare().getMedia().getMediaType(),
directItemModel.getTimestamp(),
directItemModel.getReelShare().getReelOwnerName(),
String.valueOf(directItemModel.getReelShare().getReelOwnerId()),
false
);
sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl());
StoryModel[] sms = {sm};
startActivity(new Intent(requireContext(), StoryViewer.class)
.putExtra(Constants.EXTRAS_USERNAME, directItemModel.getReelShare().getReelOwnerName())
.putExtra(Constants.EXTRAS_STORIES, sms)
);
} else if (directItemModel.getText() != null && directItemModel.getText().toString().contains("@")) {
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
}
break;
case PLACEHOLDER:
if (directItemModel.getText().toString().contains("@"))
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
break;
default:
Log.d("austin_debug", "unsupported type " + itemType);
}
break;
case 1:
sendText(null, directItemModel.getItemId(), directItemModel.isLiked());
break;
case 2:
if (String.valueOf(directItemModel.getUserId()).equals(myId)) {
// unsend: https://www.instagram.com/direct_v2/web/threads/340282366841710300949128288687654467119/items/29473546990090204551245070881259520/delete/
} else searchUsername(getUser(directItemModel.getUserId()).getUsername());
break;
=======
final DialogInterface.OnClickListener onDialogListener = (d,w) -> {
if (w == 0) {
final DirectItemType itemType = directItemModel.getItemType();
switch (itemType) {
case MEDIA_SHARE:
startActivity(new Intent(requireContext(), PostViewer.class)
.putExtra(Constants.EXTRAS_POST, new PostModel(directItemModel.getMediaModel().getCode(), false)));
break;
case LINK:
Intent linkIntent = new Intent(Intent.ACTION_VIEW);
linkIntent.setData(Uri.parse(directItemModel.getLinkModel().getLinkContext().getLinkUrl()));
startActivity(linkIntent);
break;
case TEXT:
case REEL_SHARE:
Utils.copyText(requireContext(), directItemModel.getText());
Toast.makeText(requireContext(), R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
break;
case RAVEN_MEDIA:
case MEDIA:
final ProfileModel user = getUser(directItemModel.getUserId());
Utils.dmDownload(requireContext(), user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, Collections.singletonList(itemType == DirectItemType.MEDIA ? directItemModel.getMediaModel() : directItemModel.getRavenMediaModel().getMedia()));
Toast.makeText(requireContext(), R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
break;
case STORY_SHARE:
if (directItemModel.getReelShare() != null) {
StoryModel sm = new StoryModel(
directItemModel.getReelShare().getReelId(),
directItemModel.getReelShare().getMedia().getVideoUrl(),
directItemModel.getReelShare().getMedia().getMediaType(),
directItemModel.getTimestamp(),
directItemModel.getReelShare().getReelOwnerName(),
String.valueOf(directItemModel.getReelShare().getReelOwnerId()),
false
);
sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl());
StoryModel[] sms = {sm};
startActivity(new Intent(requireContext(), StoryViewer.class)
.putExtra(Constants.EXTRAS_USERNAME, directItemModel.getReelShare().getReelOwnerName())
.putExtra(Constants.EXTRAS_STORIES, sms)
);
} else if (directItemModel.getText() != null && directItemModel.getText().toString().contains("@")) {
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
}
break;
case PLACEHOLDER:
if (directItemModel.getText().toString().contains("@"))
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
break;
default:
Log.d("austin_debug", "unsupported type " + itemType);
}
}
else if (w == 1) {
sendText(null, directItemModel.getItemId(), directItemModel.isLiked());
}
else if (w == 2) {
if (String.valueOf(directItemModel.getUserId()).equals(myId)) new Unsend().execute();
else searchUsername(getUser(directItemModel.getUserId()).getUsername());
>>>>>>>
final DialogInterface.OnClickListener onDialogListener = (dialogInterface, which) -> {
if (which == 0) {
final DirectItemType itemType = directItemModel.getItemType();
switch (itemType) {
case MEDIA_SHARE:
startActivity(new Intent(requireContext(), PostViewer.class)
.putExtra(Constants.EXTRAS_POST, new PostModel(directItemModel.getMediaModel().getCode(), false)));
break;
case LINK:
Intent linkIntent = new Intent(Intent.ACTION_VIEW);
linkIntent.setData(Uri.parse(directItemModel.getLinkModel().getLinkContext().getLinkUrl()));
startActivity(linkIntent);
break;
case TEXT:
case REEL_SHARE:
Utils.copyText(requireContext(), directItemModel.getText());
Toast.makeText(requireContext(), R.string.clipboard_copied, Toast.LENGTH_SHORT).show();
break;
case RAVEN_MEDIA:
case MEDIA:
final ProfileModel user = getUser(directItemModel.getUserId());
Utils.dmDownload(requireContext(), user.getUsername(), DownloadMethod.DOWNLOAD_DIRECT, Collections.singletonList(itemType == DirectItemType.MEDIA ? directItemModel.getMediaModel() : directItemModel.getRavenMediaModel().getMedia()));
Toast.makeText(requireContext(), R.string.downloader_downloading_media, Toast.LENGTH_SHORT).show();
break;
case STORY_SHARE:
if (directItemModel.getReelShare() != null) {
StoryModel sm = new StoryModel(
directItemModel.getReelShare().getReelId(),
directItemModel.getReelShare().getMedia().getVideoUrl(),
directItemModel.getReelShare().getMedia().getMediaType(),
directItemModel.getTimestamp(),
directItemModel.getReelShare().getReelOwnerName(),
String.valueOf(directItemModel.getReelShare().getReelOwnerId()),
false
);
sm.setVideoUrl(directItemModel.getReelShare().getMedia().getVideoUrl());
StoryModel[] sms = {sm};
startActivity(new Intent(requireContext(), StoryViewer.class)
.putExtra(Constants.EXTRAS_USERNAME, directItemModel.getReelShare().getReelOwnerName())
.putExtra(Constants.EXTRAS_STORIES, sms)
);
} else if (directItemModel.getText() != null && directItemModel.getText().toString().contains("@")) {
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
}
break;
case PLACEHOLDER:
if (directItemModel.getText().toString().contains("@"))
searchUsername(directItemModel.getText().toString().split("@")[1].split(" ")[0]);
break;
default:
Log.d("austin_debug", "unsupported type " + itemType);
}
}
else if (which == 1) {
sendText(null, directItemModel.getItemId(), directItemModel.isLiked());
}
else if (which == 2) {
if (String.valueOf(directItemModel.getUserId()).equals(myId)) new Unsend().execute();
else searchUsername(getUser(directItemModel.getUserId()).getUsername()); |
<<<<<<<
protected boolean verifyDrawable(Drawable who) {
if (mForegroundDelegate != null) {
=======
protected boolean verifyDrawable(@NonNull Drawable who) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
>>>>>>>
protected boolean verifyDrawable(@NonNull Drawable who) {
if (mForegroundDelegate != null) { |
<<<<<<<
import android.support.v7.widget.LinearLayoutCompat;
=======
import android.support.annotation.NonNull;
>>>>>>>
import android.support.v7.widget.LinearLayoutCompat;
import android.support.annotation.NonNull;
<<<<<<<
protected boolean verifyDrawable(Drawable who) {
if (mForegroundDelegate != null) {
=======
protected boolean verifyDrawable(@NonNull Drawable who) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
>>>>>>>
protected boolean verifyDrawable(@NonNull Drawable who) {
if (mForegroundDelegate != null) { |
<<<<<<<
_addConstructorCreators(ctxt, beanDesc, vchecker, intr, creators, creatorDefs);
=======
// 25-Jan-2017, tatu: As per [databind#1501], [databind#1502], [databind#1503], best
// for now to skip attempts at using anything but no-args constructor (see
// `InnerClassProperty` construction for that)
final boolean isNonStaticInnerClass = beanDesc.isNonStaticInnerClass();
if (isNonStaticInnerClass) {
// TODO: look for `@JsonCreator` annotated ones, throw explicit exception?
;
} else {
_addDeserializerConstructors(ctxt, ccState);
}
>>>>>>>
// 25-Jan-2017, tatu: As per [databind#1501], [databind#1502], [databind#1503], best
// for now to skip attempts at using anything but no-args constructor (see
// `InnerClassProperty` construction for that)
final boolean isNonStaticInnerClass = beanDesc.isNonStaticInnerClass();
if (isNonStaticInnerClass) {
// TODO: look for `@JsonCreator` annotated ones, throw explicit exception?
;
} else {
_addConstructorCreators(ctxt, ccState);
}
<<<<<<<
=======
protected void _addDeserializerFactoryMethods
(DeserializationContext ctxt, CreatorCollectionState ccState)
throws JsonMappingException
{
final BeanDescription beanDesc = ccState.beanDesc;
final CreatorCollector creators = ccState.creators;
final AnnotationIntrospector intr = ccState.annotationIntrospector();
final VisibilityChecker<?> vchecker = ccState.vchecker;
final Map<AnnotatedWithParams, BeanPropertyDefinition[]> creatorParams = ccState.creatorDefs;
List<CreatorCandidate> nonAnnotated = new LinkedList<>();
int explCount = 0;
// 21-Sep-2017, tatu: First let's handle explicitly annotated ones
for (AnnotatedMethod factory : beanDesc.getFactoryMethods()) {
JsonCreator.Mode creatorMode = intr.findCreatorAnnotation(ctxt.getConfig(), factory);
final int argCount = factory.getParameterCount();
if (creatorMode == null) {
// Only potentially accept 1-argument factory methods
if ((argCount == 1) && vchecker.isCreatorVisible(factory)) {
nonAnnotated.add(CreatorCandidate.construct(intr, factory, null));
}
continue;
}
if (creatorMode == Mode.DISABLED) {
continue;
}
// zero-arg method factory methods fine, as long as explicit
if (argCount == 0) {
creators.setDefaultCreator(factory);
continue;
}
switch (creatorMode) {
case DELEGATING:
_addExplicitDelegatingCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, null));
break;
case PROPERTIES:
_addExplicitPropertyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)));
break;
case DEFAULT:
default:
_addExplicitAnyCreator(ctxt, beanDesc, creators,
CreatorCandidate.construct(intr, factory, creatorParams.get(factory)),
// 13-Sep-2020, tatu: Factory methods do not follow config settings
// (as of Jackson 2.12)
ConstructorDetector.DEFAULT);
break;
}
++explCount;
}
// And only if and when those handled, consider potentially visible ones
if (explCount > 0) { // TODO: split method into two since we could have expl factories
return;
}
// And then implicitly found
for (CreatorCandidate candidate : nonAnnotated) {
final int argCount = candidate.paramCount();
AnnotatedWithParams factory = candidate.creator();
final BeanPropertyDefinition[] propDefs = creatorParams.get(factory);
// some single-arg factory methods (String, number) are auto-detected
if (argCount != 1) {
continue; // 2 and more args? Must be explicit, handled earlier
}
BeanPropertyDefinition argDef = candidate.propertyDef(0);
boolean useProps = _checkIfCreatorPropertyBased(intr, factory, argDef);
if (!useProps) { // not property based but delegating
/*boolean added=*/ _handleSingleArgumentCreator(creators,
factory, false, vchecker.isCreatorVisible(factory));
// 23-Sep-2016, tatu: [databind#1383]: Need to also sever link to avoid possible
// later problems with "unresolved" constructor property
if (argDef != null) {
((POJOPropertyBuilder) argDef).removeConstructors();
}
continue;
}
AnnotatedParameter nonAnnotatedParam = null;
SettableBeanProperty[] properties = new SettableBeanProperty[argCount];
int implicitNameCount = 0;
int explicitNameCount = 0;
int injectCount = 0;
for (int i = 0; i < argCount; ++i) {
final AnnotatedParameter param = factory.getParameter(i);
BeanPropertyDefinition propDef = (propDefs == null) ? null : propDefs[i];
JacksonInject.Value injectable = intr.findInjectableValue(param);
final PropertyName name = (propDef == null) ? null : propDef.getFullName();
if (propDef != null && propDef.isExplicitlyNamed()) {
++explicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
if (injectable != null) {
++injectCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
NameTransformer unwrapper = intr.findUnwrappingNameTransformer(param);
if (unwrapper != null) {
_reportUnwrappedCreatorProperty(ctxt, beanDesc, param);
/*
properties[i] = constructCreatorProperty(ctxt, beanDesc, UNWRAPPED_CREATOR_PARAM_NAME, i, param, null);
++implicitNameCount;
*/
continue;
}
// One more thing: implicit names are ok iff ctor has creator annotation
/*
if (isCreator) {
if (name != null && !name.isEmpty()) {
++implicitNameCount;
properties[i] = constructCreatorProperty(ctxt, beanDesc, name, i, param, injectable);
continue;
}
}
*/
/* 25-Sep-2014, tatu: Actually, we may end up "losing" naming due to higher-priority constructor
* (see TestCreators#testConstructorCreator() test). And just to avoid running into that problem,
* let's add one more work around
*/
/*
PropertyName name2 = _findExplicitParamName(param, intr);
if (name2 != null && !name2.isEmpty()) {
// Hmmh. Ok, fine. So what are we to do with it... ?
// For now... skip. May need to revisit this, should this become problematic
continue main_loop;
}
*/
if (nonAnnotatedParam == null) {
nonAnnotatedParam = param;
}
}
final int namedCount = explicitNameCount + implicitNameCount;
// Ok: if named or injectable, we have more work to do
if (explicitNameCount > 0 || injectCount > 0) {
// simple case; everything covered:
if ((namedCount + injectCount) == argCount) {
creators.addPropertyCreator(factory, false, properties);
} else if ((explicitNameCount == 0) && ((injectCount + 1) == argCount)) {
// secondary: all but one injectable, one un-annotated (un-named)
creators.addDelegatingCreator(factory, false, properties, 0);
} else { // otherwise, epic fail
ctxt.reportBadTypeDefinition(beanDesc,
"Argument #%d of factory method %s has no property name annotation; must have name when multiple-parameter constructor annotated as Creator",
nonAnnotatedParam.getIndex(), factory);
}
}
}
}
>>>>>>> |
<<<<<<<
=======
import com.fasterxml.jackson.annotation.JsonIncludeProperties;
>>>>>>>
import com.fasterxml.jackson.annotation.JsonIncludeProperties;
<<<<<<<
/**********************************************************************
=======
/**********************************************************
*/
/**
* @since 2.12
>>>>>>>
/**********************************************************************
<<<<<<<
protected MapSerializer(MapSerializer src,
TypeSerializer vts, Object suppressableValue, boolean suppressNulls)
=======
/**
* @deprecated in 2.12, remove from 3.0
*/
@SuppressWarnings("unchecked")
@Deprecated
protected MapSerializer(MapSerializer src, BeanProperty property,
JsonSerializer<?> keySerializer, JsonSerializer<?> valueSerializer,
Set<String> ignoredEntries)
{
this(src, property, keySerializer, valueSerializer, ignoredEntries, null);
}
/**
* @since 2.9
*/
protected MapSerializer(MapSerializer src, TypeSerializer vts,
Object suppressableValue, boolean suppressNulls)
>>>>>>>
protected MapSerializer(MapSerializer src,
TypeSerializer vts, Object suppressableValue, boolean suppressNulls)
<<<<<<<
=======
/**
* @since 2.12
*/
>>>>>>>
<<<<<<<
public static MapSerializer construct(Set<String> ignoredEntries, JavaType mapType,
=======
/**
* @since 2.12
*/
public static MapSerializer construct(Set<String> ignoredEntries, Set<String> includedEntries, JavaType mapType,
>>>>>>>
public static MapSerializer construct(Set<String> ignoredEntries, Set<String> includedEntries, JavaType mapType,
<<<<<<<
=======
/**
* @since 2.8
*/
public static MapSerializer construct(Set<String> ignoredEntries, JavaType mapType,
boolean staticValueType, TypeSerializer vts,
JsonSerializer<Object> keySerializer, JsonSerializer<Object> valueSerializer,
Object filterId)
{
return construct(ignoredEntries, null, mapType, staticValueType, vts, keySerializer, valueSerializer, filterId);
}
/**
* @since 2.9
*/
>>>>>>>
<<<<<<<
JsonIgnoreProperties.Value ignorals = intr.findPropertyIgnorals(config, propertyAcc);
=======
// ignorals
JsonIgnoreProperties.Value ignorals = intr.findPropertyIgnorals(propertyAcc);
>>>>>>>
JsonIgnoreProperties.Value ignorals = intr.findPropertyIgnorals(config, propertyAcc);
<<<<<<<
Boolean b = intr.findSerializationSortAlphabetically(config, propertyAcc);
=======
// inclusions
JsonIncludeProperties.Value inclusions = intr.findPropertyInclusions(propertyAcc);
if (inclusions != null) {
Set<String> newIncluded = inclusions.getIncluded();
if (newIncluded != null) {
included = (included == null) ? new HashSet<String>() : new HashSet<String>(included);
for (String str : newIncluded) {
included.add(str);
}
}
}
// sort key
Boolean b = intr.findSerializationSortAlphabetically(propertyAcc);
>>>>>>>
// inclusions
JsonIncludeProperties.Value inclusions = intr.findPropertyInclusions(config, propertyAcc);
if (inclusions != null) {
Set<String> newIncluded = inclusions.getIncluded();
if (newIncluded != null) {
included = (included == null) ? new HashSet<String>() : new HashSet<String>(included);
for (String str : newIncluded) {
included.add(str);
}
}
}
// sort key
Boolean b = intr.findSerializationSortAlphabetically(config, propertyAcc); |
<<<<<<<
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
=======
import cpw.mods.fml.common.event.FMLServerStartingEvent;
>>>>>>>
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
<<<<<<<
proxy.registerClient();//must be loaded after configs
=======
FMLCommonHandler.instance().bus().register(this);
>>>>>>>
proxy.registerClient();//must be loaded after configs
<<<<<<<
@SubscribeEvent
public void onConfigChanged(OnConfigChangedEvent evt)
{
if(AncientWarfareCore.modID.equals(evt.modID))
{
proxy.onConfigChanged();
}
}
=======
@EventHandler
public void serverStart(FMLServerStartingEvent evt)
{
evt.registerServerCommand(new CommandFaction());
}
>>>>>>>
@SubscribeEvent
public void onConfigChanged(OnConfigChangedEvent evt)
{
if(AncientWarfareCore.modID.equals(evt.modID))
{
proxy.onConfigChanged();
}
}
@EventHandler
public void serverStart(FMLServerStartingEvent evt)
{
evt.registerServerCommand(new CommandFaction());
} |
<<<<<<<
/**
* Vehicle Module Entity Registrations
*/
=======
public static final String NPC_FACTION_BANDIT_BARD = "bandit.bard";
public static final String NPC_FACTION_DESERT_BARD = "desert.bard";
public static final String NPC_FACTION_NATIVE_BARD = "native.bard";
public static final String NPC_FACTION_PIRATE_BARD = "pirate.bard";
public static final String NPC_FACTION_VIKING_BARD = "viking.bard";
public static final String NPC_FACTION_CUSTOM_1_BARD = "custom_1.bard";
public static final String NPC_FACTION_CUSTOM_2_BARD = "custom_2.bard";
public static final String NPC_FACTION_CUSTOM_3_BARD = "custom_3.bard";
>>>>>>>
public static final String NPC_FACTION_BANDIT_BARD = "bandit.bard";
public static final String NPC_FACTION_DESERT_BARD = "desert.bard";
public static final String NPC_FACTION_NATIVE_BARD = "native.bard";
public static final String NPC_FACTION_PIRATE_BARD = "pirate.bard";
public static final String NPC_FACTION_VIKING_BARD = "viking.bard";
public static final String NPC_FACTION_CUSTOM_1_BARD = "custom_1.bard";
public static final String NPC_FACTION_CUSTOM_2_BARD = "custom_2.bard";
public static final String NPC_FACTION_CUSTOM_3_BARD = "custom_3.bard";
/**
* Vehicle Module Entity Registrations
*/ |
<<<<<<<
public class TileEngineeringStation extends TileEntity implements IRotatableTile {
ForgeDirection facing = ForgeDirection.NORTH;
public InventoryCrafting layoutMatrix;
public InventoryCraftResult result;
public InventoryBasic bookInventory = new InventoryBasic(1) {
public void markDirty() {
onLayoutMatrixChanged(layoutMatrix);
}
;
=======
public class TileEngineeringStation extends TileEntity implements IRotatableTile {
ForgeDirection facing = ForgeDirection.NORTH;
public InventoryCrafting layoutMatrix;
public InventoryCraftResult result;
public InventoryBasic bookInventory = new InventoryBasic(1) {
@Override
public void markDirty() {
onLayoutMatrixChanged(layoutMatrix);
}
>>>>>>>
public class TileEngineeringStation extends TileEntity implements IRotatableTile {
ForgeDirection facing = ForgeDirection.NORTH;
public InventoryCrafting layoutMatrix;
public InventoryCraftResult result;
public InventoryBasic bookInventory = new InventoryBasic(1) {
@Override
public void markDirty() {
onLayoutMatrixChanged(layoutMatrix);
}
; |
<<<<<<<
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.RenderTickEvent;
=======
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.RenderTickEvent;
>>>>>>>
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent; |
<<<<<<<
=======
private String zoneOffset(String raw) {
// Add colon or not -- difference between 2.10 and earlier, 2.11 and later
return raw.substring(0, 2) + ":" + raw.substring(2); // 2.11 and later
// return raw; // 2.10 and earlier
}
>>>>>>> |
<<<<<<<
=======
import cpw.mods.fml.common.registry.EntityRegistry;
>>>>>>>
import cpw.mods.fml.common.registry.EntityRegistry; |
<<<<<<<
if (properties != null && !properties.isEmpty()) {
for (Property property : properties) {
JMethod method = jc.method(NONE, getGetterMethodReturnType(property),
Constants.STRING_GET + property.getFieldGetterName());
addJavadocToMethod(method, property);
}
}
=======
properties.forEach(property -> jc.method(NONE, getGetterMethodReturnType(property),
Constants.STRING_GET + property.getFieldGetterName()));
>>>>>>>
for (Property property : properties) {
JMethod method = jc.method(NONE, getGetterMethodReturnType(property),
Constants.STRING_GET + property.getFieldGetterName());
addJavadocToMethod(method, property);
}
<<<<<<<
/**
* Adds Javadoc to the method based on the information in the property and the generation config options.
* @param method
* @param property
*/
private void addJavadocToMethod(JMethod method, Property property) {
JDocComment javadoc = method.javadoc();
if (StringUtils.isNotBlank(property.getJavadoc())) {
javadoc.append(property.getJavadoc());
javadoc.append("\n\n@return " + getGetterMethodReturnType(property).name());
} else if (generationConfig.getOptions() != null && generationConfig.getOptions().isHasGenericJavadoc()) {
javadoc.append("Get the " + property.getField() + ".");
javadoc.append("\n\n@return " + getGetterMethodReturnType(property).name());
}
}
=======
/**
* Sets property attributes
*/
private void setProperties() {
Set<Property> occurredProperties = new HashSet<>();
globalProperties = filterProperties(occurredProperties, generationConfig.getOptions().getGlobalProperties());
occurredProperties.addAll(globalProperties);
sharedProperties = filterProperties(occurredProperties, generationConfig.getOptions().getSharedProperties());
occurredProperties.addAll(sharedProperties);
privateProperties = filterProperties(occurredProperties, generationConfig.getOptions().getProperties());
occurredProperties.addAll(privateProperties);
}
/**
* Filters the given properties for invalid fields and returns all that are not contained in occurredProperties.
*
* @param occurredProperties
* @param originalProperties
* @return filtered properties
*/
private List<Property> filterProperties(Set<Property> occurredProperties, List<Property> originalProperties) {
List<Property> properties;
if (originalProperties != null) {
properties = originalProperties.stream()
.filter(Objects::nonNull)
.filter(property -> StringUtils.isNotBlank(property.getField()))
.filter(property -> StringUtils.isNotBlank(property.getType()))
.filter(property -> !(occurredProperties.contains(property)))
.collect(Collectors.toList());
} else {
properties = Collections.emptyList();
}
return properties;
}
>>>>>>>
/**
* Adds Javadoc to the method based on the information in the property and the generation config options.
*
* @param method
* @param property
*/
private void addJavadocToMethod(JMethod method, Property property) {
JDocComment javadoc = method.javadoc();
if (StringUtils.isNotBlank(property.getJavadoc())) {
javadoc.append(property.getJavadoc());
javadoc.append("\n\n@return " + getGetterMethodReturnType(property).name());
} else if (generationConfig.getOptions() != null && generationConfig.getOptions().isHasGenericJavadoc()) {
javadoc.append("Get the " + property.getField() + ".");
javadoc.append("\n\n@return " + getGetterMethodReturnType(property).name());
}
}
/**
* Sets property attributes
*/
private void setProperties() {
Set<Property> occurredProperties = new HashSet<>();
globalProperties = filterProperties(occurredProperties, generationConfig.getOptions().getGlobalProperties());
occurredProperties.addAll(globalProperties);
sharedProperties = filterProperties(occurredProperties, generationConfig.getOptions().getSharedProperties());
occurredProperties.addAll(sharedProperties);
privateProperties = filterProperties(occurredProperties, generationConfig.getOptions().getProperties());
occurredProperties.addAll(privateProperties);
}
/**
* Filters the given properties for invalid fields and returns all that are not contained in occurredProperties.
*
* @param occurredProperties
* @param originalProperties
* @return filtered properties
*/
private List<Property> filterProperties(Set<Property> occurredProperties, List<Property> originalProperties) {
List<Property> properties;
if (originalProperties != null) {
properties = originalProperties.stream()
.filter(Objects::nonNull)
.filter(property -> StringUtils.isNotBlank(property.getField()))
.filter(property -> StringUtils.isNotBlank(property.getType()))
.filter(property -> !(occurredProperties.contains(property)))
.collect(Collectors.toList());
} else {
properties = Collections.emptyList();
}
return properties;
} |
<<<<<<<
=======
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
>>>>>>>
import org.apache.http.impl.conn.SystemDefaultDnsResolver; |
<<<<<<<
import de.is24.infrastructure.gridfs.http.security.PGPSigner;
=======
import de.is24.infrastructure.gridfs.http.security.HostNamePatternFilter;
>>>>>>>
import de.is24.infrastructure.gridfs.http.security.HostNamePatternFilter;
import de.is24.infrastructure.gridfs.http.security.PGPSigner;
<<<<<<<
public PGPSigner pgpSigner() {
return new PGPSigner(new ClassPathResource("/gpg/secring.gpg"), "yum-repo-server");
}
=======
public HostNamePatternFilter hostNamePatternFilter() {
if (hostNamePatternFilter == null) {
hostNamePatternFilter = new HostNamePatternFilter("");
}
return hostNamePatternFilter;
}
>>>>>>>
public HostNamePatternFilter hostNamePatternFilter() {
if (hostNamePatternFilter == null) {
hostNamePatternFilter = new HostNamePatternFilter("");
}
return hostNamePatternFilter;
}
public PGPSigner pgpSigner() {
return new PGPSigner(new ClassPathResource("/gpg/secring.gpg"), "yum-repo-server");
} |
<<<<<<<
hostAndRows.getValue(), batchColumnRangeSelection, timestamp),
"Atlas getRowsColumnRange " + hostAndRows.getValue().size() + " rows from " + tableRef + " on " + hostAndRows.getKey(),
=======
hostAndRows.getValue(), columnRangeSelection, timestamp),
"Atlas getRowsColumnRange " + hostAndRows.getValue().size()
+ " rows from " + tableRef + " on " + hostAndRows.getKey(),
>>>>>>>
hostAndRows.getValue(), batchColumnRangeSelection, timestamp),
"Atlas getRowsColumnRange " + hostAndRows.getValue().size()
+ " rows from " + tableRef + " on " + hostAndRows.getKey(),
<<<<<<<
private Map<byte[], RowColumnRangeIterator> getRowsColumnRangeIteratorForSingleHost(InetSocketAddress host,
TableReference tableRef,
List<byte[]> rows,
BatchColumnRangeSelection batchColumnRangeSelection,
long startTs) {
=======
private Map<byte[], RowColumnRangeIterator> getRowsColumnRangeIteratorForSingleHost(
InetSocketAddress host,
TableReference tableRef,
List<byte[]> rows,
ColumnRangeSelection columnRangeSelection,
long startTs) {
>>>>>>>
private Map<byte[], RowColumnRangeIterator> getRowsColumnRangeIteratorForSingleHost(
InetSocketAddress host,
TableReference tableRef,
List<byte[]> rows,
BatchColumnRangeSelection batchColumnRangeSelection,
long startTs) {
<<<<<<<
boolean endOfRange = isEndOfColumnRange(completedCell, col, firstPage.getRowsToRawColumnCount().get(row), batchColumnRangeSelection);
=======
boolean endOfRange = isEndOfColumnRange(
completedCell,
col,
firstPage.getRowsToRawColumnCount().get(row),
columnRangeSelection);
>>>>>>>
boolean endOfRange = isEndOfColumnRange(
completedCell,
col,
firstPage.getRowsToRawColumnCount().get(row),
batchColumnRangeSelection);
<<<<<<<
BatchColumnRangeSelection newColumnRange = new BatchColumnRangeSelection(nextCol,
batchColumnRangeSelection.getEndCol(), batchColumnRangeSelection.getBatchHint());
ret.put(row, new LocalRowColumnRangeIterator(Iterators.concat(resultIterator, getRowColumnRange(host, tableRef, row, newColumnRange, startTs))));
=======
ColumnRangeSelection newColumnRange = new ColumnRangeSelection(nextCol,
columnRangeSelection.getEndCol(), columnRangeSelection.getBatchHint());
ret.put(row, new LocalRowColumnRangeIterator(Iterators.concat(
resultIterator,
getRowColumnRange(host, tableRef, row, newColumnRange, startTs))));
>>>>>>>
BatchColumnRangeSelection newColumnRange = new BatchColumnRangeSelection(nextCol,
batchColumnRangeSelection.getEndCol(), batchColumnRangeSelection.getBatchHint());
ret.put(row, new LocalRowColumnRangeIterator(Iterators.concat(
resultIterator,
getRowColumnRange(host, tableRef, row, newColumnRange, startTs))));
<<<<<<<
BatchColumnRangeSelection columnRangeSelection) {
return (numRawResults < columnRangeSelection.getBatchHint()) ||
(completedCell &&
(RangeRequests.isLastRowName(lastCol)
|| Arrays.equals(RangeRequests.nextLexicographicName(lastCol), columnRangeSelection.getEndCol())));
=======
ColumnRangeSelection columnRangeSelection) {
return (numRawResults < columnRangeSelection.getBatchHint())
|| (completedCell
&& (RangeRequests.isLastRowName(lastCol)
|| Arrays.equals(
RangeRequests.nextLexicographicName(lastCol),
columnRangeSelection.getEndCol())));
>>>>>>>
BatchColumnRangeSelection columnRangeSelection) {
return (numRawResults < columnRangeSelection.getBatchHint())
|| (completedCell
&& (RangeRequests.isLastRowName(lastCol)
|| Arrays.equals(
RangeRequests.nextLexicographicName(lastCol),
columnRangeSelection.getEndCol()))); |
<<<<<<<
import org.joda.time.Duration;
=======
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.AfterClass;
>>>>>>>
import java.net.InetSocketAddress;
import org.joda.time.Duration;
<<<<<<<
public static void waitUntilCassandraIsUp() {
CassandraTestTools.waitTillServiceIsUp(CassandraTestConfigs.CASSANDRA_HOST, CassandraTestConfigs.THRIFT_PORT, Duration.millis(2000));
=======
public static void setup() throws IOException, InterruptedException {
CassandraService.start(CassandraService.DEFAULT_CONFIG);
}
@AfterClass
public static void stop() throws IOException {
CassandraService.stop();
>>>>>>>
public static void waitUntilCassandraIsUp() {
CassandraTestTools.waitTillServiceIsUp(CassandraTestConfigs.CASSANDRA_HOST, CassandraTestConfigs.THRIFT_PORT, Duration.millis(2000)); |
<<<<<<<
keyValueService = CassandraKeyValueService.create(
CassandraKeyValueServiceConfigManager.createSimpleManager(CassandraTestSuite.CASSANDRA_KVS_CONFIG), CassandraTestSuite.LEADER_CONFIG);
=======
keyValueService = getKeyValueService();
}
@Override
protected KeyValueService getKeyValueService() {
return CassandraKeyValueService.create(
CassandraKeyValueServiceConfigManager.createSimpleManager(CassandraTestSuite.CASSANDRA_KVS_CONFIG));
>>>>>>>
keyValueService = getKeyValueService();
}
@Override
protected KeyValueService getKeyValueService() {
return CassandraKeyValueService.create(
CassandraKeyValueServiceConfigManager.createSimpleManager(CassandraTestSuite.CASSANDRA_KVS_CONFIG), CassandraTestSuite.LEADER_CONFIG); |
<<<<<<<
public abstract Optional<Integer> timestampsGetterBatchSize();
=======
@Value.Default
public boolean scyllaDb() {
return false;
}
>>>>>>>
@Value.Default
public boolean scyllaDb() {
return false;
}
public abstract Optional<Integer> timestampsGetterBatchSize(); |
<<<<<<<
import java.util.Objects;
=======
import java.util.Optional;
>>>>>>>
import java.util.Objects;
import java.util.Optional;
<<<<<<<
public Map<byte[], RowColumnRangeIterator> getRowsColumnRange(TableReference tableRef, Iterable<byte[]> rows, BatchColumnRangeSelection columnRangeSelection, long timestamp) {
=======
public Map<byte[], RowColumnRangeIterator> getRowsColumnRange(
TableReference tableRef, Iterable<byte[]> rows, ColumnRangeSelection columnRangeSelection, long timestamp) {
>>>>>>>
public Map<byte[], RowColumnRangeIterator> getRowsColumnRange(
TableReference tableRef,
Iterable<byte[]> rows,
BatchColumnRangeSelection columnRangeSelection,
long timestamp) {
<<<<<<<
new BatchColumnRangeSelection(nextCol, columnRangeSelection.getEndCol(), columnRangeSelection.getBatchHint()),
=======
new ColumnRangeSelection(
nextCol,
columnRangeSelection.getEndCol(),
columnRangeSelection.getBatchHint()),
>>>>>>>
nextColumnRangeSelection,
<<<<<<<
private Iterator<Map.Entry<Cell, Value>> getRowColumnRange(TableReference tableRef, final byte[] row,
final BatchColumnRangeSelection columnRangeSelection, long ts) {
=======
private Iterator<Map.Entry<Cell, Value>> getRowColumnRange(
TableReference tableRef,
byte[] row,
ColumnRangeSelection columnRangeSelection,
long ts) {
>>>>>>>
@Override
public RowColumnRangeIterator getRowsColumnRange(TableReference tableRef,
Iterable<byte[]> rows,
ColumnRangeSelection columnRangeSelection,
int cellBatchHint,
long timestamp) {
List<byte[]> rowList = ImmutableList.copyOf(rows);
Map<Sha256Hash, byte[]> hashesToBytes = Maps.uniqueIndex(rowList, Sha256Hash::computeHash);
Map<Sha256Hash, Integer> ordered =
getColumnCounts(tableRef, rowList, columnRangeSelection, timestamp);
Iterator<Map<Sha256Hash, Integer>> batches = partitionByTotalCount(ordered, cellBatchHint).iterator();
Iterator<Iterator<Map.Entry<Cell, Value>>> results = new AbstractIterator<Iterator<Map.Entry<Cell, Value>>>() {
private Sha256Hash lastRowHashInPreviousBatch = null;
private byte[] lastColumnInPreviousBatch = null;
@Override
protected Iterator<Map.Entry<Cell, Value>> computeNext() {
if (!batches.hasNext()) {
return endOfData();
}
Map<Sha256Hash, Integer> currBatch = batches.next();
Map<byte[], BatchColumnRangeSelection> columnRangeSelectionsByRow = new HashMap<>(currBatch.size());
for (Map.Entry<Sha256Hash, Integer> entry : currBatch.entrySet()) {
Sha256Hash rowHash = entry.getKey();
byte[] startCol = Objects.equals(lastRowHashInPreviousBatch, rowHash)
? RangeRequests.nextLexicographicName(lastColumnInPreviousBatch)
: columnRangeSelection.getStartCol();
BatchColumnRangeSelection batchColumnRangeSelection =
new BatchColumnRangeSelection(startCol, columnRangeSelection.getEndCol(), entry.getValue());
columnRangeSelectionsByRow.put(hashesToBytes.get(rowHash), batchColumnRangeSelection);
}
Map<byte[], List<Map.Entry<Cell, Value>>> resultsByRow =
runRead(tableRef,
dbReadTable -> extractRowColumnRangePage(dbReadTable, columnRangeSelectionsByRow,
timestamp));
int totalEntries = resultsByRow.values().stream().mapToInt(List::size).sum();
if (totalEntries == 0) {
return Collections.emptyIterator();
}
// Ensure order matches that of the provided batch.
List<Map.Entry<Cell, Value>> ret = new ArrayList<>(totalEntries);
for (Sha256Hash rowHash : currBatch.keySet()) {
byte[] row = hashesToBytes.get(rowHash);
ret.addAll(resultsByRow.get(row));
}
Cell lastCell = Iterables.getLast(ret).getKey();
lastRowHashInPreviousBatch = Sha256Hash.computeHash(lastCell.getRowName());
lastColumnInPreviousBatch = lastCell.getColumnName();
return ret.iterator();
}
};
return new LocalRowColumnRangeIterator(Iterators.concat(results));
}
private Iterator<Map.Entry<Cell, Value>> getRowColumnRange(TableReference tableRef, final byte[] row,
final BatchColumnRangeSelection columnRangeSelection, long ts) {
<<<<<<<
TokenBackedBasicResultsPage<Map.Entry<Cell, Value>, byte[]> page(final byte[] startCol) throws Exception {
BatchColumnRangeSelection range = new BatchColumnRangeSelection(startCol, columnRangeSelection.getEndCol(), columnRangeSelection.getBatchHint());
List<Map.Entry<Cell, Value>> nextPage = runRead(tableRef, new Function<DbReadTable, List<Map.Entry<Cell, Value>>>() {
@Override
public List<Map.Entry<Cell, Value>> apply(DbReadTable table) {
return Iterables.getOnlyElement(extractRowColumnRangePage(table, range, ts, rowList).values());
}
});
=======
TokenBackedBasicResultsPage<Map.Entry<Cell, Value>, byte[]> page(byte[] startCol) throws Exception {
ColumnRangeSelection range = new ColumnRangeSelection(
startCol,
columnRangeSelection.getEndCol(),
columnRangeSelection.getBatchHint());
List<Map.Entry<Cell, Value>> nextPage = runRead(tableRef, table ->
Iterables.getOnlyElement(extractRowColumnRangePage(table, range, ts, rowList).values()));
>>>>>>>
TokenBackedBasicResultsPage<Map.Entry<Cell, Value>, byte[]> page(byte[] startCol) throws Exception {
BatchColumnRangeSelection range =
new BatchColumnRangeSelection(startCol,
columnRangeSelection.getEndCol(),
columnRangeSelection.getBatchHint());
List<Map.Entry<Cell, Value>> nextPage =
runRead(tableRef,
table -> Iterables.getOnlyElement(
extractRowColumnRangePage(table, range, ts, rowList).values()));
<<<<<<<
private Map<byte[], List<Map.Entry<Cell, Value>>> getFirstRowsColumnRangePage(TableReference tableRef, List<byte[]> rows,
BatchColumnRangeSelection columnRangeSelection, long ts) {
=======
private Map<byte[], List<Map.Entry<Cell, Value>>> getFirstRowsColumnRangePage(
TableReference tableRef,
List<byte[]> rows,
ColumnRangeSelection columnRangeSelection,
long ts) {
>>>>>>>
private Map<byte[], List<Map.Entry<Cell, Value>>> getFirstRowsColumnRangePage(
TableReference tableRef,
List<byte[]> rows,
BatchColumnRangeSelection columnRangeSelection,
long ts) {
<<<<<<<
private Map<byte[], List<Entry<Cell, Value>>> extractRowColumnRangePage(DbReadTable table,
BatchColumnRangeSelection columnRangeSelection,
long ts,
List<byte[]> rows) {
return extractRowColumnRangePage(table, Maps.toMap(rows, Functions.constant(columnRangeSelection)), ts);
}
private Map<byte[], List<Map.Entry<Cell, Value>>> extractRowColumnRangePage(DbReadTable table,
Map<byte[], BatchColumnRangeSelection> columnRangeSelectionsByRow,
long ts) {
Map<Sha256Hash, byte[]> hashesToBytes = Maps.newHashMapWithExpectedSize(columnRangeSelectionsByRow.size());
=======
private Map<byte[], List<Map.Entry<Cell, Value>>> extractRowColumnRangePage(
DbReadTable table,
ColumnRangeSelection columnRangeSelection,
long ts,
List<byte[]> rows) {
Map<Sha256Hash, byte[]> hashesToBytes = Maps.newHashMapWithExpectedSize(rows.size());
>>>>>>>
private Map<byte[], List<Entry<Cell, Value>>> extractRowColumnRangePage(
DbReadTable table,
BatchColumnRangeSelection columnRangeSelection,
long ts,
List<byte[]> rows) {
return extractRowColumnRangePage(table, Maps.toMap(rows, Functions.constant(columnRangeSelection)), ts);
}
private Map<byte[], List<Map.Entry<Cell, Value>>> extractRowColumnRangePage(
DbReadTable table,
Map<byte[], BatchColumnRangeSelection> columnRangeSelectionsByRow,
long ts) {
Map<Sha256Hash, byte[]> hashesToBytes = Maps.newHashMapWithExpectedSize(columnRangeSelectionsByRow.size());
<<<<<<<
for (Iterator<Entry<Cell, OverflowValue>> entryIter =
overflowValues.entrySet().iterator(); entryIter.hasNext();) {
Entry<Cell, OverflowValue> entry = entryIter.next();
=======
Iterator<Entry<Cell, OverflowValue>> overflowIterator = overflowValues.entrySet().iterator();
while (overflowIterator.hasNext()) {
Entry<Cell, OverflowValue> entry = overflowIterator.next();
>>>>>>>
Iterator<Entry<Cell, OverflowValue>> overflowIterator = overflowValues.entrySet().iterator();
while (overflowIterator.hasNext()) {
Entry<Cell, OverflowValue> entry = overflowIterator.next(); |
<<<<<<<
import com.palantir.atlasdb.qos.config.QosServiceInstallConfig;
import com.palantir.atlasdb.qos.config.QosServiceRuntimeConfig;
=======
import com.palantir.atlasdb.qos.ratelimit.OneReturningClientLimitMultiplier;
>>>>>>>
import com.palantir.atlasdb.qos.config.QosServiceInstallConfig;
import com.palantir.atlasdb.qos.ratelimit.OneReturningClientLimitMultiplier;
<<<<<<<
when(config.get()).thenReturn(configWithLimits(ImmutableMap.of()));
resource = new QosResource(config, installConfig);
=======
QosClientConfigLoader qosClientConfigLoader = QosClientConfigLoader.create(ImmutableMap::of);
OneReturningClientLimitMultiplier oneReturningClientLimitMultiplier = new OneReturningClientLimitMultiplier();
resource = new QosResource(qosClientConfigLoader, oneReturningClientLimitMultiplier);
>>>>>>>
QosClientConfigLoader qosClientConfigLoader = QosClientConfigLoader.create(ImmutableMap::of);
OneReturningClientLimitMultiplier oneReturningClientLimitMultiplier = new OneReturningClientLimitMultiplier();
resource = new QosResource(qosClientConfigLoader, oneReturningClientLimitMultiplier);
<<<<<<<
when(config.get())
.thenReturn(configWithLimits(ImmutableMap.of("foo", 10L)))
.thenReturn(configWithLimits(ImmutableMap.of("foo", 20L)));
resource = new QosResource(config, installConfig);
=======
QosClientConfigLoader qosClientConfigLoader = QosClientConfigLoader.create(
new Supplier<Map<String, QosClientLimitsConfig>>() {
Iterator<Map<String, QosClientLimitsConfig>> configIterator =
ImmutableList.of(
configWithLimits(ImmutableMap.of("foo", 10L)),
configWithLimits(ImmutableMap.of("foo", 20L)),
configWithLimits(ImmutableMap.of("foo", 30L)))
.iterator();
@Override
public Map<String, QosClientLimitsConfig> get() {
return configIterator.next();
}
});
resource = new QosResource(qosClientConfigLoader, OneReturningClientLimitMultiplier.create());
>>>>>>>
QosClientConfigLoader qosClientConfigLoader = QosClientConfigLoader.create(
new Supplier<Map<String, QosClientLimitsConfig>>() {
Iterator<Map<String, QosClientLimitsConfig>> configIterator =
ImmutableList.of(
configWithLimits(ImmutableMap.of("foo", 10L)),
configWithLimits(ImmutableMap.of("foo", 20L)),
configWithLimits(ImmutableMap.of("foo", 30L)))
.iterator();
@Override
public Map<String, QosClientLimitsConfig> get() {
return configIterator.next();
}
});
resource = new QosResource(qosClientConfigLoader, OneReturningClientLimitMultiplier.create()); |
<<<<<<<
import com.palantir.atlasdb.keyvalue.impl.TableMappingNotFoundException;
=======
import com.palantir.atlasdb.keyvalue.dbkvs.impl.TableSizeCache;
>>>>>>>
import com.palantir.atlasdb.keyvalue.dbkvs.impl.TableSizeCache;
import com.palantir.atlasdb.keyvalue.impl.TableMappingNotFoundException; |
<<<<<<<
KeyValueService kvs = getKeyValueService(atlasFactory, lockAndTimestampServices);
=======
KeyValueService kvs = NamespacedKeyValueServices.wrapWithStaticNamespaceMappingKvs(rawKvs);
kvs = ProfilingKeyValueService.create(kvs);
kvs = TracingKeyValueService.create(kvs);
kvs = ValidatingQueryRewritingKeyValueService.create(kvs);
kvs = SweepStatsKeyValueService.create(kvs, lts.time());
>>>>>>>
KeyValueService kvs = getKeyValueService(atlasFactory, lockAndTimestampServices);
kvs = TracingKeyValueService.create(kvs);
kvs = ValidatingQueryRewritingKeyValueService.create(kvs); |
<<<<<<<
public void setupEditor(GUIEditorGrid editor, MapUIController controller) {
super.setupEditor(editor, controller);
addColorEditor(editor);
}
@Override
public TextureTreeNode getNode(TextureMap map) {
return getTreeNode(map);
}
@Override
public void makeTexture(BufferedImage image, Graphics2D graphics) {
=======
public BufferedImage makeTexture(TextureMap map) {
>>>>>>>
public void setupEditor(GUIEditorGrid editor, MapUIController controller) {
super.setupEditor(editor, controller);
addColorEditor(editor);
}
@Override
public BufferedImage makeTexture(TextureMap map) { |
<<<<<<<
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.google.common.collect.Maps;
import com.mongodb.MongoClientURI;
=======
>>>>>>>
<<<<<<<
=======
import com.google.common.collect.Maps;
import com.mongodb.MongoClientURI;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
>>>>>>>
import com.google.common.collect.Maps;
import com.mongodb.MongoClientURI;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
<<<<<<<
=======
private boolean silent = false;
private final boolean httpsListener;
private final int httpsPort;
private final String httpsHost;
private final boolean httpListener;
private final int httpPort;
private final String httpHost;
private final boolean ajpListener;
private final int ajpPort;
private final String ajpHost;
private final String instanceName;
private final RequestContext.REPRESENTATION_FORMAT defaultRepresentationFromat;
private final boolean useEmbeddedKeystore;
private final String keystoreFile;
private final String keystorePassword;
private final String certPassword;
private final MongoClientURI mongoUri;
private final List<Map<String, Object>> mongoMounts;
private final List<Map<String, Object>> staticResourcesMounts;
private final List<Map<String, Object>> applicationLogicMounts;
private final List<Map<String, Object>> metadataNamedSingletons;
private final String idmImpl;
private final Map<String, Object> idmArgs;
private final String authMechanismImpl;
private final Map<String, Object> authMechanismArgs;
private final String amImpl;
private final Map<String, Object> amArgs;
private final String logFilePath;
private final Level logLevel;
private final boolean logToConsole;
private final boolean logToFile;
private final boolean localCacheEnabled;
private final long localCacheTtl;
private final boolean schemaCacheEnabled;
private final long schemaCacheTtl;
private final int requestsLimit;
private final int ioThreads;
private final int workerThreads;
private final int bufferSize;
private final int buffersPerRegion;
private final boolean directBuffers;
private final boolean forceGzipEncoding;
private final int eagerPoolSize;
private final int eagerLinearSliceWidht;
private final int eagerLinearSliceDelta;
private final int[] eagerLinearSliceHeights;
private final int eagerRndSliceMinWidht;
private final int eagerRndMaxCursors;
private final boolean authTokenEnabled;
private final int authTokenTtl;
private final ETAG_CHECK_POLICY dbEtagCheckPolicy;
private final ETAG_CHECK_POLICY collEtagCheckPolicy;
private final ETAG_CHECK_POLICY docEtagCheckPolicy;
private final Map<String, Object> connectionOptions;
private final Integer logExchangeDump;
>>>>>>>
private boolean silent = false;
private final boolean httpsListener;
private final int httpsPort;
private final String httpsHost;
private final boolean httpListener;
private final int httpPort;
private final String httpHost;
private final boolean ajpListener;
private final int ajpPort;
private final String ajpHost;
private final String instanceName;
private final RequestContext.REPRESENTATION_FORMAT defaultRepresentationFromat;
private final boolean useEmbeddedKeystore;
private final String keystoreFile;
private final String keystorePassword;
private final String certPassword;
private final MongoClientURI mongoUri;
private final List<Map<String, Object>> mongoMounts;
private final List<Map<String, Object>> staticResourcesMounts;
private final List<Map<String, Object>> applicationLogicMounts;
private final List<Map<String, Object>> metadataNamedSingletons;
private final String idmImpl;
private final Map<String, Object> idmArgs;
private final String authMechanismImpl;
private final Map<String, Object> authMechanismArgs;
private final String amImpl;
private final Map<String, Object> amArgs;
private final String logFilePath;
private final Level logLevel;
private final boolean logToConsole;
private final boolean logToFile;
private final boolean localCacheEnabled;
private final long localCacheTtl;
private final boolean schemaCacheEnabled;
private final long schemaCacheTtl;
private final int requestsLimit;
private final int ioThreads;
private final int workerThreads;
private final int bufferSize;
private final int buffersPerRegion;
private final boolean directBuffers;
private final boolean forceGzipEncoding;
private final int eagerPoolSize;
private final int eagerLinearSliceWidht;
private final int eagerLinearSliceDelta;
private final int[] eagerLinearSliceHeights;
private final int eagerRndSliceMinWidht;
private final int eagerRndMaxCursors;
private final boolean authTokenEnabled;
private final int authTokenTtl;
private final ETAG_CHECK_POLICY dbEtagCheckPolicy;
private final ETAG_CHECK_POLICY collEtagCheckPolicy;
private final ETAG_CHECK_POLICY docEtagCheckPolicy;
private final Map<String, Object> connectionOptions;
private final Integer logExchangeDump;
private final long queryTimeLimit;
private final long aggregationTimeLimit; |
<<<<<<<
=======
private static final Logger LOGGER = LoggerFactory.getLogger(PutDocumentHandler.class);
private final DocumentDAO documentDAO;
>>>>>>>
private final DocumentDAO documentDAO; |
<<<<<<<
=======
public static String getReferenceLink(
RequestContext context,
String parentUrl,
BsonValue docId) {
if (context == null || parentUrl == null) {
LOGGER.error("error creating URI, null arguments: "
+ "context = {}, parentUrl = {}, docId = {}",
context,
parentUrl,
docId);
return "";
}
String uri = "#";
if (docId == null) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_null");
} else if (docId.isString()
&& ObjectId.isValid(docId.asString().getValue())) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.asString().getValue())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.STRING.name());
} else if (docId.isString()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.asString().getValue());
} else if (docId.isObjectId()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.asObjectId().getValue().toString());
} else if (docId.isBoolean()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_" + docId.asBoolean().getValue());
} else if (docId.isInt32()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + docId.asInt32().getValue())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId.isInt64()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + docId.asInt64().getValue())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId.isDouble()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + docId.asDouble().getValue())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId.isNull()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_null");
} else if (docId instanceof BsonMaxKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_MaxKey");
} else if (docId instanceof BsonMinKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_MinKey");
} else if (docId.isDateTime()) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + docId.asDateTime().getValue())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.DATE.name());
} else {
String _id;
try {
_id = getIdString(docId);
} catch (UnsupportedDocumentIdException uie) {
_id = docId.toString();
}
context.addWarning("resource with _id: "
+ _id + " does not have an URI "
+ "since the _id is of type "
+ docId.getClass().getSimpleName());
}
return uri;
}
public static String getReferenceLink(String parentUrl, Object docId) {
if (parentUrl == null) {
LOGGER.error("error creating URI, null arguments: parentUrl = null, docId = {}", docId);
return "";
}
String uri;
if (docId == null) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_null");
} else if (docId instanceof String && ObjectId.isValid((String) docId)) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.STRING.name());
} else if (docId instanceof String || docId instanceof ObjectId) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString());
} else if (docId instanceof BsonObjectId) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(((BsonObjectId) docId).getValue().toString());
} else if (docId instanceof BsonString) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(((BsonString) docId).getValue());
} else if (docId instanceof BsonBoolean) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_" + ((BsonBoolean) docId).getValue());
} else if (docId instanceof BsonInt32) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + ((BsonNumber) docId).asInt32().getValue());
} else if (docId instanceof BsonInt64) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + ((BsonNumber) docId).asInt64().getValue());
} else if (docId instanceof BsonDouble) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + ((BsonDouble) docId).asDouble().getValue());
} else if (docId instanceof BsonNull) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_null");
} else if (docId instanceof BsonMaxKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_MaxKey");
} else if (docId instanceof BsonMinKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/_MinKey");
} else if (docId instanceof BsonDateTime) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("" + ((BsonDateTime) docId).getValue());
} else if (docId instanceof Integer) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId instanceof Long) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId instanceof Float) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId instanceof Double) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(docId.toString())
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.NUMBER.name());
} else if (docId instanceof MinKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_MinKey");
} else if (docId instanceof MaxKey) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_MaxKey");
} else if (docId instanceof Date) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat(((Date) docId).getTime() + "")
.concat("?")
.concat(DOC_ID_TYPE_QPARAM_KEY)
.concat("=")
.concat(DOC_ID_TYPE.DATE.name());
} else if (docId instanceof Boolean) {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_" + (boolean) docId);
} else {
uri = URLUtils.removeTrailingSlashes(parentUrl)
.concat("/")
.concat("_? (unsuppored _id type)");
}
return uri;
}
>>>>>>> |
<<<<<<<
=======
// scanResult is null if the plugins directory is empty
if (this.scanResult == null) {
return ret;
}
>>>>>>>
// scanResult is null if the plugins directory is empty
if (this.scanResult == null) {
return ret;
} |
<<<<<<<
import com.softinstigate.restheart.utils.FileUtils;
=======
import com.softinstigate.restheart.utils.HttpStatus;
>>>>>>>
import com.softinstigate.restheart.utils.FileUtils;
import com.softinstigate.restheart.utils.HttpStatus;
<<<<<<<
private URL url;
=======
private String url;
>>>>>>>
private String url;
<<<<<<<
private final Path CONF_FILE = new File("./etc/restheart-integrationtest.yml").toPath();
=======
private Executor httpExecutor;
private final ConcurrentHashMap<Long, Integer> threadPages = new ConcurrentHashMap<>();
>>>>>>>
private final Path CONF_FILE = new File("./etc/restheart-integrationtest.yml").toPath();
private Executor httpExecutor;
private final ConcurrentHashMap<Long, Integer> threadPages = new ConcurrentHashMap<>();
<<<<<<<
MongoDBClientSingleton.init(FileUtils.getConfiguration(CONF_FILE));
=======
MongoDBClientSingleton.init(new Configuration("./etc/restheart-integrationtest.yml"));
httpExecutor = Executor.newInstance().authPreemptive(new HttpHost("127.0.0.1", 8080, "http")).auth(new HttpHost("127.0.0.1"), id, pwd);
>>>>>>>
try {
MongoDBClientSingleton.init(FileUtils.getConfiguration(CONF_FILE, false));
} catch (ConfigurationException ex) {
System.out.println(ex.getMessage() + ", exiting...");
System.exit(-1);
}
httpExecutor = Executor.newInstance().authPreemptive(new HttpHost("127.0.0.1", 8080, "http")).auth(new HttpHost("127.0.0.1"), id, pwd); |
<<<<<<<
public static final BasicDBObject PROPS_QUERY = new BasicDBObject("_id", "_properties");
=======
>>>>>>>
public static final BasicDBObject PROPS_QUERY = new BasicDBObject("_id", "_properties");
<<<<<<<
final CollectionDAO collectionDAO = new CollectionDAO();
DBCollection propsColl = collectionDAO.getCollection(dbName, "_properties");
=======
DBCollection propscoll = collectionDAO.getCollection(dbName, "_properties");
>>>>>>>
DBCollection propscoll = collectionDAO.getCollection(dbName, "_properties");
<<<<<<<
// in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic)
DBObject old = coll.findAndModify(PROPS_QUERY, fieldsToReturn, null, false, content, false, true);
=======
// in this case we need to provide the other data using $set operator
// and this makes it a partial update (patch semantic)
DBObject old = coll.findAndModify(METADATA_QUERY, fieldsToReturn, null, false, content, false, true);
>>>>>>>
// in this case we need to provide the other data using $set operator and this makes it a partial update (patch semantic)
DBObject old = coll.findAndModify(PROPS_QUERY, fieldsToReturn, null, false, content, false, true); |
<<<<<<<
long stringBlockId = nextStringBlockId();
=======
String string = (String) value;
if ( ShortString.encode( string, record ) )
{
record.setType( PropertyType.SHORT_STRING );
return;
}
int stringBlockId = nextStringBlockId();
>>>>>>>
String string = (String) value;
if ( ShortString.encode( string, record ) )
{
record.setType( PropertyType.SHORT_STRING );
return;
}
long stringBlockId = nextStringBlockId(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.