conflict_resolution
stringlengths 27
16k
|
---|
<<<<<<<
import org.arend.source.BinarySource;
import org.arend.source.FileBinarySource;
import org.arend.source.GZIPStreamBinarySource;
import org.arend.source.Source;
import org.arend.typechecking.order.dependency.DependencyListener;
=======
import org.arend.source.*;
>>>>>>>
import org.arend.source.*;
import org.arend.typechecking.order.dependency.DependencyListener; |
<<<<<<<
import com.jetbrains.jetpad.vclang.error.Error;
import com.jetbrains.jetpad.vclang.error.ErrorReporter;
import com.jetbrains.jetpad.vclang.error.GeneralError;
=======
>>>>>>>
import com.jetbrains.jetpad.vclang.error.Error;
import com.jetbrains.jetpad.vclang.error.GeneralError;
<<<<<<<
public Void visitClassField(Abstract.ClassField def, Scope parentScope) {
=======
public Void visitClassField(Abstract.ClassField def, Boolean isStatic) {
if (myResolveListener == null) {
return null;
}
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(nsProviders, myParentScope, myContext, myNameResolver, myResolveListener);
>>>>>>>
public Void visitClassField(Abstract.ClassField def, Scope parentScope) {
<<<<<<<
public Void visitData(Abstract.DataDefinition def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myErrorReporter, myResolveListener);
=======
public Void visitData(Abstract.DataDefinition def, Boolean isStatic) {
if (myResolveListener == null) {
return null;
}
Scope scope = new DataScope(myParentScope, nsProviders.statics.forDefinition(def));
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(nsProviders, scope, myContext, myNameResolver, myResolveListener);
>>>>>>>
public Void visitData(Abstract.DataDefinition def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myResolveListener);
<<<<<<<
public Void visitConstructor(Abstract.Constructor def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myErrorReporter, myResolveListener);
=======
public Void visitConstructor(Abstract.Constructor def, Boolean isStatic) {
if (myResolveListener == null) {
return null;
}
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(nsProviders, myParentScope, myContext, myNameResolver, myResolveListener);
>>>>>>>
public Void visitConstructor(Abstract.Constructor def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myResolveListener);
<<<<<<<
public Void visitClass(Abstract.ClassDefinition def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myErrorReporter, myResolveListener);
=======
public Void visitClass(Abstract.ClassDefinition def, Boolean isStatic) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(nsProviders, myParentScope, myContext, myNameResolver, myResolveListener);
>>>>>>>
public Void visitClass(Abstract.ClassDefinition def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myResolveListener);
<<<<<<<
Namespace staticNamespace = myNsProviders.statics.forDefinition(def);
Scope staticScope = new StaticClassScope(parentScope, staticNamespace);
for (Abstract.Statement statement : def.getGlobalStatements()) {
if (statement instanceof Abstract.NamespaceCommandStatement) {
staticScope = statement.accept(this, staticScope);
}
}
=======
Namespace staticNamespace = nsProviders.statics.forDefinition(def);
Scope staticScope = new StaticClassScope(myParentScope, staticNamespace);
StatementResolveNameVisitor stVisitor = new StatementResolveNameVisitor(nsProviders, myNameResolver, staticScope, myContext, myResolveListener);
>>>>>>>
Namespace staticNamespace = myNsProviders.statics.forDefinition(def);
Scope staticScope = new StaticClassScope(parentScope, staticNamespace);
for (Abstract.Statement statement : def.getGlobalStatements()) {
if (statement instanceof Abstract.NamespaceCommandStatement) {
staticScope = statement.accept(this, staticScope);
}
}
<<<<<<<
Scope child = myNsProviders.dynamics.forClass(def);
mergeNames(staticNamespace, child);
Scope dynamicScope = new DynamicClassScope(staticScope, child);
=======
Scope dynamicScope = new DynamicClassScope(myParentScope, staticNamespace, nsProviders.dynamics.forClass(def), myResolveListener);
DefinitionResolveNameVisitor dyVisitor = new DefinitionResolveNameVisitor(nsProviders, dynamicScope, myContext, myNameResolver, myResolveListener);
>>>>>>>
Scope child = myNsProviders.dynamics.forClass(def);
mergeNames(staticNamespace, child);
Scope dynamicScope = new DynamicClassScope(staticScope, child);
<<<<<<<
public Void visitImplement(Abstract.Implementation def, Scope parentScope) {
Abstract.ClassField referable = myNameResolver.resolveClassField(def.getParent(), def.getName(), myNsProviders.dynamics, myErrorReporter, def);
=======
public Void visitImplement(Abstract.Implementation def, Boolean params) {
if (myResolveListener == null) {
return null;
}
Abstract.ClassField referable = myNameResolver.resolveClassField(def.getParent(), def.getName(), nsProviders.dynamics, myResolveListener, def);
>>>>>>>
public Void visitImplement(Abstract.Implementation def, Scope parentScope) {
Abstract.ClassField referable = myNameResolver.resolveClassField(def.getParent(), def.getName(), myNsProviders.dynamics, myResolveListener, def);
<<<<<<<
myErrorReporter.report(new WrongDefinition("Expected a class", resolvedUnderlyingClass, def));
=======
myResolveListener.report(new WrongDefinition("Expected a class", def));
>>>>>>>
myResolveListener.report(new WrongDefinition("Expected a class", resolvedUnderlyingClass, def));
<<<<<<<
myErrorReporter.report(resolvedClassifyingField != null ? new WrongDefinition("Expected a class field", resolvedClassifyingField, def) : new NotInScopeError(def, def.getClassifyingFieldName()));
=======
myResolveListener.report(resolvedClassifyingField != null ? new WrongDefinition("Expected a class field", def) : new NotInScopeError(def, def.getClassifyingFieldName()));
>>>>>>>
myResolveListener.report(resolvedClassifyingField != null ? new WrongDefinition("Expected a class field", resolvedClassifyingField, def) : new NotInScopeError(def, def.getClassifyingFieldName()));
<<<<<<<
Abstract.ClassField classField = myNameResolver.resolveClassField((Abstract.ClassDefinition) resolvedUnderlyingClass, viewField.getUnderlyingFieldName(), myNsProviders.dynamics, myErrorReporter, viewField);
=======
Abstract.ClassField classField = myNameResolver.resolveClassField((Abstract.ClassDefinition) resolvedUnderlyingClass, viewField.getUnderlyingFieldName(), nsProviders.dynamics, myResolveListener, viewField);
>>>>>>>
Abstract.ClassField classField = myNameResolver.resolveClassField((Abstract.ClassDefinition) resolvedUnderlyingClass, viewField.getUnderlyingFieldName(), myNsProviders.dynamics, myResolveListener, viewField);
<<<<<<<
public Void visitClassViewInstance(Abstract.ClassViewInstance def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myErrorReporter, myResolveListener);
=======
public Void visitClassViewInstance(Abstract.ClassViewInstance def, Boolean params) {
if (myResolveListener == null) {
return null;
}
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(nsProviders, myParentScope, myContext, myNameResolver, myResolveListener);
>>>>>>>
public Void visitClassViewInstance(Abstract.ClassViewInstance def, Scope parentScope) {
ExpressionResolveNameVisitor exprVisitor = new ExpressionResolveNameVisitor(myNsProviders, parentScope, myContext, myNameResolver, myResolveListener); |
<<<<<<<
myVisitor.getErrorReporter().report(new TypeMismatchError(text("A pi type"), termDoc(result1.type), fun));
=======
if (!result1.type.isInstance(ErrorExpression.class)) {
LocalTypeCheckingError error = new TypeMismatchError(text("A pi type"), termDoc(result1.type), fun);
fun.setWellTyped(myVisitor.getContext(), new ErrorExpression(result1.expression, error));
myVisitor.getErrorReporter().report(error);
}
>>>>>>>
if (!result1.type.isInstance(ErrorExpression.class)) {
myVisitor.getErrorReporter().report(new TypeMismatchError(text("A pi type"), termDoc(result1.type), fun));
}
<<<<<<<
myVisitor.getErrorReporter().report(new TypeMismatchError(typeDoc(expectedType), termDoc(result.toResult(myVisitor.getEquations()).type), expr));
=======
CheckTypeVisitor.Result result1 = result.toResult(myVisitor.getEquations());
if (!result1.type.isInstance(ErrorExpression.class)) {
LocalTypeCheckingError error = new TypeMismatchError(typeDoc(expectedType), termDoc(result1.type), expr);
expr.setWellTyped(myVisitor.getContext(), new ErrorExpression(result1.expression, error));
myVisitor.getErrorReporter().report(error);
}
>>>>>>>
CheckTypeVisitor.Result result1 = result.toResult(myVisitor.getEquations());
if (!result1.type.isInstance(ErrorExpression.class)) {
myVisitor.getErrorReporter().report(new TypeMismatchError(typeDoc(expectedType), termDoc(result1.type), expr));
} |
<<<<<<<
public static Sort generateUpperBound(Sort domSort, Sort codSort, Equations equations, Concrete.SourceNode sourceNode) {
if ((domSort.getPLevel().getVar() == null || codSort.getPLevel().getVar() == null || domSort.getPLevel().getVar() == codSort.getPLevel().getVar())) {
=======
public static Sort generateUpperBound(Sort domSort, Sort codSort, Equations equations, Abstract.SourceNode sourceNode) {
if (domSort.getPLevel().getVar() == null || codSort.getPLevel().getVar() == null || domSort.getPLevel().getVar() == codSort.getPLevel().getVar()) {
>>>>>>>
public static Sort generateUpperBound(Sort domSort, Sort codSort, Equations equations, Concrete.SourceNode sourceNode) {
if (domSort.getPLevel().getVar() == null || codSort.getPLevel().getVar() == null || domSort.getPLevel().getVar() == codSort.getPLevel().getVar()) { |
<<<<<<<
private CheckTypeVisitor.TResult makeResult(Definition definition, Expression thisExpr, Concrete.ReferenceExpression expr) {
Sort sortArgument = definition instanceof DataDefinition && !definition.getParameters().hasNext() ? Sort.PROP : Sort.generateInferVars(myVisitor.getEquations(), expr);
=======
private CheckTypeVisitor.TResult makeResult(Definition definition, Expression thisExpr, Abstract.ReferenceExpression expr) {
Sort sortArgument;
if (definition instanceof DataDefinition && !definition.getParameters().hasNext()) {
sortArgument = Sort.PROP;
} else {
if (expr.getPLevel() == null && expr.getHLevel() == null) {
sortArgument = Sort.generateInferVars(myVisitor.getEquations(), expr);
} else {
Level pLevel = null;
if (expr.getPLevel() != null) {
pLevel = expr.getPLevel().accept(myVisitor, LevelVariable.PVAR);
}
if (pLevel == null) {
InferenceLevelVariable pl = new InferenceLevelVariable(LevelVariable.LvlType.PLVL, expr.getPLevel());
myVisitor.getEquations().addVariable(pl);
pLevel = new Level(pl);
}
Level hLevel = null;
if (expr.getHLevel() != null) {
hLevel = expr.getHLevel().accept(myVisitor, LevelVariable.HVAR);
}
if (hLevel == null) {
InferenceLevelVariable hl = new InferenceLevelVariable(LevelVariable.LvlType.HLVL, expr.getHLevel());
myVisitor.getEquations().addVariable(hl);
hLevel = new Level(hl);
}
sortArgument = new Sort(pLevel, hLevel);
}
}
>>>>>>>
private CheckTypeVisitor.TResult makeResult(Definition definition, Expression thisExpr, Concrete.ReferenceExpression expr) {
Sort sortArgument;
if (definition instanceof DataDefinition && !definition.getParameters().hasNext()) {
sortArgument = Sort.PROP;
} else {
if (expr.getPLevel() == null && expr.getHLevel() == null) {
sortArgument = Sort.generateInferVars(myVisitor.getEquations(), expr);
} else {
Level pLevel = null;
if (expr.getPLevel() != null) {
pLevel = expr.getPLevel().accept(myVisitor, LevelVariable.PVAR);
}
if (pLevel == null) {
InferenceLevelVariable pl = new InferenceLevelVariable(LevelVariable.LvlType.PLVL, expr.getPLevel());
myVisitor.getEquations().addVariable(pl);
pLevel = new Level(pl);
}
Level hLevel = null;
if (expr.getHLevel() != null) {
hLevel = expr.getHLevel().accept(myVisitor, LevelVariable.HVAR);
}
if (hLevel == null) {
InferenceLevelVariable hl = new InferenceLevelVariable(LevelVariable.LvlType.HLVL, expr.getHLevel());
myVisitor.getEquations().addVariable(hl);
hLevel = new Level(hl);
}
sortArgument = new Sort(pLevel, hLevel);
}
} |
<<<<<<<
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(perm != null, "perm is null");
return execute(new ClientExecReturn<Boolean,ClientService.Client>() {
@Override
public Boolean execute(ClientService.Client client) throws Exception {
return client.hasTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, perm.getId());
}
});
=======
ArgumentChecker.notNull(principal, table, perm);
try {
return execute(new ClientExecReturn<Boolean,ClientService.Client>() {
@Override
public Boolean execute(ClientService.Client client) throws Exception {
return client.hasTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, perm.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
}
>>>>>>>
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(perm != null, "perm is null");
try {
return execute(new ClientExecReturn<Boolean,ClientService.Client>() {
@Override
public Boolean execute(ClientService.Client client) throws Exception {
return client.hasTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, perm.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
}
<<<<<<<
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(permission != null, "permission is null");
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.grantTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
=======
ArgumentChecker.notNull(principal, table, permission);
try {
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.grantTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
}
>>>>>>>
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(permission != null, "permission is null");
try {
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.grantTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
}
<<<<<<<
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(permission != null, "permission is null");
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.revokeTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
=======
ArgumentChecker.notNull(principal, table, permission);
try {
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.revokeTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
}
>>>>>>>
checkArgument(principal != null, "principal is null");
checkArgument(table != null, "table is null");
checkArgument(permission != null, "permission is null");
try {
execute(new ClientExec<ClientService.Client>() {
@Override
public void execute(ClientService.Client client) throws Exception {
client.revokeTablePermission(Tracer.traceInfo(), credentials.toThrift(instance), principal, table, permission.getId());
}
});
} catch (AccumuloSecurityException e) {
if (e.getSecurityErrorCode() == org.apache.accumulo.core.client.security.SecurityErrorCode.NAMESPACE_DOESNT_EXIST)
throw new AccumuloSecurityException(null, SecurityErrorCode.TABLE_DOESNT_EXIST, e);
else
throw e;
} |
<<<<<<<
import com.jetbrains.jetpad.vclang.typechecking.error.ArgInferenceError;
import com.jetbrains.jetpad.vclang.typechecking.error.NotInScopeError;
import com.jetbrains.jetpad.vclang.typechecking.error.TypeCheckingError;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.CompositeInstancePool;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.EmptyInstancePool;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.LocalInstancePool;
=======
import com.jetbrains.jetpad.vclang.typechecking.error.LocalErrorReporter;
import com.jetbrains.jetpad.vclang.typechecking.error.local.ArgInferenceError;
import com.jetbrains.jetpad.vclang.typechecking.error.local.LocalTypeCheckingError;
import com.jetbrains.jetpad.vclang.typechecking.error.local.NotInScopeError;
>>>>>>>
import com.jetbrains.jetpad.vclang.typechecking.error.LocalErrorReporter;
import com.jetbrains.jetpad.vclang.typechecking.error.local.ArgInferenceError;
import com.jetbrains.jetpad.vclang.typechecking.error.local.LocalTypeCheckingError;
import com.jetbrains.jetpad.vclang.typechecking.error.local.NotInScopeError;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.CompositeInstancePool;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.EmptyInstancePool;
import com.jetbrains.jetpad.vclang.typechecking.typeclass.LocalInstancePool;
<<<<<<<
public void visitParameters(List<? extends Abstract.Argument> arguments, Abstract.SourceNode node, List<Binding> context, List<Binding> polyParamsList, LinkList list, CheckTypeVisitor visitor, LocalInstancePool localInstancePool) {
=======
@Override
public FunctionDefinition visitFunction(final Abstract.FunctionDefinition def, ClassDefinition enclosingClass) {
Abstract.Definition.Arrow arrow = def.getArrow();
final FunctionDefinition typedDef = new FunctionDefinition(def, STATIC_NS_SNAPSHOT_PROVIDER.forDefinition(def));
myState.record(def, typedDef);
// TODO[scopes] Fill namespace
List<? extends Abstract.Argument> arguments = def.getArguments();
final List<Binding> context = new ArrayList<>();
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).build();
LinkList list = new LinkList();
if (enclosingClass != null) {
DependentLink thisParam = createThisParam(enclosingClass);
context.add(thisParam);
list.append(thisParam);
visitor.setThisClass(enclosingClass, Reference(thisParam));
typedDef.setThisClass(enclosingClass);
}
List<Binding> polyParamsList = new ArrayList<>();
>>>>>>>
public void visitParameters(List<? extends Abstract.Argument> arguments, Abstract.SourceNode node, List<Binding> context, List<Binding> polyParamsList, LinkList list, CheckTypeVisitor visitor, LocalInstancePool localInstancePool) {
<<<<<<<
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).instancePool(EmptyInstancePool.INSTANCE).build(def);
=======
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).build();
>>>>>>>
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).instancePool(EmptyInstancePool.INSTANCE).build();
<<<<<<<
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).instancePool(EmptyInstancePool.INSTANCE).thisClass(enclosingClass, Reference(thisParameter)).build(def);
=======
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).thisClass(enclosingClass, Reference(thisParameter)).build();
>>>>>>>
CheckTypeVisitor visitor = new CheckTypeVisitor.Builder(myState, context, myErrorReporter).instancePool(EmptyInstancePool.INSTANCE).thisClass(enclosingClass, Reference(thisParameter)).build(); |
<<<<<<<
public abstract TypeCheckingError getErrorInfer(Expression... candidates);
=======
public abstract Abstract.SourceNode getSourceNode();
public abstract LocalTypeCheckingError getErrorInfer(Expression... candidates);
>>>>>>>
public abstract LocalTypeCheckingError getErrorInfer(Expression... candidates); |
<<<<<<<
import com.jetbrains.jetpad.vclang.term.pattern.elimtree.BranchElimTreeNode;
=======
>>>>>>>
import com.jetbrains.jetpad.vclang.term.pattern.elimtree.BranchElimTreeNode;
<<<<<<<
Expression expr1 = Apps(ConCall(bdSnoc, Nat()), ConCall(bdNil, Nat()));
assertEquals(Lam(lamArgs(Tele(vars("y"), Nat())), Apps(ConCall(bdCons, Nat()), Index(0), ConCall(bdNil, Nat()))), expr1.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testFuncNorm() {
Expression expr1 = Apps(FunCall(Prelude.PATH_INFIX), Nat(), Zero());
assertEquals(
Lam(lamArgs(Tele(vars("a'"), Nat())), Apps(FunCall(Prelude.PATH_INFIX), Nat(), Zero(), Index(0))).normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()),
expr1.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>())
);
}
@Test
public void testIsoleft() {
Expression expr = Apps(FunCall(Prelude.ISO), Index(0), Index(1), Index(2), Index(3), Index(4), Index(5), ConCall(Prelude.LEFT));
assertEquals(Index(0), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testIsoRight() {
Expression expr = Apps(FunCall(Prelude.ISO), Index(0), Index(1), Index(2), Index(3), Index(4), Index(5), ConCall(Prelude.RIGHT));
assertEquals(Index(1), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testCoeIso() {
Expression expr = Apps(FunCall(Prelude.COERCE), Lam("k", Apps(FunCall(Prelude.ISO), Index(1), Index(2), Index(3), Index(4), Index(5), Index(6), Index(0))), Index(6), ConCall(Prelude.RIGHT));
assertEquals(Apps(Index(2), Index(6)), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testCoeIsoFreeVar() {
Expression expr = Apps(FunCall(Prelude.COERCE), Lam("k", Apps(FunCall(Prelude.ISO), Apps(DataCall(Prelude.PATH), Lam("i", DataCall(Prelude.INTERVAL)), Index(0), Index(0)), Index(2), Index(3), Index(4), Index(5), Index(6), Index(0))), Index(6), ConCall(Prelude.RIGHT));
assertEquals(expr, expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
=======
Expression expr1 = Apps(ConCall(bdSnoc, Nat()), ConCall(bdNil));
assertEquals(Lam(teleArgs(Tele(vars("y"), Nat())), Apps(ConCall(bdCons, Nat()), Index(0), ConCall(bdNil))), expr1.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
>>>>>>>
Expression expr1 = Apps(ConCall(bdSnoc, Nat()), ConCall(bdNil, Nat()));
assertEquals(Lam(teleArgs(Tele(vars("y"), Nat())), Apps(ConCall(bdCons, Nat()), Index(0), ConCall(bdNil, Nat()))), expr1.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testFuncNorm() {
Expression expr1 = Apps(FunCall(Prelude.PATH_INFIX), Nat(), Zero());
assertEquals(
Lam(teleArgs(Tele(vars("a'"), Nat())), Apps(FunCall(Prelude.PATH_INFIX), Nat(), Zero(), Index(0))).normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()),
expr1.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>())
);
}
@Test
public void testIsoleft() {
Expression expr = Apps(FunCall(Prelude.ISO), Index(0), Index(1), Index(2), Index(3), Index(4), Index(5), ConCall(Prelude.LEFT));
assertEquals(Index(0), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testIsoRight() {
Expression expr = Apps(FunCall(Prelude.ISO), Index(0), Index(1), Index(2), Index(3), Index(4), Index(5), ConCall(Prelude.RIGHT));
assertEquals(Index(1), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testCoeIso() {
Expression expr = Apps(FunCall(Prelude.COERCE), Lam("k", Apps(FunCall(Prelude.ISO), Index(1), Index(2), Index(3), Index(4), Index(5), Index(6), Index(0))), Index(6), ConCall(Prelude.RIGHT));
assertEquals(Apps(Index(2), Index(6)), expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>()));
}
@Test
public void testCoeIsoFreeVar() {
Expression expr = Apps(FunCall(Prelude.COERCE), Lam("k", Apps(FunCall(Prelude.ISO), Apps(DataCall(Prelude.PATH), Lam("i", DataCall(Prelude.INTERVAL)), Index(0), Index(0)), Index(2), Index(3), Index(4), Index(5), Index(6), Index(0))), Index(6), ConCall(Prelude.RIGHT));
assertEquals(expr, expr.normalize(NormalizeVisitor.Mode.NF, new ArrayList<Binding>())); |
<<<<<<<
import com.jetbrains.jetpad.vclang.term.definition.BaseDefinition;
=======
import com.jetbrains.jetpad.vclang.term.definition.Referable;
import com.jetbrains.jetpad.vclang.term.definition.Universe;
>>>>>>>
import com.jetbrains.jetpad.vclang.term.definition.Referable; |
<<<<<<<
import com.jetbrains.jetpad.vclang.term.internal.FieldSet;
=======
import com.jetbrains.jetpad.vclang.term.expr.sort.Level;
import com.jetbrains.jetpad.vclang.term.expr.sort.LevelMax;
import com.jetbrains.jetpad.vclang.term.expr.sort.Sort;
import com.jetbrains.jetpad.vclang.term.expr.sort.SortMax;
import com.jetbrains.jetpad.vclang.term.expr.subst.ExprSubstitution;
import com.jetbrains.jetpad.vclang.term.expr.type.PiUniverseType;
import com.jetbrains.jetpad.vclang.term.expr.type.Type;
>>>>>>>
import com.jetbrains.jetpad.vclang.term.expr.sort.Level;
import com.jetbrains.jetpad.vclang.term.expr.sort.LevelMax;
import com.jetbrains.jetpad.vclang.term.expr.sort.Sort;
import com.jetbrains.jetpad.vclang.term.expr.sort.SortMax;
import com.jetbrains.jetpad.vclang.term.expr.subst.ExprSubstitution;
import com.jetbrains.jetpad.vclang.term.expr.type.PiUniverseType;
import com.jetbrains.jetpad.vclang.term.expr.type.Type;
import com.jetbrains.jetpad.vclang.term.internal.FieldSet; |
<<<<<<<
private static Sort typeCheckParameters(List<? extends Concrete.Parameter> parameters, LinkList list, CheckTypeVisitor visitor, LocalInstancePool localInstancePool) {
=======
private static Sort typeCheckParameters(List<? extends Abstract.Parameter> arguments, LinkList list, CheckTypeVisitor visitor, LocalInstancePool localInstancePool, Map<Integer, ClassField> classifyingFields, Sort expectedSort) {
>>>>>>>
private static Sort typeCheckParameters(List<? extends Concrete.Parameter> parameters, LinkList list, CheckTypeVisitor visitor, LocalInstancePool localInstancePool, Sort expectedSort) {
<<<<<<<
for (Concrete.Parameter parameter : parameters) {
if (parameter instanceof Concrete.TypeParameter) {
Concrete.TypeParameter typeParameter = (Concrete.TypeParameter) parameter;
Type paramResult = visitor.finalCheckType(typeParameter.getType());
=======
for (Abstract.Parameter parameter : arguments) {
if (parameter instanceof Abstract.TypeParameter) {
Abstract.TypeParameter typeParameter = (Abstract.TypeParameter) parameter;
Type paramResult = visitor.finalCheckType(typeParameter.getType(), expectedSort == null ? ExpectedType.OMEGA : new UniverseExpression(expectedSort));
>>>>>>>
for (Concrete.Parameter parameter : parameters) {
if (parameter instanceof Concrete.TypeParameter) {
Concrete.TypeParameter typeParameter = (Concrete.TypeParameter) parameter;
Type paramResult = visitor.finalCheckType(typeParameter.getType(), expectedSort == null ? ExpectedType.OMEGA : new UniverseExpression(expectedSort));
<<<<<<<
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool) != null;
=======
Map<Integer, ClassField> classifyingFields = new HashMap<>();
Abstract.FunctionDefinition def = (Abstract.FunctionDefinition) typedDef.getAbstractDefinition();
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool, classifyingFields, null) != null;
>>>>>>>
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool, null) != null;
<<<<<<<
CheckTypeVisitor.Result termResult = visitor.finalCheckExpr(((Concrete.TermFunctionBody) body).getTerm(), expectedType);
=======
CheckTypeVisitor.Result termResult = visitor.finalCheckExpr(((Abstract.TermFunctionBody) body).getTerm(), expectedType, true);
>>>>>>>
CheckTypeVisitor.Result termResult = visitor.finalCheckExpr(((Concrete.TermFunctionBody) body).getTerm(), expectedType, true);
<<<<<<<
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool) != null;
=======
Abstract.DataDefinition def = dataDefinition.getAbstractDefinition();
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool, classifyingFields, null) != null;
>>>>>>>
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, localInstancePool, null) != null;
<<<<<<<
private static Sort typeCheckConstructor(Concrete.Constructor def, Patterns patterns, DataDefinition dataDefinition, CheckTypeVisitor visitor, Set<DataDefinition> dataDefinitions) {
Constructor constructor = new Constructor(def.getReferable(), dataDefinition);
=======
private static Sort typeCheckConstructor(Abstract.Constructor def, Patterns patterns, DataDefinition dataDefinition, CheckTypeVisitor visitor, Set<DataDefinition> dataDefinitions, Sort userSort) {
Constructor constructor = new Constructor(def, dataDefinition);
>>>>>>>
private static Sort typeCheckConstructor(Concrete.Constructor def, Patterns patterns, DataDefinition dataDefinition, CheckTypeVisitor visitor, Set<DataDefinition> dataDefinitions, Sort userSort) {
Constructor constructor = new Constructor(def.getReferable(), dataDefinition);
<<<<<<<
sort = typeCheckParameters(def.getParameters(), list, visitor, null);
=======
sort = typeCheckParameters(def.getParameters(), list, visitor, null, null, userSort);
>>>>>>>
sort = typeCheckParameters(def.getParameters(), list, visitor, null, userSort);
<<<<<<<
for (Concrete.ReferenceExpression aSuperClass : def.getSuperClasses()) {
CheckTypeVisitor.Result result = visitor.finalCheckExpr(aSuperClass, null);
if (result == null) {
classOk = false;
continue;
}
=======
for (Abstract.SuperClass aSuperClass : def.getSuperClasses()) {
CheckTypeVisitor.Result result = visitor.finalCheckExpr(aSuperClass.getSuperClass(), null, false);
if (result == null) {
classOk = false;
continue;
}
>>>>>>>
for (Concrete.ReferenceExpression aSuperClass : def.getSuperClasses()) {
CheckTypeVisitor.Result result = visitor.finalCheckExpr(aSuperClass, null, false);
if (result == null) {
classOk = false;
continue;
}
<<<<<<<
TypedDependentLink thisParameter = createThisParam(typedDef);
visitor.getFreeBindings().add(thisParameter);
visitor.setThis(typedDef, thisParameter);
CheckTypeVisitor.Result result = visitor.finalCheckExpr(implementation.getImplementation(), field.getBaseType(Sort.STD).subst(field.getThisParameter(), new ReferenceExpression(thisParameter)));
typedDef.implementField(field, new ClassDefinition.Implementation(thisParameter, result != null ? result.expression : new ErrorExpression(null, null)));
if (result == null || result.expression.isInstance(ErrorExpression.class)) {
classOk = false;
=======
TypedDependentLink thisParameter = createThisParam(typedDef);
visitor.getFreeBindings().add(thisParameter);
visitor.setThis(typedDef, thisParameter);
CheckTypeVisitor.Result result = visitor.finalCheckExpr(implementation.getImplementation(), field.getBaseType(Sort.STD).subst(field.getThisParameter(), new ReferenceExpression(thisParameter)), false);
typedDef.implementField(field, new ClassDefinition.Implementation(thisParameter, result != null ? result.expression : new ErrorExpression(null, null)));
if (result == null || result.expression.isInstance(ErrorExpression.class)) {
classOk = false;
}
>>>>>>>
TypedDependentLink thisParameter = createThisParam(typedDef);
visitor.getFreeBindings().add(thisParameter);
visitor.setThis(typedDef, thisParameter);
CheckTypeVisitor.Result result = visitor.finalCheckExpr(implementation.getImplementation(), field.getBaseType(Sort.STD).subst(field.getThisParameter(), new ReferenceExpression(thisParameter)), false);
typedDef.implementField(field, new ClassDefinition.Implementation(thisParameter, result != null ? result.expression : new ErrorExpression(null, null)));
if (result == null || result.expression.isInstance(ErrorExpression.class)) {
classOk = false;
<<<<<<<
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, null) != null;
=======
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, null, null, null) != null;
>>>>>>>
boolean paramsOk = typeCheckParameters(def.getParameters(), list, visitor, null, null) != null; |
<<<<<<<
public TypeCheckingError getErrorInfer(Expression... candidates) {
=======
public Abstract.SourceNode getSourceNode() {
return myVar.getSourceNode();
}
@Override
public LocalTypeCheckingError getErrorInfer(Expression... candidates) {
>>>>>>>
public LocalTypeCheckingError getErrorInfer(Expression... candidates) { |
<<<<<<<
import com.jetbrains.jetpad.vclang.naming.DefinitionResolvedName;
import com.jetbrains.jetpad.vclang.naming.ModuleResolvedName;
import com.jetbrains.jetpad.vclang.naming.Namespace;
import com.jetbrains.jetpad.vclang.naming.NamespaceMember;
import com.jetbrains.jetpad.vclang.term.context.binding.Binding;
=======
import com.jetbrains.jetpad.vclang.naming.namespace.EmptyNamespace;
import com.jetbrains.jetpad.vclang.naming.namespace.SimpleNamespace;
>>>>>>>
import com.jetbrains.jetpad.vclang.naming.namespace.EmptyNamespace;
import com.jetbrains.jetpad.vclang.naming.namespace.SimpleNamespace;
import com.jetbrains.jetpad.vclang.term.context.binding.Binding;
<<<<<<<
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
=======
>>>>>>>
import java.util.ArrayList;
import java.util.List;
<<<<<<<
Data(Namespace parentNs, String name, Abstract.Binding.Precedence precedence, TypeUniverse universe, DependentLink parameters, List<Binding> polyParams) {
=======
Data(SimpleNamespace parentNs, String name, Abstract.Binding.Precedence precedence, TypeUniverse universe, DependentLink parameters) {
>>>>>>>
Data(SimpleNamespace parentNs, String name, Abstract.Binding.Precedence precedence, TypeUniverse universe, DependentLink parameters, List<Binding> polyParams) {
<<<<<<<
public Function(Namespace parentNs, String name, Abstract.Binding.Precedence precedence, DependentLink parameters, Expression resultType, ElimTreeNode elimTree, List<Binding> polyParams) {
myResolvedName = new DefinitionResolvedName(parentNs, name);
TypeUniverse universe = resultType.toUniverse() != null ? resultType.toUniverse().getUniverse() : resultType.getType().toUniverse().getUniverse();
myDefinition = new FunctionDefinition(myResolvedName, precedence, parameters, resultType, elimTree, universe);
myDefinition.setPolyParams(polyParams);
=======
public Function(SimpleNamespace parentNs, String name, Abstract.Binding.Precedence precedence, DependentLink parameters, Expression resultType, ElimTreeNode elimTree) {
myDefinition = new FunctionDefinition(name, precedence, EmptyNamespace.INSTANCE, parameters, resultType, elimTree);
>>>>>>>
public Function(SimpleNamespace parentNs, String name, Abstract.Binding.Precedence precedence, DependentLink parameters, Expression resultType, ElimTreeNode elimTree, List<Binding> polyParams) {
myDefinition = new FunctionDefinition(name, precedence, EmptyNamespace.INSTANCE, parameters, resultType, elimTree);
myDefinition.setUniverse(resultType.toUniverse() != null ? resultType.toUniverse().getUniverse() : resultType.getType().toUniverse().getUniverse());
myDefinition.setPolyParams(polyParams); |
<<<<<<<
String name = ctx.name(i) instanceof NameBinOpContext ? ((NameBinOpContext) ctx.name(i)).BIN_OP().getText() : ((NameIdContext) ctx.name(i)).ID().getText();
Definition definition = module.getStaticField(name);
=======
String name = getName(ctx.name(i));
Definition definition = module.findChild(name);
>>>>>>>
String name = ctx.name(i) instanceof NameBinOpContext ? ((NameBinOpContext) ctx.name(i)).BIN_OP().getText() : ((NameIdContext) ctx.name(i)).ID().getText();
Definition definition = module.getStaticField(name);
<<<<<<<
private FunctionDefinition visitDefFunction(boolean overridden, PrecedenceContext precCtx, NameContext nameCtx, List<TeleContext> teleCtx, ExprContext typeCtx, ArrowContext arrowCtx, ExprContext termCtx) {
Concrete.FunctionDefinition def = visitFunctionRawBegin(overridden, precCtx, nameCtx, teleCtx, typeCtx, arrowCtx);
if (def == null) {
return null;
}
List<Binding> localContext = new ArrayList<>();
FunctionDefinition typedDef = TypeChecking.typeCheckFunctionBegin(myModuleLoader, myParent, def, localContext, null);
if (typedDef != null) {
TypeChecking.typeCheckFunctionEnd(myModuleLoader, myParent, termCtx == null ? null : visitExpr(termCtx), typedDef, localContext, null, myOnlyStatics);
}
visitFunctionRawEnd(def);
return typedDef;
}
private Concrete.FunctionDefinition visitFunctionRawBegin(boolean overridden, PrecedenceContext precCtx, NameContext nameCtx, List<TeleContext> teleCtx, ExprContext typeCtx, ArrowContext arrowCtx) {
Name name = getName(nameCtx);
int size = myContext.size();
List<Concrete.Argument> arguments = new ArrayList<>();
for (TeleContext tele : teleCtx) {
List<Concrete.Argument> args = visitLamTele(tele);
if (args == null) {
trimToSize(myContext, size);
return null;
}
=======
private ModuleLoader.TypeCheckingUnit visitDefFunction(boolean overridden, PrecedenceContext precCtx, NameContext nameCtx, List<TeleContext> teleCtx, ExprContext typeCtx, ArrowContext arrowCtx, ExprContext termCtx) {
final String name = getName(nameCtx);
final Concrete.Position position = getNamePosition(nameCtx);
>>>>>>>
private FunctionDefinition visitDefFunction(boolean overridden, PrecedenceContext precCtx, NameContext nameCtx, List<TeleContext> teleCtx, ExprContext typeCtx, ArrowContext arrowCtx, ExprContext termCtx) {
Concrete.FunctionDefinition def = visitFunctionRawBegin(overridden, precCtx, nameCtx, teleCtx, typeCtx, arrowCtx);
if (def == null) {
return null;
}
List<Binding> localContext = new ArrayList<>();
FunctionDefinition typedDef = TypeChecking.typeCheckFunctionBegin(myModuleLoader, myParent, def, localContext, null);
if (typedDef != null) {
TypeChecking.typeCheckFunctionEnd(myModuleLoader, myParent, termCtx == null ? null : visitExpr(termCtx), typedDef, localContext, null, myOnlyStatics);
}
visitFunctionRawEnd(def);
return typedDef;
}
private Concrete.FunctionDefinition visitFunctionRawBegin(boolean overridden, PrecedenceContext precCtx, NameContext nameCtx, List<TeleContext> teleCtx, ExprContext typeCtx, ArrowContext arrowCtx) {
Name name = getName(nameCtx);
<<<<<<<
Definition.Arrow arrow = arrowCtx instanceof ArrowLeftContext ? Abstract.Definition.Arrow.LEFT : arrowCtx instanceof ArrowRightContext ? Abstract.Definition.Arrow.RIGHT : null;
return new Concrete.FunctionDefinition(name.position, name.name, precCtx == null ? null : visitPrecedence(precCtx), name.fixity, arguments, type, arrow, null, overridden);
}
=======
Definition.Arrow arrow = getArrow(arrowCtx);
Abstract.Definition.Precedence precedence = precCtx == null ? null : visitPrecedence(precCtx);
Abstract.Definition.Fixity fixity = getNameFixity(nameCtx);
Concrete.FunctionDefinition def = new Concrete.FunctionDefinition(position, name, precedence, fixity, new ArrayList<>(arguments), type, arrow, null, overridden);
>>>>>>>
Definition.Arrow arrow = arrowCtx instanceof ArrowLeftContext ? Abstract.Definition.Arrow.LEFT : arrowCtx instanceof ArrowRightContext ? Abstract.Definition.Arrow.RIGHT : null;
return new Concrete.FunctionDefinition(name.position, name.name, precCtx == null ? null : visitPrecedence(precCtx), name.fixity, arguments, type, arrow, null, overridden);
}
<<<<<<<
Name name = getName(ctx.name());
=======
boolean isPrefix = ctx.name() instanceof NameIdContext;
final String name = getName(ctx.name());
final Concrete.Position position = getNamePosition(ctx.name());
>>>>>>>
Name name = getName(ctx.name());
<<<<<<<
Name conName = getName(ctx.constructor(i).name());
=======
isPrefix = ctx.constructor(i).name() instanceof NameIdContext;
final String constructorName = getName(ctx.constructor(i).name());
final Concrete.Position constructorPosition = getNamePosition(ctx.constructor(i).name());
>>>>>>>
Name conName = getName(ctx.constructor(i).name());
<<<<<<<
Concrete.Constructor con = new Concrete.Constructor(conName.position, conName.name, visitPrecedence(ctx.constructor(i).precedence()), conName.fixity, new Universe.Type(), arguments, def);
if (TypeChecking.typeCheckConstructor(myModuleLoader, typedDef, con, localContext, index) != null) {
++index;
}
=======
Concrete.Constructor concreteConstructor = new Concrete.Constructor(constructorPosition, constructorName, visitPrecedence(ctx.constructor(i).precedence()), isPrefix ? Definition.Fixity.PREFIX : Definition.Fixity.INFIX, new Universe.Type(), arguments, def);
Constructor typedConstructor = (Constructor) getDefinition(concreteConstructor.getName(), concreteConstructor.getPosition(), new Constructor(i, concreteConstructor.getName(), typedDef, concreteConstructor.getPrecedence(), concreteConstructor.getFixity()));
if (typedConstructor == null) continue;
constructors.add(concreteConstructor);
typedDef.getConstructors().add(typedConstructor);
>>>>>>>
Concrete.Constructor con = new Concrete.Constructor(conName.position, conName.name, visitPrecedence(ctx.constructor(i).precedence()), conName.fixity, new Universe.Type(), arguments, def);
if (TypeChecking.typeCheckConstructor(myModuleLoader, typedDef, con, localContext, index) != null) {
++index;
}
<<<<<<<
return getName(ctx.name());
=======
return getName(ctx.name());
}
private static String getName(NameContext ctx) {
boolean isPrefix = ctx instanceof NameIdContext;
return isPrefix ? ((NameIdContext) ctx).ID().getText() : ((NameBinOpContext) ctx).BIN_OP().getText();
}
private static Concrete.Position getNamePosition(NameContext ctx) {
boolean isPrefix = ctx instanceof NameIdContext;
return tokenPosition(isPrefix ? ((NameIdContext) ctx).ID().getSymbol() : ((NameBinOpContext) ctx).BIN_OP().getSymbol());
}
private static Abstract.Definition.Fixity getNameFixity(NameContext ctx) {
boolean isPrefix = ctx instanceof NameIdContext;
return isPrefix ? Definition.Fixity.PREFIX : Definition.Fixity.INFIX;
}
@Override
public Concrete.LetClause visitLetClause(LetClauseContext ctx) {
final int oldContextSize = myContext.size();
final String name = ctx.ID().getText();
final List<Concrete.Argument> arguments = visitFunctionArguments(ctx.tele());
if (arguments == null) {
trimToSize(myContext, oldContextSize);
return null;
}
final Concrete.Expression resultType = ctx.typeAnnotation() == null ? null: visitExpr(ctx.typeAnnotation().expr());
final Abstract.Definition.Arrow arrow = getArrow(ctx.arrow());
final Concrete.Expression term = visitExpr(ctx.expr());
trimToSize(myContext, oldContextSize);
myContext.add(name);
return new Concrete.LetClause(tokenPosition(ctx.getStart()), name, new ArrayList<>(arguments), resultType, arrow, term);
}
@Override
public Concrete.LetExpression visitLet(LetContext ctx) {
final int oldContextSize = myContext.size();
final List<Concrete.LetClause> clauses = new ArrayList<>();
for (LetClauseContext clauseCtx : ctx.letClause()) {
clauses.add(visitLetClause(clauseCtx));
}
final Concrete.Expression expr = visitExpr(ctx.expr());
trimToSize(myContext, oldContextSize);
return new Concrete.LetExpression(tokenPosition(ctx.getStart()), clauses, expr);
>>>>>>>
return getName(ctx.name());
}
@Override
public Concrete.LetClause visitLetClause(LetClauseContext ctx) {
final int oldContextSize = myContext.size();
final String name = ctx.ID().getText();
final List<Concrete.Argument> arguments = visitFunctionArguments(ctx.tele());
if (arguments == null) {
trimToSize(myContext, oldContextSize);
return null;
}
final Concrete.Expression resultType = ctx.typeAnnotation() == null ? null: visitExpr(ctx.typeAnnotation().expr());
final Abstract.Definition.Arrow arrow = getArrow(ctx.arrow());
final Concrete.Expression term = visitExpr(ctx.expr());
trimToSize(myContext, oldContextSize);
myContext.add(name);
return new Concrete.LetClause(tokenPosition(ctx.getStart()), name, new ArrayList<>(arguments), resultType, arrow, term);
}
@Override
public Concrete.LetExpression visitLet(LetContext ctx) {
final int oldContextSize = myContext.size();
final List<Concrete.LetClause> clauses = new ArrayList<>();
for (LetClauseContext clauseCtx : ctx.letClause()) {
clauses.add(visitLetClause(clauseCtx));
}
final Concrete.Expression expr = visitExpr(ctx.expr());
trimToSize(myContext, oldContextSize);
return new Concrete.LetExpression(tokenPosition(ctx.getStart()), clauses, expr); |
<<<<<<<
public void declare(@NotNull ModulePath module, @NotNull LongName longName, @NotNull String description, @NotNull Precedence precedence, @NotNull MetaDefinition meta) {
declare(module, longName, description, precedence, null, null, meta);
}
@Override
public void declare(@NotNull ModulePath module, @NotNull LongName longName, @NotNull String description, @NotNull Precedence precedence, @Nullable String alias, @Nullable Precedence aliasPrecedence, @NotNull MetaDefinition meta) {
=======
public MetaRef declare(@NotNull ModulePath module, @NotNull LongName longName, @NotNull String description, @NotNull Precedence precedence, @Nullable MetaDefinition meta) {
>>>>>>>
public MetaRef declare(@NotNull ModulePath module, @NotNull LongName longName, @NotNull String description, @NotNull Precedence precedence, @Nullable MetaDefinition meta) {
return declare(module, longName, description, precedence, null, null, meta);
}
@Override
public MetaRef declare(@NotNull ModulePath module, @NotNull LongName longName, @NotNull String description, @NotNull Precedence precedence, @Nullable String alias, @Nullable Precedence aliasPrecedence, @Nullable MetaDefinition meta) {
<<<<<<<
scope.names.put(name, new MetaReferable(precedence, name, aliasPrecedence, alias, description, meta));
=======
MetaReferable metaRef = new MetaReferable(precedence, name, description, meta);
scope.names.put(name, metaRef);
return metaRef;
>>>>>>>
MetaReferable metaRef = new MetaReferable(precedence, name, aliasPrecedence, alias, description, meta);
scope.names.put(name, metaRef);
return metaRef; |
<<<<<<<
DataDefinition typedDef = TypeChecking.typeCheckDataBegin(myModuleLoader, myParent, def, localContext);
if (typedDef == null)
return null;
=======
DataDefinition typedDef = TypeChecking.typeCheckDataBegin(myModuleLoader, myNamespace, !isStatic ? myLocalNamespace : null, def, localContext);
>>>>>>>
DataDefinition typedDef = TypeChecking.typeCheckDataBegin(myModuleLoader, myNamespace, !isStatic ? myLocalNamespace : null, def, localContext);
if (typedDef == null)
return null;
<<<<<<<
for (int i = 0; i < def.getConstructors().size(); i++) {
TypeChecking.typeCheckConstructor(myModuleLoader, typedDef, def.getConstructors().get(i), localContext, i);
=======
List<Concrete.TypeArgument> arguments = visitTeles(ctx.constructor(i).tele());
trimToSize(myContext, size);
if (arguments == null) {
continue;
}
Concrete.Constructor con = new Concrete.Constructor(conName.position, conName, visitPrecedence(ctx.constructor(i).precedence()), new Universe.Type(), arguments, def);
if (TypeChecking.typeCheckConstructor(myModuleLoader, myNamespace, typedDef, con, localContext, index) != null) {
++index;
}
>>>>>>>
//TODO: indexing
for (int i = 0; i < def.getConstructors().size(); i++) {
TypeChecking.typeCheckConstructor(myModuleLoader, myNamespace, typedDef, def.getConstructors().get(i), localContext, i); |
<<<<<<<
int on = 0, total = 0;
for (Argument argument : arguments) {
if (argument instanceof NameArgument) {
++on;
++total;
} else
if (argument instanceof TelescopeArgument) {
liftPatterns(on);
on = ((TelescopeArgument) argument).getNames().size();
total += on;
if (!((TypeArgument) argument).getType().accept(this)) {
return false;
}
} else {
throw new IllegalStateException();
=======
try (PatternLifter lifter = new PatternLifter()) {
for (Argument argument : arguments) {
if (argument instanceof NameArgument) {
lifter.liftPatterns();
} else if (argument instanceof TelescopeArgument) {
if (!((TypeArgument) argument).getType().accept(this)) return false;
lifter.liftPatterns(((TelescopeArgument) argument).getNames().size());
} else {
throw new IllegalStateException();
}
>>>>>>>
try (PatternLifter lifter = new PatternLifter()) {
for (Argument argument : arguments) {
if (argument instanceof NameArgument) {
lifter.liftPatterns();
} else if (argument instanceof TelescopeArgument) {
if (!((TypeArgument) argument).getType().accept(this)) {
return false;
}
lifter.liftPatterns(((TelescopeArgument) argument).getNames().size());
} else {
throw new IllegalStateException();
} |
<<<<<<<
TypeCheckingTestCase.TypeCheckClassResult result = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => cons 0 nil");
testType(Apps(result.getDefinition("List").getDefCall(), Nat()), result);
=======
NamespaceMember member = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => cons 0 nil");
Expression list = Apps(DataCall((DataDefinition) member.namespace.getDefinition("List")), Nat());
assertEquals(list, member.namespace.getDefinition("test").getType());
assertEquals(list, ((LeafElimTreeNode) ((FunctionDefinition) member.namespace.getDefinition("test")).getElimTree()).getExpression().getType());
>>>>>>>
TypeCheckClassResult result = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => cons 0 nil");
testType(Apps(DataCall((DataDefinition) result.getDefinition("List")), Nat()), result);
<<<<<<<
TypeCheckingTestCase.TypeCheckClassResult result = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => (List Nat).nil");
testType(Apps(result.getDefinition("List").getDefCall(), Nat()), result);
=======
NamespaceMember member = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => (List Nat).nil");
Expression list = Apps(DataCall((DataDefinition) member.namespace.getDefinition("List")), Nat());
assertEquals(list, member.namespace.getDefinition("test").getType());
assertEquals(list, ((LeafElimTreeNode) ((FunctionDefinition) member.namespace.getDefinition("test")).getElimTree()).getExpression().getType());
>>>>>>>
TypeCheckClassResult result = typeCheckClass("\\static \\data List (A : \\Type0) | nil | cons A (List A) \\static \\function test => (List Nat).nil");
testType(Apps(DataCall((DataDefinition) result.getDefinition("List")), Nat()), result);
<<<<<<<
TypeCheckingTestCase.TypeCheckClassResult result = typeCheckClass("\\static \\class Test { \\abstract A : \\Type0 \\abstract a : A } \\static \\function test => Test { A => Nat }");
assertEquals(Universe(1), result.getDefinition("Test").getType());
assertEquals(Universe(0), result.getDefinition("test").getType());
testType(Universe(TypeUniverse.SetOfLevel(0)), result);
=======
NamespaceMember member = typeCheckClass("\\static \\class Test { \\abstract A : \\Type0 \\abstract a : A } \\static \\function test => Test { A => Nat }");
assertEquals(Universe(1), member.namespace.getDefinition("Test").getType());
assertEquals(Universe(TypeUniverse.SetOfLevel(0)), member.namespace.getDefinition("test").getType());
assertEquals(Universe(TypeUniverse.SetOfLevel(0)), ((LeafElimTreeNode) ((FunctionDefinition) member.namespace.getDefinition("test")).getElimTree()).getExpression().getType());
assertEquals(Universe(TypeUniverse.SetOfLevel(0)), ((FunctionDefinition) member.namespace.getDefinition("test")).getResultType());
>>>>>>>
TypeCheckClassResult result = typeCheckClass("\\static \\class Test { \\abstract A : \\Type0 \\abstract a : A } \\static \\function test => Test { A => Nat }");
assertEquals(Universe(1), result.getDefinition("Test").getType());
assertEquals(Universe(TypeUniverse.SetOfLevel(0)), result.getDefinition("test").getType());
testType(Universe(TypeUniverse.SetOfLevel(0)), result);
<<<<<<<
TypeCheckingTestCase.TypeCheckClassResult result = typeCheckClass("\\static \\class C { \\abstract x : Nat \\function f (p : 0 = x) => p } \\static \\function test (p : Nat -> C) => (p 0).f");
DependentLink p = param("p", Pi(Nat(), result.getDefinition("C").getDefCall()));
=======
NamespaceMember member = typeCheckClass("\\static \\class C { \\abstract x : Nat \\function f (p : 0 = x) => p } \\static \\function test (p : Nat -> C) => (p 0).f");
DependentLink p = param("p", Pi(Nat(), ClassCall((ClassDefinition) member.namespace.getDefinition("C"))));
>>>>>>>
TypeCheckClassResult result = typeCheckClass("\\static \\class C { \\abstract x : Nat \\function f (p : 0 = x) => p } \\static \\function test (p : Nat -> C) => (p 0).f");
DependentLink p = param("p", Pi(Nat(), ClassCall((ClassDefinition) result.getDefinition("C"))));
<<<<<<<
.addArgument(Apps(result.getDefinition("C.x").getDefCall(), Apps(Reference(p), Zero())), AppExpression.DEFAULT);
assertEquals(Pi(p, Pi(type, type)).normalize(NormalizeVisitor.Mode.NF), result.getDefinition("test").getType().normalize(NormalizeVisitor.Mode.NF));
=======
.addArgument(Apps(FieldCall((ClassField) member.namespace.getMember("C").namespace.getDefinition("x")), Apps(Reference(p), Zero())), AppExpression.DEFAULT);
assertEquals(Pi(p, Pi(type, type)).normalize(NormalizeVisitor.Mode.NF), member.namespace.getDefinition("test").getType().normalize(NormalizeVisitor.Mode.NF));
>>>>>>>
.addArgument(Apps(FieldCall((ClassField) result.getDefinition("C.x")), Apps(Reference(p), Zero())), AppExpression.DEFAULT);
assertEquals(Pi(p, Pi(type, type)).normalize(NormalizeVisitor.Mode.NF), result.getDefinition("test").getType().normalize(NormalizeVisitor.Mode.NF));
<<<<<<<
testType(Sigma(params(xy, param(Apps(FunCall(Prelude.PATH_INFIX).addArgument(ZeroLvl(), EnumSet.noneOf(AppExpression.Flag.class)).addArgument(Fin(Suc(Zero())), EnumSet.noneOf(AppExpression.Flag.class))
.addArgument(Nat(), EnumSet.noneOf(AppExpression.Flag.class)), Reference(xy), Reference(xy.getNext()))))), result);
=======
assertEquals(Sigma(params(xy, param(Apps(FunCall(Prelude.PATH_INFIX).addArgument(ZeroLvl(), EnumSet.noneOf(AppExpression.Flag.class))
.addArgument(Fin(Suc(Zero())), EnumSet.noneOf(AppExpression.Flag.class))
.addArgument(Nat(), EnumSet.noneOf(AppExpression.Flag.class)), Reference(xy), Reference(xy.getNext()))))),
((LeafElimTreeNode)((FunctionDefinition) def).getElimTree()).getExpression().getType());
>>>>>>>
testType(Sigma(params(xy, param(Apps(FunCall(Prelude.PATH_INFIX).addArgument(ZeroLvl(), EnumSet.noneOf(AppExpression.Flag.class))
.addArgument(Fin(Suc(Zero())), EnumSet.noneOf(AppExpression.Flag.class))
.addArgument(Nat(), EnumSet.noneOf(AppExpression.Flag.class)), Reference(xy), Reference(xy.getNext()))))),
result);
<<<<<<<
DataDefinition data = (DataDefinition) result.getDefinition("C");
assertEquals(Apps(data.getDefCall(), Zero()), data.getConstructor("c1").getType());
=======
DataDefinition data = (DataDefinition) member.namespace.getMember("C").definition;
assertEquals(Apps(DataCall(data), Zero()), data.getConstructor("c1").getType());
>>>>>>>
DataDefinition data = (DataDefinition) result.getDefinition("C");
assertEquals(Apps(DataCall(data), Zero()), data.getConstructor("c1").getType()); |
<<<<<<<
public static void visitModule(Abstract.ClassDefinition module, Scope globalScope, NameResolver nameResolver, NamespaceProviders nsProviders, ResolveListener resolveListener, ErrorReporter errorReporter) {
DefinitionResolveNameVisitor visitor = new DefinitionResolveNameVisitor(nsProviders, nameResolver, errorReporter, resolveListener);
visitor.visitClass(module, globalScope);
=======
public static void visitModule(Abstract.ClassDefinition module, Scope globalScope, NameResolver nameResolver, NamespaceProviders nsProviders, ResolveListener resolveListener) {
DefinitionResolveNameVisitor visitor = new DefinitionResolveNameVisitor(nsProviders, globalScope, nameResolver, resolveListener);
visitor.visitClass(module, null);
>>>>>>>
public static void visitModule(Abstract.ClassDefinition module, Scope globalScope, NameResolver nameResolver, NamespaceProviders nsProviders, ResolveListener resolveListener) {
DefinitionResolveNameVisitor visitor = new DefinitionResolveNameVisitor(nsProviders, nameResolver, resolveListener);
visitor.visitClass(module, globalScope); |
<<<<<<<
Type paramType = visitor.checkParamType(typeArgument.getType());
if (paramType == null) continue;
=======
Type paramType = visitor.checkTypeExpression(typeArgument.getType());
if (paramType == null) {
ok = false;
continue;
}
>>>>>>>
Type paramType = visitor.checkParamType(typeArgument.getType());
if (paramType == null) {
ok = false;
continue;
}
<<<<<<<
if (expectedType != null && termResult.getType().toSorts() != null && !termResult.getType().toSorts().isLessOrEquals(expectedType.toSorts())) {
myErrorReporter.report(new TypeMismatchError(expectedType, termResult.getType(), term));
} else {
typedDef.setElimTree(top(list.getFirst(), leaf(def.getArrow(), termResult.getExpression())));
if (expectedType == null) {
typedDef.setResultType(termResult.getType());
}
=======
typedDef.setElimTree(top(list.getFirst(), leaf(def.getArrow(), termResult.getExpression())));
if (expectedType == null) {
typedDef.setResultType(termResult.getType());
typedDef.typeHasErrors(!paramsOk);
>>>>>>>
if (expectedType != null && termResult.getType().toSorts() != null && !termResult.getType().toSorts().isLessOrEquals(expectedType.toSorts())) {
myErrorReporter.report(new TypeMismatchError(expectedType, termResult.getType(), term));
} else {
typedDef.setElimTree(top(list.getFirst(), leaf(def.getArrow(), termResult.getExpression())));
if (expectedType == null) {
typedDef.setResultType(termResult.getType());
typedDef.typeHasErrors(!paramsOk);
} |
<<<<<<<
Definition plus = result.getDefinition("+");
=======
FunctionDefinition plus = (FunctionDefinition) member.namespace.getDefinition("+");
>>>>>>>
FunctionDefinition plus = (FunctionDefinition) result.getDefinition("+");
<<<<<<<
assertEquals(leaf(Abstract.Definition.Arrow.RIGHT, Apps(plus.getDefCall(), FunCall(pFun), Apps(FunCall(qFun), Reference(hFun.getParameters())))), hFun.getElimTree());
FunctionDefinition kFun = (FunctionDefinition) result.getDefinition("A.C.k");
=======
assertEquals(leaf(Abstract.Definition.Arrow.RIGHT, Apps(FunCall(plus), FunCall(pFun), Apps(FunCall(qFun), Reference(hFun.getParameters())))), hFun.getElimTree());
FunctionDefinition kFun = (FunctionDefinition) cMember.namespace.getDefinition("k");
>>>>>>>
assertEquals(leaf(Abstract.Definition.Arrow.RIGHT, Apps(FunCall(plus), FunCall(pFun), Apps(FunCall(qFun), Reference(hFun.getParameters())))), hFun.getElimTree());
FunctionDefinition kFun = (FunctionDefinition) result.getDefinition("A.C.k"); |
<<<<<<<
if (!bindings.isEmpty() && (!myExactSolutions.isEmpty() || (!myEqSolutions.isEmpty() && !onlyPreciseSolutions))) {
do {
was = false;
InferenceBinding binding = null;
Expression subst = null;
for (Iterator<Map.Entry<InferenceBinding, ExactSolution>> it = myExactSolutions.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<InferenceBinding, ExactSolution> entry = it.next();
if (bindings.remove(entry.getKey())) {
was = true;
it.remove();
subst = entry.getValue().solve(this, entry.getKey(), result.ExprSubst);
if (subst == null) {
entry.getKey().reportErrorLevelInfer(myErrorReporter);
break;
}
if (update(entry.getKey(), subst, result.ExprSubst)) {
binding = entry.getKey();
}
break;
=======
do {
was = false;
InferenceBinding binding = null;
Expression subst = null;
// TODO: First solve variables that are not levels, then level variables
for (Iterator<Map.Entry<InferenceBinding, ExactSolution>> it = myExactSolutions.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<InferenceBinding, ExactSolution> entry = it.next();
if (bindings.contains(entry.getKey())) {
was = true;
it.remove();
subst = entry.getValue().solve(this, entry.getKey(), result);
if (update(entry.getKey(), subst, result)) {
binding = entry.getKey();
bindings.remove(binding);
>>>>>>>
if (!bindings.isEmpty() && (!myExactSolutions.isEmpty() || (!myEqSolutions.isEmpty() && !onlyPreciseSolutions))) {
do {
was = false;
InferenceBinding binding = null;
Expression subst = null;
for (Iterator<Map.Entry<InferenceBinding, ExactSolution>> it = myExactSolutions.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<InferenceBinding, ExactSolution> entry = it.next();
if (bindings.contains(entry.getKey())) {
was = true;
it.remove();
subst = entry.getValue().solve(this, entry.getKey(), result.ExprSubst);
if (subst == null) {
entry.getKey().reportErrorLevelInfer(myErrorReporter);
break;
}
if (update(entry.getKey(), subst, result.ExprSubst)) {
binding = entry.getKey();
bindings.remove(binding);
}
break; |
<<<<<<<
Abstract.Definition.Arrow getArrow();
Expression getTerm();
List<? extends Argument> getArguments();
=======
ElimTreeNode getElimTree();
List<Argument> getArguments();
>>>>>>>
ElimTreeNode getElimTree();
List<? extends Argument> getArguments(); |
<<<<<<<
import com.jetbrains.jetpad.vclang.term.context.binding.Binding;
import com.jetbrains.jetpad.vclang.term.context.binding.inference.InferenceBinding;
=======
import com.jetbrains.jetpad.vclang.term.Preprelude;
import com.jetbrains.jetpad.vclang.term.context.binding.Variable;
import com.jetbrains.jetpad.vclang.term.context.binding.inference.InferenceVariable;
>>>>>>>
import com.jetbrains.jetpad.vclang.term.context.binding.Variable;
import com.jetbrains.jetpad.vclang.term.context.binding.inference.InferenceVariable; |
<<<<<<<
assertEquals(1, domArguments.get(1).getArguments().size());
assertEquals(Reference(testFun.getParameters()), domArguments.get(1).getArguments().get(0));
assertEquals(member.namespace.findChild("A").getDefinition("x").getDefCall(), domArguments.get(1).getFunction());
=======
assertEquals(1, domArguments.get(3).getArguments().size());
assertEquals(Reference(testFun.getParameters()), domArguments.get(3).getArguments().get(0));
assertEquals(FieldCall((ClassField) result.getDefinition("A.x")), domArguments.get(3).getFunction());
>>>>>>>
assertEquals(1, domArguments.get(1).getArguments().size());
assertEquals(Reference(testFun.getParameters()), domArguments.get(1).getArguments().get(0));
assertEquals(FieldCall((ClassField) result.getDefinition("A.x")), domArguments.get(1).getFunction());
<<<<<<<
assertEquals(Prelude.PATH_CON, parameterFunction.toDefCall().getPolyDefinition());
=======
assertNotNull(parameterFunction.toConCall());
assertTrue(Prelude.isPathCon(parameterFunction.toConCall().getDefinition()));
>>>>>>>
assertEquals(Prelude.PATH_CON, parameterFunction.toDefCall().getPolyDefinition());
<<<<<<<
List<Expression> parameters = paramConCall.getDataTypeArguments();
assertEquals(3, parameters.size());
=======
List<? extends Expression> parameters = paramConCall.getDataTypeArguments();
assertEquals(5, parameters.size());
>>>>>>>
List<? extends Expression> parameters = paramConCall.getDataTypeArguments();
assertEquals(3, parameters.size()); |
<<<<<<<
private static FunctionDefinition INT_FROM_NAT;
=======
>>>>>>>
<<<<<<<
case "fromNat": {
var parent = definition.getReferable().getLocatedReferableParent();
assert parent != null;
switch (parent.getRefName()) {
default:
throw new IllegalArgumentException(parent.getRefName() + " shouldn't have member fromNat");
case "Int":
INT_FROM_NAT = (FunctionDefinition) definition;
INT_FROM_NAT.setStatus(Definition.TypeCheckingStatus.NO_ERRORS);
break;
case "Fin":
FIN_FROM_NAT = (FunctionDefinition) definition;
FIN_FROM_NAT.setStatus(Definition.TypeCheckingStatus.NO_ERRORS);
break;
}
break;
}
=======
>>>>>>>
case "fromNat":
FIN_FROM_NAT = (FunctionDefinition) definition;
FIN_FROM_NAT.setStatus(Definition.TypeCheckingStatus.NO_ERRORS);
break;
<<<<<<<
consumer.accept(INT_FROM_NAT);
=======
>>>>>>>
<<<<<<<
public FunctionDefinition getIntFromNat() {
return INT_FROM_NAT;
}
@Override
=======
>>>>>>> |
<<<<<<<
import com.jetbrains.jetpad.vclang.module.ModuleLoader;
=======
import com.jetbrains.jetpad.vclang.term.Abstract;
import com.jetbrains.jetpad.vclang.term.Concrete;
import com.jetbrains.jetpad.vclang.term.Prelude;
>>>>>>>
import com.jetbrains.jetpad.vclang.module.ModuleLoader;
import com.jetbrains.jetpad.vclang.term.Abstract;
import com.jetbrains.jetpad.vclang.term.Concrete;
import com.jetbrains.jetpad.vclang.term.Prelude; |
<<<<<<<
import com.liferay.portal.*;
=======
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.SendPasswordException;
import com.liferay.portal.UserEmailAddressException;
>>>>>>>
import com.liferay.portal.*;
<<<<<<<
=======
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils);
>>>>>>>
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils);
<<<<<<<
new ForgotPasswordResource(userLocalManager, userManager,
companyAPI, responseUtil);
=======
new ForgotPasswordResource(userLocalManager, userService,
companyAPI, authenticationHelper);
>>>>>>>
new ForgotPasswordResource(userLocalManager, userService,
companyAPI, responseUtil);
<<<<<<<
=======
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils);
>>>>>>>
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils);
<<<<<<<
=======
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils);
>>>>>>>
final JsonWebTokenUtils jsonWebTokenUtils = mock(JsonWebTokenUtils.class);
final WebResource webResource = new WebResource(apiProvider, jsonWebTokenUtils); |
<<<<<<<
import com.dotmarketing.util.UtilMethods;
import com.httpbridge.webproxy.http.TaskController;
=======
import com.dotcms.repackage.httpbridge.com.httpbridge.webproxy.http.TaskController;
import com.liferay.portal.auth.PrincipalFinder;
>>>>>>>
import com.dotmarketing.util.UtilMethods;
import com.dotcms.repackage.httpbridge.com.httpbridge.webproxy.http.TaskController; |
<<<<<<<
Map<String, Map<String, EndpointDetail>> endpointsMap = localHistory.getEndpointsMap();
Map<String, Map<String, EndpointDetail>> endpointTrackingMap = new HashMap<String, Map<String, EndpointDetail>>();
// For each group (environment)
for (String groupID : endpointsMap.keySet()) {
Map<String, EndpointDetail> endpointsGroup = endpointsMap.get(groupID);
// For each endpoint (server) in the group
for (String endpointID : endpointsGroup.keySet()) {
PublishingEndPoint targetEndpoint = endpointAPI.findEndPointById(endpointID);
if (targetEndpoint != null && !targetEndpoint.isSending()) {
WebTarget webTarget = client.target(targetEndpoint.toURL() + "/api/auditPublishing");
try {
// Try to get the status of the remote endpoints to
// update the local history
PublishAuditHistory remoteHistory =
PublishAuditHistory.getObjectFromString(
webTarget
.path("get")
.path(bundleAudit.getBundleId()).request().get(String.class));
if (remoteHistory != null) {
endpointTrackingMap.putAll(remoteHistory
.getEndpointsMap());
for (String remoteGroupId : remoteHistory
.getEndpointsMap().keySet()) {
Map<String, EndpointDetail> remoteGroup = endpointTrackingMap
.get(remoteGroupId);
for (String remoteEndpointId : remoteGroup
.keySet()) {
EndpointDetail remoteDetail = remoteGroup
.get(remoteEndpointId);
localHistory.addOrUpdateEndpoint(
groupID, endpointID,
remoteDetail);
=======
//There is no need to keep checking after MAX_NUM_TRIES.
if (localHistory.getNumTries() <= (MAX_NUM_TRIES + 1)){
Map<String, Map<String, EndpointDetail>> endpointsMap = localHistory.getEndpointsMap();
Map<String, Map<String, EndpointDetail>> endpointTrackingMap = new HashMap<String, Map<String, EndpointDetail>>();
// For each group (environment)
for (String groupID : endpointsMap.keySet()) {
Map<String, EndpointDetail> endpointsGroup = endpointsMap.get(groupID);
// For each endpoint (server) in the group
for (String endpointID : endpointsGroup.keySet()) {
PublishingEndPoint targetEndpoint = endpointAPI.findEndPointById(endpointID);
if (targetEndpoint != null && !targetEndpoint.isSending()) {
WebResource webResource = client.resource(targetEndpoint.toURL() + "/api/auditPublishing");
try {
// Try to get the status of the remote endpoints to
// update the local history
PublishAuditHistory remoteHistory =
PublishAuditHistory.getObjectFromString(
webResource
.path("get")
.path(bundleAudit.getBundleId()).get(String.class));
if (remoteHistory != null) {
endpointTrackingMap.putAll(remoteHistory
.getEndpointsMap());
for (String remoteGroupId : remoteHistory
.getEndpointsMap().keySet()) {
Map<String, EndpointDetail> remoteGroup = endpointTrackingMap
.get(remoteGroupId);
for (String remoteEndpointId : remoteGroup
.keySet()) {
EndpointDetail remoteDetail = remoteGroup
.get(remoteEndpointId);
localHistory.addOrUpdateEndpoint(
groupID, endpointID,
remoteDetail);
}
>>>>>>>
//There is no need to keep checking after MAX_NUM_TRIES.
if (localHistory.getNumTries() <= (MAX_NUM_TRIES + 1)){
Map<String, Map<String, EndpointDetail>> endpointsMap = localHistory.getEndpointsMap();
Map<String, Map<String, EndpointDetail>> endpointTrackingMap = new HashMap<String, Map<String, EndpointDetail>>();
// For each group (environment)
for (String groupID : endpointsMap.keySet()) {
Map<String, EndpointDetail> endpointsGroup = endpointsMap.get(groupID);
// For each endpoint (server) in the group
for (String endpointID : endpointsGroup.keySet()) {
PublishingEndPoint targetEndpoint = endpointAPI.findEndPointById(endpointID);
if (targetEndpoint != null && !targetEndpoint.isSending()) {
WebTarget webTarget = client.target(targetEndpoint.toURL() + "/api/auditPublishing");
try {
// Try to get the status of the remote endpoints to
// update the local history
PublishAuditHistory remoteHistory =
PublishAuditHistory.getObjectFromString(
webTarget
.path("get")
.path(bundleAudit.getBundleId()).request().get(String.class));
if (remoteHistory != null) {
endpointTrackingMap.putAll(remoteHistory
.getEndpointsMap());
for (String remoteGroupId : remoteHistory
.getEndpointsMap().keySet()) {
Map<String, EndpointDetail> remoteGroup = endpointTrackingMap
.get(remoteGroupId);
for (String remoteEndpointId : remoteGroup
.keySet()) {
EndpointDetail remoteDetail = remoteGroup
.get(remoteEndpointId);
localHistory.addOrUpdateEndpoint(
groupID, endpointID,
remoteDetail);
} |
<<<<<<<
ret.add(Task03500RulesEngineDataModel.class);
=======
ret.add(Task03160PublishingPushedAssetsTable.class);
>>>>>>>
ret.add(Task03160PublishingPushedAssetsTable.class);
ret.add(Task03500RulesEngineDataModel.class); |
<<<<<<<
import com.dotcms.content.elasticsearch.business.ContentletIndexAPI;
import com.dotcms.content.elasticsearch.business.ESContentletAPIImpl;
import com.dotcms.content.elasticsearch.business.ESContentletIndexAPI;
import com.dotcms.content.elasticsearch.business.ESIndexAPI;
import com.dotcms.content.elasticsearch.business.IndiciesAPI;
import com.dotcms.content.elasticsearch.business.IndiciesAPIImpl;
import com.dotcms.contenttype.business.ContentTypeApi;
import com.dotcms.contenttype.business.ContentTypeApiImpl;
import com.dotcms.contenttype.business.FieldApi;
import com.dotcms.contenttype.business.FieldApiImpl;
=======
import com.dotcms.company.CompanyAPI;
import com.dotcms.company.CompanyAPIFactory;
import com.dotcms.content.elasticsearch.business.*;
>>>>>>>
import com.dotcms.content.elasticsearch.business.ContentletIndexAPI;
import com.dotcms.content.elasticsearch.business.ESContentletAPIImpl;
import com.dotcms.content.elasticsearch.business.ESContentletIndexAPI;
import com.dotcms.content.elasticsearch.business.ESIndexAPI;
import com.dotcms.content.elasticsearch.business.IndiciesAPI;
import com.dotcms.content.elasticsearch.business.IndiciesAPIImpl;
import com.dotcms.contenttype.business.ContentTypeApi;
import com.dotcms.contenttype.business.ContentTypeApiImpl;
import com.dotcms.contenttype.business.FieldApi;
import com.dotcms.contenttype.business.FieldApiImpl;
import com.dotcms.company.CompanyAPI;
import com.dotcms.company.CompanyAPIFactory;
import com.dotcms.content.elasticsearch.business.*;
<<<<<<<
import com.dotmarketing.beans.Host;
=======
import com.dotcms.rest.api.v1.system.websocket.WebSocketContainerAPI;
import com.dotcms.rest.api.v1.system.websocket.WebSocketContainerAPIFactory;
>>>>>>>
import com.dotmarketing.beans.Host;
import com.dotcms.rest.api.v1.system.websocket.WebSocketContainerAPI;
import com.dotcms.rest.api.v1.system.websocket.WebSocketContainerAPIFactory;
<<<<<<<
public static FieldApi getFieldAPI2() {
return new FieldApiImpl();
}
public static User systemUser() throws DotDataException {
return getUserAPI().getSystemUser();
}
public static Host systemHost() throws DotDataException {
return getHostAPI().findSystemHost();
}
=======
/**
* Returns the System Events API that allows other pieces of the application
* (or third-party services) to interact with events generated by system
* features and react to them.
*
* @return An instance of the {@link SystemEventsAPI}.
*/
public static SystemEventsAPI getSystemEventsAPI() {
return (SystemEventsAPI) getInstance(APIIndex.SYSTEM_EVENTS_API);
}
/**
* Generates a unique instance of the specified dotCMS API.
*
* @param index
* - The specified API to retrieve based on the {@link APIIndex}
* class.
* @return A singleton of the API.
*/
>>>>>>>
public static FieldApi getFieldAPI2() {
return new FieldApiImpl();
}
public static User systemUser() throws DotDataException {
return getUserAPI().getSystemUser();
}
public static Host systemHost() throws DotDataException {
return getHostAPI().findSystemHost();
}
/**
* Returns the System Events API that allows other pieces of the application
* (or third-party services) to interact with events generated by system
* features and react to them.
*
* @return An instance of the {@link SystemEventsAPI}.
*/
public static SystemEventsAPI getSystemEventsAPI() {
return (SystemEventsAPI) getInstance(APIIndex.SYSTEM_EVENTS_API);
}
/**
* Generates a unique instance of the specified dotCMS API.
*
* @param index
* - The specified API to retrieve based on the {@link APIIndex}
* class.
* @return A singleton of the API.
*/ |
<<<<<<<
public static RulesCache getRulesCache() {
return (RulesCache) getInstance(CacheIndex.RulesCache);
}
public static SiteVisitCache getSiteVisitCache() {
return (SiteVisitCache) getInstance(CacheIndex.SiteVisitCache);
}
=======
public static ContentTypeCache getContentTypeCache() {
return (ContentTypeCache) getInstance(CacheIndex.ContentTypeCache);
}
>>>>>>>
public static RulesCache getRulesCache() {
return (RulesCache) getInstance(CacheIndex.RulesCache);
}
public static SiteVisitCache getSiteVisitCache() {
return (SiteVisitCache) getInstance(CacheIndex.SiteVisitCache);
}
public static ContentTypeCache getContentTypeCache() {
return (ContentTypeCache) getInstance(CacheIndex.ContentTypeCache);
}
<<<<<<<
NewNotification("NewNotification Cache"),
RulesCache("Rules Cache"),
SiteVisitCache("Rules Engine - Site Visits");
=======
NewNotification("NewNotification Cache"),
ContentTypeCache("Content Type Cache");
>>>>>>>
RulesCache("Rules Cache"),
SiteVisitCache("Rules Engine - Site Visits"),
NewNotification("NewNotification Cache"),
ContentTypeCache("Content Type Cache");
<<<<<<<
case RulesCache : return new RulesCacheImpl();
case SiteVisitCache : return new SiteVisitCacheImpl();
=======
case ContentTypeCache: return new ContentTypeCacheImpl();
>>>>>>>
case RulesCache : return new RulesCacheImpl();
case SiteVisitCache : return new SiteVisitCacheImpl();
case ContentTypeCache: return new ContentTypeCacheImpl(); |
<<<<<<<
import com.dotcms.repackage.org.apache.struts.Globals;
=======
>>>>>>>
import com.dotcms.repackage.struts.org.apache.struts.Globals; |
<<<<<<<
import com.dotmarketing.startup.runonce.Task01311CreateClusterConfigModel;
=======
import com.dotmarketing.startup.runonce.Task01320PostgresqlIndiciesFK;
>>>>>>>
import com.dotmarketing.startup.runonce.Task01311CreateClusterConfigModel;
import com.dotmarketing.startup.runonce.Task01320PostgresqlIndiciesFK;
<<<<<<<
ret.add(Task01311CreateClusterConfigModel.class);
=======
ret.add(Task01320PostgresqlIndiciesFK.class);
>>>>>>>
ret.add(Task01311CreateClusterConfigModel.class);
ret.add(Task01320PostgresqlIndiciesFK.class); |
<<<<<<<
import com.dotcms.datagen.ContainerDataGen;
import com.dotcms.datagen.ContentletDataGen;
import com.dotcms.datagen.FolderDataGen;
import com.dotcms.datagen.HTMLPageDataGen;
import com.dotcms.datagen.StructureDataGen;
import com.dotcms.datagen.TemplateDataGen;
=======
import com.dotcms.mock.request.MockInternalRequest;
import com.dotcms.mock.response.BaseResponse;
>>>>>>>
import com.dotcms.datagen.ContainerDataGen;
import com.dotcms.datagen.ContentletDataGen;
import com.dotcms.datagen.FolderDataGen;
import com.dotcms.datagen.HTMLPageDataGen;
import com.dotcms.datagen.StructureDataGen;
import com.dotcms.datagen.TemplateDataGen;
import com.dotcms.mock.request.MockInternalRequest;
import com.dotcms.mock.response.BaseResponse; |
<<<<<<<
if(metaMap!=null) {
Gson gson = new Gson();
=======
if(metaMap!=null){
Identifier contIdent = APILocator.getIdentifierAPI().find(contentlet);
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
>>>>>>>
if(metaMap!=null) {
Gson gson = new GsonBuilder().disableHtmlEscaping().create(); |
<<<<<<<
import com.dotmarketing.business.*;
import com.dotmarketing.portlets.contentlet.business.DotContentletStateException;
import com.dotmarketing.portlets.rules.business.RulesEngine;
import com.dotmarketing.portlets.rules.model.Rule;
import com.liferay.portal.language.LanguageException;
import org.apache.commons.logging.LogFactory;
=======
>>>>>>>
import com.dotmarketing.portlets.contentlet.business.DotContentletStateException;
import com.dotmarketing.portlets.rules.business.RulesEngine;
import com.dotmarketing.portlets.rules.model.Rule;
import com.liferay.portal.language.LanguageException; |
<<<<<<<
import com.dotmarketing.startup.runonce.Task01330CreateIndicesForVersionTables;
=======
import com.dotmarketing.startup.runonce.Task01325CreateFoundationForNotificationSystem;
>>>>>>>
import com.dotmarketing.startup.runonce.Task01325CreateFoundationForNotificationSystem;
import com.dotmarketing.startup.runonce.Task01330CreateIndicesForVersionTables;
<<<<<<<
ret.add(Task01330CreateIndicesForVersionTables.class);
=======
ret.add(Task01325CreateFoundationForNotificationSystem.class);
>>>>>>>
ret.add(Task01325CreateFoundationForNotificationSystem.class);
ret.add(Task01330CreateIndicesForVersionTables.class); |
<<<<<<<
ret.add(Task00865AddTimestampToVersionTables.class);
=======
ret.add(Task00900CreateLogConsoleTable.class);
>>>>>>>
ret.add(Task00865AddTimestampToVersionTables.class);
ret.add(Task00900CreateLogConsoleTable.class); |
<<<<<<<
ret.add(Task03500RulesEngineDataModel.class);
=======
ret.add(Task03165ModifyLoadRecordsToIndex.class);
>>>>>>>
ret.add(Task03165ModifyLoadRecordsToIndex.class);
ret.add(Task03500RulesEngineDataModel.class); |
<<<<<<<
import com.dotcms.repackage.org.codehaus.jackson.annotate.JsonIgnore;
import com.dotmarketing.business.*;
=======
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.dotmarketing.business.PermissionAPI;
import com.dotmarketing.business.PermissionSummary;
import com.dotmarketing.business.Permissionable;
import com.dotmarketing.business.RelatedPermissionableGroup;
>>>>>>>
import com.dotmarketing.business.*;
<<<<<<<
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
=======
>>>>>>>
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
<<<<<<<
public boolean evaluate(HttpServletRequest req, HttpServletResponse res) throws DotDataException {
boolean result = true;
for (ConditionGroup group : getGroups()) {
if(group.getOperator()== Condition.Operator.AND) {
result = result && group.evaluate(req, res);
} else {
result = result || group.evaluate(req, res);
}
if(!result) return false;
}
return result;
}
public boolean equals(Object o) {
if(!UtilMethods.isSet(o)) return false;
if(!(o instanceof Rule)) return false;
return id.equals(((Rule)o).getId());
}
=======
@JSONIgnore
@Override
public String toString() {
return "Rule [id=" + id + ", name=" + name + ", fireOn=" + fireOn
+ ", shortCircuit=" + shortCircuit + ", host=" + host
+ ", folder=" + folder + ", priority=" + priority
+ ", enabled=" + enabled + ", modDate=" + modDate + "]";
}
>>>>>>>
public boolean evaluate(HttpServletRequest req, HttpServletResponse res) throws DotDataException {
boolean result = true;
for (ConditionGroup group : getGroups()) {
if(group.getOperator()== Condition.Operator.AND) {
result = result && group.evaluate(req, res);
} else {
result = result || group.evaluate(req, res);
}
if(!result) return false;
}
return result;
}
public boolean equals(Object o) {
if(!UtilMethods.isSet(o)) return false;
if(!(o instanceof Rule)) return false;
return id.equals(((Rule)o).getId());
}
@JSONIgnore
@Override
public String toString() {
return "Rule [id=" + id + ", name=" + name + ", fireOn=" + fireOn
+ ", shortCircuit=" + shortCircuit + ", host=" + host
+ ", folder=" + folder + ", priority=" + priority
+ ", enabled=" + enabled + ", modDate=" + modDate + "]";
} |
<<<<<<<
List htmlPages = getChildrenClass(folder, HTMLPage.class);
=======
List files = getChildrenClass(folder, File.class);
>>>>>>>
<<<<<<<
for (Object page : htmlPages) {
APILocator.getHTMLPageAPI().movePage((HTMLPage) page, folder, systemUser, false);
}
=======
for (Object file : files) {
APILocator.getFileAPI().moveFile((File) file, folder, systemUser, false);
}
>>>>>>>
<<<<<<<
List htmlPages = getChildrenClass(nextFolder, HTMLPage.class);
=======
List files = getChildrenClass(nextFolder,File.class);
>>>>>>>
<<<<<<<
updateMovedFolderAssets(nextFolder, nextNewFolder, htmlPages, links);
=======
>>>>>>>
updateMovedFolderAssets(nextFolder, nextNewFolder, links);
<<<<<<<
List htmlPages = getChildrenClass(theFolder,HTMLPage.class);
for (HTMLPage page : (List<HTMLPage>) htmlPages) {
Identifier identifier = APILocator.getIdentifierAPI().find(page);
if (page.isWorking()) {
// updating caches
WorkingCache.removeAssetFromCache(page);
CacheLocator.getIdentifierCache().removeFromCacheByVersionable(page);
}
if (page.isLive()) {
LiveCache.removeAssetFromCache(page);
}
if (page.isWorking()) {
// gets identifier for this webasset and changes the uri and
// persists it
identifier.setHostId(newHost.getIdentifier());
identifier.setURI(page.getURI(theFolder));
APILocator.getIdentifierAPI().save(identifier);
CacheLocator.getIdentifierCache().removeFromCacheByIdentifier(identifier.getId());
}
// Add to Preview and Live Cache
if (page.isLive()) {
LiveCache.removeAssetFromCache(page);
LiveCache.addToLiveAssetToCache(page);
}
if (page.isWorking()) {
WorkingCache.removeAssetFromCache(page);
WorkingCache.addToWorkingAssetToCache(page);
CacheLocator.getIdentifierCache().removeFromCacheByVersionable(page);
}
// republishes the page to reset the VTL_SERVLETURI variable
if (page.isLive()) {
PageServices.invalidateAll(page);
}
}
=======
List<File> files = APILocator.getFolderAPI().getFiles(theFolder, systemUser, false);
for (File file : files) {
Identifier identifier = APILocator.getIdentifierAPI().find(file);
// assets cache
if (file.isLive())
LiveCache.removeAssetFromCache(file);
if (file.isWorking())
WorkingCache.removeAssetFromCache(file);
if (file.isWorking()) {
// gets identifier for this webasset and changes the uri and
// persists it
identifier.setHostId(newHost.getIdentifier());
identifier.setURI(file.getURI(theFolder));
APILocator.getIdentifierAPI().save(identifier);
CacheLocator.getIdentifierCache().removeFromCacheByIdentifier(identifier.getId());
}
// Add to Preview and Live Cache
if (file.isLive()) {
LiveCache.addToLiveAssetToCache(file);
}
if (file.isWorking())
WorkingCache.addToWorkingAssetToCache(file);
}
>>>>>>>
<<<<<<<
private void updateMovedFolderAssets(Folder oldFolder, Folder newFolder, List<HTMLPage> htmlPages, List<Link> links)
=======
private void updateMovedFolderAssets(Folder oldFolder, Folder newFolder, List<File> files, List<Link> links)
>>>>>>>
private void updateMovedFolderAssets(Folder oldFolder, Folder newFolder, List<Link> links)
<<<<<<<
for (HTMLPage page : htmlPages) {
APILocator.getHTMLPageAPI().movePage(page, newFolder, systemUser, false);
}
=======
for (File file : files) {
APILocator.getFileAPI().moveFile(file, newFolder, systemUser, false);
}
>>>>>>> |
<<<<<<<
import com.dotcms.rest.api.v1.authentication.AuthenticationResource;
import com.dotcms.rest.api.v1.authentication.ForgotPasswordResource;
import com.dotcms.rest.api.v1.authentication.LoginFormResource;
import com.dotcms.rest.api.v1.authentication.LogoutResource;
import com.dotcms.rest.api.v1.content.ContentletResource;
=======
import com.dotcms.rest.api.v1.authentication.*;
>>>>>>>
import com.dotcms.rest.api.v1.authentication.AuthenticationResource;
import com.dotcms.rest.api.v1.authentication.ForgotPasswordResource;
import com.dotcms.rest.api.v1.authentication.LoginFormResource;
import com.dotcms.rest.api.v1.authentication.LogoutResource;
import com.dotcms.rest.api.v1.content.ContentletResource;
import com.dotcms.rest.api.v1.authentication.*;
<<<<<<<
REST_CLASSES.add(ContentletResource.class);
=======
REST_CLASSES.add(ResetPasswordResource.class);
>>>>>>>
REST_CLASSES.add(ContentletResource.class);
REST_CLASSES.add(ResetPasswordResource.class); |
<<<<<<<
import com.dotmarketing.startup.runonce.Task00900CreateLogConsoleTable;
=======
import com.dotmarketing.startup.runonce.Task00850DropOldFilesConstraintInWorkflow;
import com.dotmarketing.startup.runonce.Task00855FixRenameFolder;
import com.dotmarketing.startup.runonce.Task00860ExtendServerIdsMSSQL;
>>>>>>>
import com.dotmarketing.startup.runonce.Task00900CreateLogConsoleTable;
import com.dotmarketing.startup.runonce.Task00850DropOldFilesConstraintInWorkflow;
import com.dotmarketing.startup.runonce.Task00855FixRenameFolder;
import com.dotmarketing.startup.runonce.Task00860ExtendServerIdsMSSQL;
<<<<<<<
ret.add(Task00900CreateLogConsoleTable.class);
=======
ret.add(Task00850DropOldFilesConstraintInWorkflow.class);
ret.add(Task00855FixRenameFolder.class);
ret.add(Task00860ExtendServerIdsMSSQL.class);
>>>>>>>
ret.add(Task00850DropOldFilesConstraintInWorkflow.class);
ret.add(Task00855FixRenameFolder.class);
ret.add(Task00860ExtendServerIdsMSSQL.class);
ret.add(Task00900CreateLogConsoleTable.class); |
<<<<<<<
=======
import com.dotcms.concurrent.DotSubmitter;
>>>>>>>
import com.dotcms.concurrent.DotSubmitter;
<<<<<<<
SystemEventType systemEventType = isNew ? SystemEventType.SAVE_BASE_CONTENT_TYPE : SystemEventType.UPDATE_BASE_CONTENT_TYPE;
ContentType type=new StructureTransformer(structure).from();
try {
String actionUrl = contentTypeUtil.getActionUrl(type);
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
systemEventsAPI.push(systemEventType, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION,
PermissionAPI.PERMISSION_READ));
} catch (DotDataException e) {
throw new RuntimeException( e );
}
=======
final DotSubmitter dotSubmitter =
SystemEventsFactory.getInstance().getDotSubmitter();
dotSubmitter.execute(() -> {
final SystemEventType systemEventType = isNew ?
SystemEventType.SAVE_BASE_CONTENT_TYPE : SystemEventType.UPDATE_BASE_CONTENT_TYPE;
try {
String actionUrl = isNew ? contentTypeUtil.getActionUrl(structure) : null;
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, structure);
systemEventsAPI.push(systemEventType, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION,
PermissionAPI.PERMISSION_READ));
} catch (DotDataException e) {
throw new BaseRuntimeInternationalizationException( e );
}
});
>>>>>>>
ContentType type=new StructureTransformer(structure).from();
final DotSubmitter dotSubmitter =
SystemEventsFactory.getInstance().getDotSubmitter();
dotSubmitter.execute(() -> {
final SystemEventType systemEventType = isNew ?
SystemEventType.SAVE_BASE_CONTENT_TYPE : SystemEventType.UPDATE_BASE_CONTENT_TYPE;
try {
String actionUrl = contentTypeUtil.getActionUrl(type);
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
systemEventsAPI.push(systemEventType, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION,
PermissionAPI.PERMISSION_READ));
} catch (DotDataException e) {
throw new RuntimeException( e );
}
}); |
<<<<<<<
ret.add(Task03500RulesEngineDataModel.class);
=======
ret.add(Task03150LoweCaseURLOnVirtualLinksTable.class);
>>>>>>>
ret.add(Task03150LoweCaseURLOnVirtualLinksTable.class);
ret.add(Task03500RulesEngineDataModel.class); |
<<<<<<<
private static VelocityServlet me;
public static VelocityServlet me(){
return me;
}
=======
private final String PREVIEW_MODE_VTL= "preview_mode.vtl";
private final String PREVIEW_MODE_MENU_VTL= "preview_mode_menu.vtl";
>>>>>>>
private final String PREVIEW_MODE_VTL= "preview_mode.vtl";
private final String PREVIEW_MODE_MENU_VTL= "preview_mode_menu.vtl";
private static VelocityServlet me;
public static VelocityServlet me(){
return me;
} |
<<<<<<<
ret.add(Task03550ModificationDateColumnAddedToUserTable.class);
=======
ret.add(Task03550RenameContainersTable.class);
>>>>>>>
ret.add(Task03550RenameContainersTable.class);
ret.add(Task03550ModificationDateColumnAddedToUserTable.class); |
<<<<<<<
import com.dotmarketing.business.APILocator;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.portlets.rules.conditionlet.Conditionlet;
import com.dotmarketing.portlets.rules.conditionlet.ConditionletInputValue;
import com.dotmarketing.util.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
=======
>>>>>>>
import com.dotmarketing.business.APILocator;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.portlets.rules.conditionlet.Conditionlet;
import com.dotmarketing.util.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
<<<<<<<
public Conditionlet getConditionlet() {
if(conditionlet==null) {
try {
conditionlet = APILocator.getRulesAPI().findConditionlet(conditionletId);
} catch (DotDataException | DotSecurityException e) {
Logger.error(this, "Unable to load conditionlet for condition with id: " + id);
}
}
return conditionlet;
}
public void setConditionlet(Conditionlet conditionlet) {
this.conditionlet = conditionlet;
}
public boolean evaluate(HttpServletRequest req, HttpServletResponse res) {
return getConditionlet().evaluate(req, res, getComparison(), getValues());
}
=======
@Override
public String toString() {
return "Condition [id=" + id + ", name=" + name + ", ruleId=" + ruleId
+ ", conditionletId=" + conditionletId + ", conditionGroup="
+ conditionGroup + ", comparison=" + comparison + ", values="
+ values + ", modDate=" + modDate + ", operator=" + operator
+ ", priority=" + priority + "]";
}
>>>>>>>
public Conditionlet getConditionlet() {
if(conditionlet==null) {
try {
conditionlet = APILocator.getRulesAPI().findConditionlet(conditionletId);
} catch (DotDataException | DotSecurityException e) {
Logger.error(this, "Unable to load conditionlet for condition with id: " + id);
}
}
return conditionlet;
}
public void setConditionlet(Conditionlet conditionlet) {
this.conditionlet = conditionlet;
}
public boolean evaluate(HttpServletRequest req, HttpServletResponse res) {
return getConditionlet().evaluate(req, res, getComparison(), getValues());
}
@Override
public String toString() {
return "Condition [id=" + id + ", name=" + name + ", ruleId=" + ruleId
+ ", conditionletId=" + conditionletId + ", conditionGroup="
+ conditionGroup + ", comparison=" + comparison + ", values="
+ values + ", modDate=" + modDate + ", operator=" + operator
+ ", priority=" + priority + "]";
} |
<<<<<<<
import java.net.InetAddress;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.cache.Fqn;
import org.jgroups.Address;
import org.jgroups.ChannelClosedException;
import org.jgroups.ChannelException;
import org.jgroups.ChannelNotConnectedException;
import org.jgroups.Event;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.PhysicalAddress;
import org.jgroups.ReceiverAdapter;
import org.jgroups.View;
import com.dotcms.cluster.bean.ESProperty;
import com.dotcms.cluster.bean.Server;
import com.dotcms.cluster.bean.ServerPort;
import com.dotcms.cluster.business.ClusterFactory;
import com.dotcms.cluster.business.ServerAPI;
=======
import com.dotcms.repackage.backport_util_concurrent_3_1.edu.emory.mathcs.backport.java.util.Collections;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.Cache;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.CacheBuilder;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.RemovalListener;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.RemovalNotification;
import com.dotcms.repackage.jbosscache_core.org.jboss.cache.Fqn;
import com.dotcms.repackage.jgroups_2_12_2_final.org.jgroups.*;
import com.dotcms.repackage.struts.org.apache.struts.Globals;
>>>>>>>
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import com.dotcms.cluster.bean.Server;
import com.dotcms.cluster.bean.ServerPort;
import com.dotcms.cluster.business.ClusterFactory;
import com.dotcms.cluster.business.ServerAPI;
import com.dotcms.repackage.backport_util_concurrent_3_1.edu.emory.mathcs.backport.java.util.Collections;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.Cache;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.CacheBuilder;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.RemovalListener;
import com.dotcms.repackage.guava_11_0_1.com.google.common.cache.RemovalNotification;
import com.dotcms.repackage.jbosscache_core.org.jboss.cache.Fqn;
import com.dotcms.repackage.jgroups_2_12_2_final.org.jgroups.*;
import com.dotcms.repackage.struts.org.apache.struts.Globals;
<<<<<<<
public static final String TEST_MESSAGE = "HELLO CLUSTER!";
=======
>>>>>>>
public static final String TEST_MESSAGE = "HELLO CLUSTER!";
<<<<<<<
=======
>>>>>>>
<<<<<<<
cacheToDisk = new ConcurrentHashMap<String, Boolean>();
=======
cacheToDisk.clear();
>>>>>>>
cacheToDisk.clear();
<<<<<<<
try {
channel.send(null, null, "ACK");
} catch (ChannelNotConnectedException e) {
Logger.error(DotGuavaCacheAdministratorImpl.class, e.getMessage(), e);
} catch (ChannelClosedException e) {
Logger.error(DotGuavaCacheAdministratorImpl.class, e.getMessage(), e);
}
} else if (v.toString().equals("ACK")) {
Logger.info(this, "ACK Received " + new Date());
=======
} else if(v.toString().equals("MultiMessageResources.reload")) {
MultiMessageResources messages = (MultiMessageResources) Config.CONTEXT.getAttribute( Globals.MESSAGES_KEY );
messages.reload();
>>>>>>>
try {
channel.send(null, null, "ACK");
} catch (ChannelNotConnectedException e) {
Logger.error(DotGuavaCacheAdministratorImpl.class, e.getMessage(), e);
} catch (ChannelClosedException e) {
Logger.error(DotGuavaCacheAdministratorImpl.class, e.getMessage(), e);
}
} else if (v.toString().equals("ACK")) {
Logger.info(this, "ACK Received " + new Date());
} else if(v.toString().equals("MultiMessageResources.reload")) {
MultiMessageResources messages = (MultiMessageResources) Config.CONTEXT.getAttribute( Globals.MESSAGES_KEY );
messages.reload(); |
<<<<<<<
user.getAgreedToTermsOfUse(), user.getActive());
userHBM.setModDate(user.getModificationDate());
=======
user.getAgreedToTermsOfUse(), user.getActive(),
user.getDeleteInProgress(), user.getDeleteDate());
>>>>>>>
user.getAgreedToTermsOfUse(), user.getActive(),
user.getDeleteInProgress(), user.getDeleteDate());
userHBM.setModDate(user.getModificationDate());
<<<<<<<
userHBM.setModDate(user.getModificationDate());
=======
userHBM.setDeleteInProgress(user.getDeleteInProgress());
userHBM.setDeleteDate(user.getDeleteDate());
>>>>>>>
userHBM.setDeleteInProgress(user.getDeleteInProgress());
userHBM.setDeleteDate(user.getDeleteDate());
userHBM.setModDate(user.getModificationDate());
<<<<<<<
user.getAgreedToTermsOfUse(), user.getActive());
userHBM.setModDate(user.getModificationDate());
=======
user.getAgreedToTermsOfUse(), user.getActive(),
user.getDeleteInProgress(), user.getDeleteDate());
>>>>>>>
user.getAgreedToTermsOfUse(), user.getActive(),
user.getDeleteInProgress(), user.getDeleteDate());
userHBM.setModDate(user.getModificationDate()); |
<<<<<<<
import com.dotcms.rest.RestClientBuilder;
import com.dotcms.rest.api.v1.sites.ruleengine.RestCondition;
import com.dotmarketing.beans.Host;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.exception.DotSecurityException;
import com.dotmarketing.portlets.contentlet.business.HostAPI;
import com.dotmarketing.portlets.rules.actionlet.CountRequestsActionlet;
import com.dotmarketing.portlets.rules.conditionlet.MockTrueConditionlet;
import com.dotmarketing.portlets.rules.model.*;
=======
import com.dotcms.rest.api.FunctionalTestConfig;
>>>>>>>
<<<<<<<
* @param ruleName
* @return
* @throws JSONException
=======
>>>>>>>
<<<<<<<
private String createRule(String ruleName) throws JSONException{
//setup
JSONObject ruleJSON = new JSONObject();
ruleJSON.put("name", ruleName);
=======
private String createRule(String ruleID) throws JSONException {
//setup
JSONObject ruleJSON = new JSONObject();
ruleJSON.put("name", ruleID);
>>>>>>>
<<<<<<<
response = target.path("/sites/" + defaultHost.getIdentifier() + "/ruleengine/conditions/" + conditionId).request(MediaType.APPLICATION_JSON_TYPE).delete();
deleteConditionGroup(group, rule);
deleteRule(rule);
}
@Test
public void testUsersCountryConditionlet() throws JSONException{
// setup
final String RULE_NAME = "testUsersCountryRule";
final String CONDITION_NAME = "testUsersCountryCondition";
final String ruleId = createRule(RULE_NAME);
final String groupId = createConditionGroup(ruleId);
try {
// create valid condition
RestCondition restCondition = new RestCondition.Builder()
.name(CONDITION_NAME)
.conditionlet(UsersCountryConditionlet.class.getSimpleName())
.comparison("is")
.operator(Condition.Operator.AND.name())
.owningGroup(groupId)
.build();
WebTarget target = client.target("http://" + serverName + ":" + serverPort + "/api/v1");
// REST POST condition
Response response = target.path("/sites/" + defaultHost.getIdentifier() + "/ruleengine/conditions")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(restCondition));
assertTrue(response.getStatus() == HttpStatus.SC_OK);
// get the id of the POSTed condition from the response
String responseStr = response.readEntity(String.class);
JSONObject responseJSON = new JSONObject(responseStr);
String conditionId = (String) responseJSON.get("id");
// REST GET condition by Id
response = target.path("/sites/" + defaultHost.getIdentifier() + "/ruleengine/conditions/" + conditionId)
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
assertTrue(response.getStatus() == HttpStatus.SC_OK);
RestCondition returnedCondition = response.readEntity(RestCondition.class);
assertTrue(returnedCondition.name.equals(CONDITION_NAME));
// create a condition value
RestConditionValue value = new RestConditionValue.Builder().value("VE").priority(0).build();
// REST POST condition value
response = target.path("/sites/" + defaultHost.getIdentifier() + "/ruleengine/conditions/" + conditionId + "/conditionValues")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(value));
assertTrue(response.getStatus() == HttpStatus.SC_OK);
// REST DELETE condition
response = target.path("/sites/" + defaultHost.getIdentifier() + "/ruleengine/conditions/" + conditionId).request(MediaType.APPLICATION_JSON_TYPE).delete();
assertTrue(response.getStatus() == HttpStatus.SC_NO_CONTENT);
} finally {
deleteConditionGroup(groupId, ruleId);
deleteRule(ruleId);
}
}
=======
response = target.path("/sites/" + config.defaultHostId + "/ruleengine/conditions/" + conditionId)
.request(MediaType.APPLICATION_JSON_TYPE)
.delete();
deleteConditionGroup(group, rule);
deleteRule(rule);
}
>>>>>>> |
<<<<<<<
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import com.dotcms.contenttype.business.ContentTypeApi;
import com.dotcms.contenttype.exception.NotFoundInDbException;
import com.dotcms.contenttype.model.type.BaseContentType;
import com.dotcms.contenttype.model.type.ContentType;
import com.dotcms.contenttype.transform.contenttype.StructureTransformer;
=======
>>>>>>>
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import com.dotcms.contenttype.business.ContentTypeApi;
import com.dotcms.contenttype.exception.NotFoundInDbException;
import com.dotcms.contenttype.model.type.BaseContentType;
import com.dotcms.contenttype.model.type.ContentType;
import com.dotcms.contenttype.transform.contenttype.StructureTransformer;
<<<<<<<
=======
>>>>>>>
<<<<<<<
=======
>>>>>>>
<<<<<<<
=======
import java.io.Serializable;
import java.util.*;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_READ;
import static com.dotmarketing.business.PermissionAPI.PERMISSION_WRITE;
>>>>>>>
<<<<<<<
String actionUrl = contentTypeUtil.getActionUrl(type);
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
=======
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, structure);
>>>>>>>
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
<<<<<<<
String actionUrl = contentTypeUtil.getActionUrl(type);
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
systemEventsAPI.push(SystemEventType.DELETE_BASE_CONTENT_TYPE, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION, PermissionAPI.PERMISSION_READ));
=======
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, structure);
systemEventsAPI.push(SystemEventType.DELETE_BASE_CONTENT_TYPE, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION,
PermissionAPI.PERMISSION_READ));
>>>>>>>
ContentTypePayloadDataWrapper contentTypePayloadDataWrapper = new ContentTypePayloadDataWrapper(actionUrl, type);
systemEventsAPI.push(SystemEventType.DELETE_BASE_CONTENT_TYPE, new Payload(contentTypePayloadDataWrapper, Visibility.PERMISSION, PermissionAPI.PERMISSION_READ)); |
<<<<<<<
ret.add(Task03725NewNotificationTable.class);
ret.add(Task03730UpdateMssqlVarcharTextColumns.class);
ret.add(Task03800AddIndexLowerStructureTable.class);
=======
ret.add(Task03725NewNotificationTable.class);
>>>>>>>
ret.add(Task03725NewNotificationTable.class);
ret.add(Task03800AddIndexLowerStructureTable.class); |
<<<<<<<
* Register a Rules Engine Conditionlet service
*
* @param context
* @param conditionlet
*/
@SuppressWarnings ("unchecked")
protected void registerRuleConditionlet ( BundleContext context, Conditionlet conditionlet) {
//Getting the service to register our Conditionlet
ServiceReference serviceRefSelected = context.getServiceReference( ConditionletOSGIService.class.getName() );
if ( serviceRefSelected == null ) {
return;
}
if ( conditionlets == null ) {
conditionlets = new ArrayList<Conditionlet>();
}
this.conditionletOSGIService = (ConditionletOSGIService) context.getService( serviceRefSelected );
this.conditionletOSGIService.addConditionlet(conditionlet.getClass());
conditionlets.add( conditionlet );
Logger.info( this, "Added Rule Conditionlet: " + conditionlet.getName() );
//Register Language under /resources/messages folder.
Enumeration<String> langFiles = context.getBundle().getEntryPaths("messages");
while( langFiles.hasMoreElements() ){
String langFile = (String)langFiles.nextElement();
//We need to verify file is a language file.
String languageFilePrefix = "messages" + File.separator + "Language_";
String languageFileSuffix = ".properties";
String languageFileDelimiter = "-";
//Validating Language file name: For example: Language_en-US.properties
if(langFile.startsWith(languageFilePrefix)
&& langFile.contains(languageFileDelimiter)
&& langFile.endsWith(languageFileSuffix)){
//Get the Language and Country Codes.
String languageCountry = langFile.replace(languageFilePrefix,"").replace(languageFileSuffix, "");
String languageCode = languageCountry.split(languageFileDelimiter)[0];
String countryCode = languageCountry.split(languageFileDelimiter)[1];
URL file = context.getBundle().getEntry(langFile);
Map<String, String> generalKeysToAdd = new HashMap<String, String>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(file.openStream()));
String line;
while ((line = in.readLine()) != null){
//Make sure line contains = sign.
String delimiter = "=";
if(line.contains(delimiter)){
String[] keyValue = line.split(delimiter);
String key = keyValue[0];
String value = keyValue[1];
generalKeysToAdd.put(key,value);
}
}
} catch (IOException e) {
Logger.error(this.getClass(), "Error opening Language File: " + langFile, e);
}
try {
Language languageObject = APILocator.getLanguageAPI().getLanguage(languageCode, countryCode);
if(UtilMethods.isSet(languageObject.getLanguageCode())){
APILocator.getLanguageAPI().saveLanguageKeys(languageObject,
generalKeysToAdd,
new HashMap<String, String>(),
new HashSet<String>());
} else {
Logger.warn(this.getClass(), "Country and Language do not exist: " + languageCountry);
}
} catch (DotDataException e) {
Logger.error(this.getClass(), "Error inserting language properties for: " + languageCountry, e);
}
}
}
}
/**
* Register a given CacheProvider implementation
=======
* Register a given CacheProvider implementation for a given region
>>>>>>>
* Register a Rules Engine Conditionlet service
*
* @param context
* @param conditionlet
*/
@SuppressWarnings ("unchecked")
protected void registerRuleConditionlet ( BundleContext context, Conditionlet conditionlet) {
//Getting the service to register our Conditionlet
ServiceReference serviceRefSelected = context.getServiceReference( ConditionletOSGIService.class.getName() );
if ( serviceRefSelected == null ) {
return;
}
if ( conditionlets == null ) {
conditionlets = new ArrayList<Conditionlet>();
}
this.conditionletOSGIService = (ConditionletOSGIService) context.getService( serviceRefSelected );
this.conditionletOSGIService.addConditionlet(conditionlet.getClass());
conditionlets.add( conditionlet );
Logger.info( this, "Added Rule Conditionlet: " + conditionlet.getName() );
//Register Language under /resources/messages folder.
Enumeration<String> langFiles = context.getBundle().getEntryPaths("messages");
while( langFiles.hasMoreElements() ){
String langFile = (String)langFiles.nextElement();
//We need to verify file is a language file.
String languageFilePrefix = "messages" + File.separator + "Language_";
String languageFileSuffix = ".properties";
String languageFileDelimiter = "-";
//Validating Language file name: For example: Language_en-US.properties
if(langFile.startsWith(languageFilePrefix)
&& langFile.contains(languageFileDelimiter)
&& langFile.endsWith(languageFileSuffix)){
//Get the Language and Country Codes.
String languageCountry = langFile.replace(languageFilePrefix,"").replace(languageFileSuffix, "");
String languageCode = languageCountry.split(languageFileDelimiter)[0];
String countryCode = languageCountry.split(languageFileDelimiter)[1];
URL file = context.getBundle().getEntry(langFile);
Map<String, String> generalKeysToAdd = new HashMap<String, String>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(file.openStream()));
String line;
while ((line = in.readLine()) != null){
//Make sure line contains = sign.
String delimiter = "=";
if(line.contains(delimiter)){
String[] keyValue = line.split(delimiter);
String key = keyValue[0];
String value = keyValue[1];
generalKeysToAdd.put(key,value);
}
}
} catch (IOException e) {
Logger.error(this.getClass(), "Error opening Language File: " + langFile, e);
}
try {
Language languageObject = APILocator.getLanguageAPI().getLanguage(languageCode, countryCode);
if(UtilMethods.isSet(languageObject.getLanguageCode())){
APILocator.getLanguageAPI().saveLanguageKeys(languageObject,
generalKeysToAdd,
new HashMap<String, String>(),
new HashSet<String>());
} else {
Logger.warn(this.getClass(), "Country and Language do not exist: " + languageCountry);
}
} catch (DotDataException e) {
Logger.error(this.getClass(), "Error inserting language properties for: " + languageCountry, e);
}
}
}
}
/**
* Register a given CacheProvider implementation for a given region |
<<<<<<<
import java.nio.charset.StandardCharsets;
=======
import org.apache.accumulo.core.Constants;
import org.apache.log4j.Logger;
>>>>>>>
import java.nio.charset.StandardCharsets;
import org.apache.log4j.Logger; |
<<<<<<<
package com.dotmarketing.util;
import java.util.regex.Pattern;
import com.dotcms.repackage.com.google.common.base.CaseFormat;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONArray;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONObject;
public class StringUtils {
public static String formatPhoneNumber(String phoneNumber) {
try {
String s = phoneNumber.replaceAll("\\(|\\)|:|-|\\.", "");
;
s = s.replaceAll("(\\d{3})(\\d{3})(\\d{4})(\\d{3})*", "($1) $2-$3x$4");
if (s.endsWith("x"))
s = s.substring(0, s.length() - 1);
return s;
} catch (Exception ex) {
return "";
}
}
public static boolean isJson(String jsonString) {
if(jsonString.indexOf("{") <0 || jsonString.indexOf("}") <0){
return false;
}
try {
if (jsonString.startsWith("{"))
new JSONObject(jsonString);
else if (jsonString.startsWith("["))
new JSONArray(jsonString);
return true;
} catch (Exception e) {
return false;
}
}
// Pattern is threadsafe
private static Pattern camelCaseLowerPattern = Pattern.compile("^[a-z]+([A-Z][a-z0-9]+)+");
private static Pattern camelCaseUpperPattern = Pattern.compile("^[A-Z]+([A-Z][a-z0-9]+)+");
public static String camelCaseLower(String variable) {
// are we already camelCase?
if(camelCaseLowerPattern.matcher(variable).find()){
return variable;
}
String var = variable.toLowerCase().replaceAll("[^a-z\\d]", "-");
while(var.startsWith("-")){
var =var.substring(1, var.length());
}
return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,var);
}
public static String camelCaseUpper(String variable) {
// are we already camelCase?
if(camelCaseUpperPattern.matcher(variable).find()){
return variable;
}
String ret = camelCaseLower(variable);
String firtChar = ret.substring(0,1);
return firtChar.toUpperCase() + ret.substring(1,ret.length());
}
public static boolean isSet(String test){
return UtilMethods.isSet(test);
}
public static String nullEmptyStr(String test){
return isSet(test) ? test : null;
}
}
=======
package com.dotmarketing.util;
import java.util.regex.Pattern;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONArray;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONObject;
import static com.dotcms.repackage.org.apache.commons.lang.StringUtils.*;
public class StringUtils {
public static final char COMMA = ',';
public static String formatPhoneNumber(String phoneNumber) {
try {
String s = phoneNumber.replaceAll("\\(|\\)|:|-|\\.", "");
;
s = s.replaceAll("(\\d{3})(\\d{3})(\\d{4})(\\d{3})*", "($1) $2-$3x$4");
if (s.endsWith("x"))
s = s.substring(0, s.length() - 1);
return s;
} catch (Exception ex) {
return "";
}
}
public static String sanitizeCamelCase(String variable, boolean firstLetterUppercase) {
Boolean upperCase = firstLetterUppercase;
String velocityvar = "";
String re = "[^a-zA-Z0-9]+";
Pattern p = Pattern.compile(re);
for (int i = 0; i < variable.length(); i++) {
Character c = variable.charAt(i);
if (upperCase) {
c = Character.toUpperCase(c);
} else {
c = Character.toLowerCase(c);
}
if (p.matcher(c.toString()).matches()) {
upperCase = true;
} else {
upperCase = false;
velocityvar += c;
}
}
velocityvar = velocityvar.replaceAll(re, "");
return velocityvar;
}
public static String sanitizeCamelCase(String variable) {
return sanitizeCamelCase(variable, false);
}
public static boolean isJson(String jsonString) {
if(jsonString.indexOf("{") <0 || jsonString.indexOf("}") <0){
return false;
}
try {
if (jsonString.startsWith("{"))
new JSONObject(jsonString);
else if (jsonString.startsWith("["))
new JSONArray(jsonString);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Split the string by commans
* Pre: string argument must be not null
* @param string {@link String}
* @return String array
*/
public static String [] splitByCommas (final String string) {
return split(string, COMMA);
} // splitByComma.
}
>>>>>>>
package com.dotmarketing.util;
import java.util.regex.Pattern;
import com.dotcms.repackage.com.google.common.base.CaseFormat;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONArray;
import com.dotcms.repackage.org.codehaus.jettison.json.JSONObject;
import static com.dotcms.repackage.org.apache.commons.lang.StringUtils.*;
public class StringUtils {
public static String formatPhoneNumber(String phoneNumber) {
try {
String s = phoneNumber.replaceAll("\\(|\\)|:|-|\\.", "");
;
s = s.replaceAll("(\\d{3})(\\d{3})(\\d{4})(\\d{3})*", "($1) $2-$3x$4");
if (s.endsWith("x"))
s = s.substring(0, s.length() - 1);
return s;
} catch (Exception ex) {
return "";
}
}
public static boolean isJson(String jsonString) {
if(jsonString.indexOf("{") <0 || jsonString.indexOf("}") <0){
return false;
}
try {
if (jsonString.startsWith("{"))
new JSONObject(jsonString);
else if (jsonString.startsWith("["))
new JSONArray(jsonString);
return true;
} catch (Exception e) {
return false;
}
}
// Pattern is threadsafe
private static Pattern camelCaseLowerPattern = Pattern.compile("^[a-z]+([A-Z][a-z0-9]+)+");
private static Pattern camelCaseUpperPattern = Pattern.compile("^[A-Z]+([A-Z][a-z0-9]+)+");
public static String camelCaseLower(String variable) {
// are we already camelCase?
if(camelCaseLowerPattern.matcher(variable).find()){
return variable;
}
String var = variable.toLowerCase().replaceAll("[^a-z\\d]", "-");
while(var.startsWith("-")){
var =var.substring(1, var.length());
}
return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,var);
}
public static String camelCaseUpper(String variable) {
// are we already camelCase?
if(camelCaseUpperPattern.matcher(variable).find()){
return variable;
}
String ret = camelCaseLower(variable);
String firtChar = ret.substring(0,1);
return firtChar.toUpperCase() + ret.substring(1,ret.length());
}
public static boolean isSet(String test){
return UtilMethods.isSet(test);
}
public static String nullEmptyStr(String test){
return isSet(test) ? test : null;
}
/**
* Split the string by commans
* Pre: string argument must be not null
* @param string {@link String}
* @return String array
*/
final static char COMMA = ',';
public static String [] splitByCommas (final String string) {
return split(string, COMMA);
} // splitByComma.
} |
<<<<<<<
import com.dotcms.repackage.commons_io_2_0_1.org.apache.commons.io.FilenameUtils;
import org.apache.felix.http.api.ExtHttpService;
=======
>>>>>>>
<<<<<<<
import com.dotcms.repackage.struts.org.apache.struts.Globals;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionForward;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionMapping;
import com.dotcms.repackage.struts.org.apache.struts.config.ActionConfig;
import com.dotcms.repackage.struts.org.apache.struts.config.ForwardConfig;
import com.dotcms.repackage.struts.org.apache.struts.config.ModuleConfig;
import com.dotcms.repackage.struts.org.apache.struts.config.impl.ModuleConfigImpl;
=======
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.ModuleConfig;
>>>>>>> |
<<<<<<<
=======
/**
* Get Locale saved on the {@link HttpSession} {@link Globals} LOCALE_KEY,
* if the LOCALE_KEY is also null, will get the request default one.
*
* If country or language are not null (one of them could be null), will build a new locale.
* Not any session will be created.
* @param request {@link HttpServletRequest}
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request) {
return getLocale (request, null, null);
}
/**
* Get Locale based on the arguments country and language, if both are null will try to get it from the {@link Globals} LOCALE_KEY,
* if the LOCALE_KEY is also null, will get the request default one.
*
* If country or language are not null (one of them could be null), will build a new locale.
* Not any session will be created.
* @param request
* @param country
* @param language
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request, final String country, final String language) {
return getLocale (request, country, language, false);
}
>>>>>>>
/**
* Get Locale saved on the {@link HttpSession} {@link Globals} LOCALE_KEY,
* if the LOCALE_KEY is also null, will get the request default one.
*
* If country or language are not null (one of them could be null), will build a new locale.
* Not any session will be created.
* @param request {@link HttpServletRequest}
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request) {
return getLocale (request, null, null);
}
/**
* Get Locale based on the arguments country and language, if both are null will try to get it from the {@link Globals} LOCALE_KEY,
* if the LOCALE_KEY is also null, will get the request default one.
*
* If country or language are not null (one of them could be null), will build a new locale.
* Not any session will be created.
* @param request
* @param country
* @param language
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request, final String country, final String language) {
return getLocale (request, country, language, false);
}
<<<<<<<
* @param request {@link HttpServletRequest}
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request) {
return getLocale(request, null, null);
} // getLocale
/**
* Get Locale based on the arguments country and language, if both are null will try to get it from the {@link Globals} LOCALE_KEY,
* if the LOCALE_KEY is also null, will get the request default one.
*
* If country or language are not null (one of them could be null), will build a new locale and set to the session under {@link Globals} LOCALE_KEY
* @param request {@link HttpServletRequest}
* @param country {@link String}
* @param language {@link String}
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request, final String country, final String language) {
=======
* @param request
* @param country
* @param language
* @param createSession true if you want to create the session in case it is not created, false otherwise. If the session is not created, won't set the locale in the session at the end of the process.
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request, final String country, final String language, final boolean createSession) {
>>>>>>>
* @param request {@link HttpServletRequest}
* @param country {@link String}
* @param language {@link String}
* @return Locale
* @param createSession true if you want to create the session in case it is not created, false otherwise. If the session is not created, won't set the locale in the session at the end of the process.
* @return Locale
*/
public static Locale getLocale (final HttpServletRequest request, final String country, final String language, final boolean createSession) { |
<<<<<<<
/**
* A key/value pair. The key and value may not be set after construction.
*/
=======
import org.apache.accumulo.core.Constants;
>>>>>>>
import org.apache.accumulo.core.Constants;
/**
* A key/value pair. The key and value may not be set after construction.
*/ |
<<<<<<<
ret.add(Task03055RemoveLicenseManagerPortlet.class);
ret.add(Task03100HTMLPageAsContentChanges.class);
=======
ret.add(Task03055RemoveLicenseManagerPortlet.class);
ret.add(Task03060AddClusterServerAction.class);
ret.add(Task03065AddHtmlPageIR.class);
>>>>>>>
ret.add(Task03055RemoveLicenseManagerPortlet.class);
ret.add(Task03060AddClusterServerAction.class);
ret.add(Task03065AddHtmlPageIR.class);
ret.add(Task03100HTMLPageAsContentChanges.class); |
<<<<<<<
import com.dotcms.api.web.HttpServletRequestThreadLocal;
import com.dotcms.cms.login.LoginService;
import com.dotcms.cms.login.LoginServiceFactory;
import com.dotcms.rest.api.v1.system.websocket.SessionWrapper;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.UserAPI;
import com.liferay.portal.model.User;
import javax.servlet.http.HttpServletRequest;
=======
>>>>>>>
import com.dotcms.api.web.HttpServletRequestThreadLocal;
import com.dotcms.cms.login.LoginService;
import com.dotcms.cms.login.LoginServiceFactory;
import com.dotcms.rest.api.v1.system.websocket.SessionWrapper;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.UserAPI;
import com.liferay.portal.model.User;
import javax.servlet.http.HttpServletRequest;
<<<<<<<
private final String visibilityId; // user id, role uid or permission, if it is global, this is not need
private final Map<String, Object> user;
=======
private final String visibilityId; // user id, role uid or permission, if it is global, this is not need
>>>>>>>
private final Map<String, Object> user;
private final String visibilityId; // user id, role uid or permission, if it is global, this is not need
<<<<<<<
public boolean verified(SessionWrapper session) {
return visibility.verified(session, this);
}
/**
* return the user who fire the event, if the user was fired by a Job and not by a User's action then the user
* is the System User
*
* @return
*/
public Map<String, Object> getUser() {
return user;
}
=======
>>>>>>>
/**
* return the user who fire the event, if the user was fired by a Job and not by a User's action then the user
* is the System User
*
* @return
*/
public Map<String, Object> getUser() {
return user;
} |
<<<<<<<
import org.grobid.core.utilities.KeyGen;
import org.grobid.core.engines.citations.LabeledReferenceResult;
import org.grobid.core.engines.citations.ReferenceSegmenter;
import org.grobid.core.engines.counters.CitationParserCounters;
import org.grobid.core.engines.tagging.GenericTaggerUtils;
=======
>>>>>>>
import org.grobid.core.utilities.KeyGen;
import org.grobid.core.engines.citations.LabeledReferenceResult;
import org.grobid.core.engines.citations.ReferenceSegmenter;
import org.grobid.core.engines.counters.CitationParserCounters;
import org.grobid.core.engines.tagging.GenericTaggerUtils;
<<<<<<<
// general segmentation
Document doc = parsers.getSegmentationParser().processing(inputPdf, config);
=======
// general segmentation
Document doc = parsers.getSegmentationParser().processing(inputPdf, config);
>>>>>>>
// general segmentation
Document doc = parsers.getSegmentationParser().processing(inputPdf, config);
<<<<<<<
//parsers.getHeaderParser().processingHeaderBlock(config.isConsolidateHeader(), doc, resHeader);
parsers.getHeaderParser().processingHeaderSection(config.isConsolidateHeader(), doc, resHeader);
// above, use the segmentation model result
=======
//if (mode == 0)
{
parsers.getHeaderParser().processingHeaderBlock(config.isConsolidateHeader(), doc, resHeader);
}
/*else {
parsers.getHeaderParser().processingHeaderSection(doc, consolidateHeader, resHeader);
}*/
>>>>>>>
//parsers.getHeaderParser().processingHeaderBlock(config.isConsolidateHeader(), doc, resHeader);
parsers.getHeaderParser().processingHeaderSection(config.isConsolidateHeader(), doc, resHeader);
// above, use the segmentation model result
<<<<<<<
figures, tables,
config);
=======
config);
>>>>>>>
figures, tables,
config);
<<<<<<<
SortedSet<DocumentPiece> documentBodyParts) {
if ((documentBodyParts == null) || (documentBodyParts.size() == 0)) {
=======
SortedSet<DocumentPiece> documentBodyParts) {
if ((documentBodyParts == null) || (documentBodyParts.size() == 0)) {
>>>>>>>
SortedSet<DocumentPiece> documentBodyParts) {
if ((documentBodyParts == null) || (documentBodyParts.size() == 0)) {
<<<<<<<
boolean graphicVector = false;
boolean graphicBitmap = false;
Block block = blocks.get(blockIndex);
=======
Block block = blocks.get(blockIndex);
>>>>>>>
boolean graphicVector = false;
boolean graphicBitmap = false;
Block block = blocks.get(blockIndex);
<<<<<<<
SortedSet<DocumentPiece> documentBodyParts = doc.getDocumentPart(SegmentationLabel.BODY);
if (documentBodyParts != null) {
=======
//String fulltext = doc.getFulltextFeatured(true, true);
SortedSet<DocumentPiece> documentBodyParts = doc.getDocumentPart(SegmentationLabel.BODY);
if (documentBodyParts != null) {
>>>>>>>
SortedSet<DocumentPiece> documentBodyParts = doc.getDocumentPart(SegmentationLabel.BODY);
if (documentBodyParts != null) {
<<<<<<<
=======
>>>>>>>
<<<<<<<
StringBuilder bufferName = parsers.getAuthorParser().trainingExtraction(inputs, false);
=======
StringBuffer bufferName = parsers.getAuthorParser().trainingExtraction(inputs, false);
>>>>>>>
StringBuilder bufferName = parsers.getAuthorParser().trainingExtraction(inputs, false);
<<<<<<<
private StringBuilder trainingExtraction(String result,
List<LayoutToken> tokenizations) {
=======
private StringBuffer trainingExtraction(String result,
List<LayoutToken> tokenizations) {
>>>>>>>
private StringBuilder trainingExtraction(String result,
List<LayoutToken> tokenizations) {
<<<<<<<
output = writeField(buffer, s1, lastTag0, s2, "<equation>",
"<formula>", addSpace, 4, false);
=======
if (openFigure) {
output = writeField(buffer, s1, lastTag0, s2, "<trash>", "<trash>", addSpace, 4, false);
} else {
//output = writeField(buffer, s1, lastTag0, s2, "<trash>", "<figure>\n\t\t\t\t<trash>",
output = writeField(buffer, s1, lastTag0, s2, "<trash>", "<trash>",
addSpace, 3, false);
if (output) {
openFigure = true;
}
}
}
if (!output) {
output = writeField(buffer, s1, lastTag0, s2, "<equation>",
"<formula>", addSpace, 3, false);
}
if (!output) {
output = writeField(buffer, s1, lastTag0, s2, "<figure_marker>",
"<ref type=\"figure\">", addSpace, 3, false);
>>>>>>>
output = writeField(buffer, s1, lastTag0, s2, "<equation>",
"<formula>", addSpace, 4, false);
<<<<<<<
List<Figure> figures,
List<Table> tables,
GrobidAnalysisConfig config) {
=======
GrobidAnalysisConfig config) {
>>>>>>>
List<Figure> figures,
List<Table> tables,
GrobidAnalysisConfig config) {
<<<<<<<
//int mode = config.getFulltextProcessingMode();
tei = teiFormater.toTEIBody(tei, reseBody, resHeader, resCitations,
layoutTokenization, figures, tables, doc, config);
=======
int mode = config.getFulltextProcessingMode();
if (config.getFulltextProcessingMode() == 0) {
tei = teiFormater.toTEIBodyLight(tei, reseBody, resHeader, resCitations,
layoutTokenization, doc, config);
}
else if (mode == 1) {
tei = teiFormater.toTEIBodyML(tei, reseBody, resHeader, resCitations,
layoutTokenization.getTokenization(), doc);
}
>>>>>>>
//int mode = config.getFulltextProcessingMode();
tei = teiFormater.toTEIBody(tei, reseBody, resHeader, resCitations,
layoutTokenization, figures, tables, doc, config); |
<<<<<<<
// not used anymore
protected transient DocumentNode top = null;
=======
>>>>>>>
<<<<<<<
protected transient Multimap<Integer, GraphicObject> imagesPerPage = LinkedListMultimap.create();
=======
// the document outline (or bookmark) embedded in the PDF, if present
protected DocumentNode outlineRoot = null;
protected Multimap<Integer, GraphicObject> imagesPerPage = LinkedListMultimap.create();
>>>>>>>
// the document outline (or bookmark) embedded in the PDF, if present
protected transient DocumentNode outlineRoot = null;
protected transient Multimap<Integer, GraphicObject> imagesPerPage = LinkedListMultimap.create(); |
<<<<<<<
retVal = engine.processHeader(originFile.getAbsolutePath(), consolidate, null);
=======
if (isparallelExec) {
retVal = engine.processHeader(originFile.getAbsolutePath(), consolidate, null);
//retVal = engine.segmentAndProcessHeader(originFile, consolidate, null);
GrobidPoolingFactory.returnEngine(engine);
engine = null;
} else {
//TODO: sync does not make sense
synchronized (engine) {
retVal = engine.processHeader(originFile.getAbsolutePath(), consolidate, null);
//retVal = engine.segmentAndProcessHeader(originFile, consolidate, null);
}
}
if ((retVal == null) || (retVal.isEmpty())) {
response = Response.status(Status.NO_CONTENT).build();
} else {
if (htmlFormat) {
response = Response.status(Status.OK).entity(formatAsHTML(retVal)).type(MediaType.APPLICATION_XML).build();
} else {
response = Response.status(Status.OK).entity(retVal).type(MediaType.APPLICATION_XML).build();
}
}
>>>>>>>
retVal = engine.processHeader(originFile.getAbsolutePath(), consolidate, null);
<<<<<<<
public String processFulltextDocument(final InputStream inputStream,
final boolean consolidate,
final boolean htmlFormat,
final int startPage,
final int endPage,
final boolean generateIDs) throws Exception {
=======
public static Response processStatelessFulltextDocument(final InputStream inputStream,
final boolean consolidate,
final boolean htmlFormat,
final int startPage,
final int endPage,
final boolean generateIDs,
final List<String> teiCoordinates) {
>>>>>>>
public String processFulltextDocument(final InputStream inputStream,
final boolean consolidate,
final boolean htmlFormat,
final int startPage,
final int endPage,
final boolean generateIDs,
final List<String> teiCoordinates) throws Exception { |
<<<<<<<
import org.apache.commons.lang3.StringUtils;
=======
>>>>>>>
<<<<<<<
import org.grobid.core.utilities.LayoutTokensUtil;
=======
import org.grobid.core.utilities.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
>>>>>>>
import org.grobid.core.utilities.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<<<<<<<
public static void main(String args[]) {
try {
// /Work/temp/context/1000k/AS_101465473421322_1401202662564.pdf
// /Work/temp/context/1000k/AS_104748833312772_1401985480367.pdf - invalid byte
//
// File input = new File("/Work/temp/pub_citation_styles/1994FEBSLett350_235Hadden.pdf");
// File input = new File("/Work/temp/context/1000k/AS_99223336914944_1400668095132.pdf");
// File input = new File("/tmp/AS_100005549445135_1400854589869.pdf"); // not all tokens
// File input = new File("/Work/temp/context/coords/1.pdf");
// File input = new File("/Work/temp/context/1000k/AS_101465473421322_1401202662564.pdf");
// File input = new File("/Work/temp/context/1000k/AS_104748833312772_1401985480367.pdf");
// File input = new File("/Work/temp/context/1000k/AS_101477532045313_1401205537270.pdf"); // NO BLOCKS
File input = new File("/Users/zholudev/Downloads/2010 Materials Science and Engineering B Vikas.pdf"); // NO BLOCKS
// File input = new File("/Users/zholudev/Downloads/AS-316773709090817@1452536145958_content_1.pdf"); // NO BLOCKS
// File input = new File("/Users/zholudev/Downloads/AS-231890204491776@1432298341550_content_1.pdfs");
// File input = new File("/Users/zholudev/Downloads/AS-101217116098573@1401143449634_content_1.pdf");
// File input = new File("/Users/zholudev/Downloads/AS-320647283052546@1453459677289_content_1.pdf"); //BAD BLOCK
// File input = new File("/Users/zholudev/Downloads/AS-99301753622543@1400686791996_content_1 (1).pdf"); //spaces
// File input = new File("/Users/zholudev/Downloads/AS-321758798778369@1453724683241_content_1.pdf"); //spaces
// File input = new File("/Users/zholudev/Downloads/AS-100068715663376@1400869649962_content_1.pdf");
// File input = new File("/Users/zholudev/Downloads/Es0264448.pdf");
// File input = new File("/Users/zholudev/Downloads/AS-322933097549839@1454004659412_content_1.pdf");
//
//
// File input = new File("/Users/zholudev/Downloads/AS-317309489483776@1452663885159_content_1.pdf");
// File input = new File("/tmp/2.pdf");
// File input = new File("/Users/zholudev/Downloads/Curtoni 2009 Perspectivas Actuales.pdf");
// File input = new File("/Work/temp/figureExtraction/3.pdf");
// File input = new File("/Work/temp/context/tilo/4.pdf");
// File input = new File("/tmp/test2.pdf");
// File input = new File("/Work/workspace/habibi/habibi-worker/src/test/resources/data/pdfs/AS_319297254236160_1453137804981.pdf");
// File input = new File("/Work/temp/pub_citation_styles/1996ParPrecConfProc00507369.pdf");
// File input = new File("/Work/temp/pub_citation_styles/LaptenokJSSv18i08.pdf");
//
// File input = new File("/Work/temp/context/coords/3.pdf");
// File input = new File("/Work/temp/context/coords/3.pdf");
// File input = new File("/Work/temp/context/coords/2.pdf");
final PDDocument document = PDDocument.load(input);
File outPdf = new File("/tmp/test.pdf");
GrobidProperties.set_GROBID_HOME_PATH("grobid-home");
GrobidProperties.setGrobidPropertiesPath("grobid-home/config/grobid.properties");
LibraryLoader.load();
final Engine engine = GrobidFactory.getInstance().getEngine();
GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder().
build();
Document teiDoc = engine.fullTextToTEIDoc(input, config);
PDDocument out = annotatePdfWithCitations(document, teiDoc);
if (out != null) {
out.save(outPdf);
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(outPdf);
}
}
System.out.println(Engine.getCntManager());
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static PDDocument annotatePdfWithCitations(PDDocument document, Document teiDoc) throws IOException, COSVisitorException, XPathException {
=======
private static final Logger LOGGER = LoggerFactory.getLogger(CitationsVisualizer.class);
/**
* Augment a PDF with bibliographical annotation, for bib. ref. and bib markers.
* The PDF annotation layer is used with "GoTo" and "URI" action links.
* The annotations of the bibliographical references can be associated to an URL in order
* to have clickable references direclty in the PDF.
* The Apache PDFBox library is used.
*
* @param document PDDocument object resulting from the PDF parsing with PDFBox
* @param teiDoc the Document object resulting from the full document structuring
* @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference
* annotations, if null the bib. ref. annotations are not associated to external URL.
*/
public static PDDocument annotatePdfWithCitations(PDDocument document, Document teiDoc,
List<String> resolvedBibRefUrl) throws IOException, COSVisitorException, XPathException {
>>>>>>>
private static final Logger LOGGER = LoggerFactory.getLogger(CitationsVisualizer.class);
/**
* Augment a PDF with bibliographical annotation, for bib. ref. and bib markers.
* The PDF annotation layer is used with "GoTo" and "URI" action links.
* The annotations of the bibliographical references can be associated to an URL in order
* to have clickable references direclty in the PDF.
* The Apache PDFBox library is used.
*
* @param document PDDocument object resulting from the PDF parsing with PDFBox
* @param teiDoc the Document object resulting from the full document structuring
* @param resolvedBibRefUrl the list of URL to be added to the bibliographical reference
* annotations, if null the bib. ref. annotations are not associated to external URL.
*/
public static PDDocument annotatePdfWithCitations(PDDocument document, Document teiDoc,
List<String> resolvedBibRefUrl) throws IOException, COSVisitorException, XPathException {
<<<<<<<
String teiId = cit.getResBib().getTeiId();
annotatePage(document, b.toString(), teiId.hashCode(), contexts.containsKey(teiId) ? 1.5f : 0.5f);
//annotating reference markers
for (BibDataSetContext c : contexts.get(teiId)) {
System.out.println(c.getContext());
String mrect = c.getDocumentCoords();
// if (!c.getTeiId().equals("b5")) {
for (String coords : mrect.split(";")) {
annotatePage(document, coords, teiId.hashCode(), 1.0f);
}
// }
=======
annotatePage(document, b.toString(), teiId, theUrl, 1.5f, false, dictionary);
}
//annotating reference markers
for (BibDataSetContext c : contexts.get(teiId)) {
//System.out.println(c.getContext());
String mrect = c.getDocumentCoords();
if ((mrect != null) && (mrect.trim().length()>0)) {
for (String coords : mrect.split(";")) {
if (coords.trim().length() == 0)
continue;
annotatePage(document, coords, teiId, null, 1.0f, true, dictionary);
totalMarkers1++;
}
>>>>>>>
annotatePage(document, b.toString(), teiId, theUrl, 1.5f, false, dictionary);
}
//annotating reference markers
for (BibDataSetContext c : contexts.get(teiId)) {
//System.out.println(c.getContext());
String mrect = c.getDocumentCoords();
if ((mrect != null) && (mrect.trim().length()>0)) {
for (String coords : mrect.split(";")) {
if (coords.trim().length() == 0)
continue;
annotatePage(document, coords, teiId, null, 1.0f, true, dictionary);
totalMarkers1++;
}
<<<<<<<
if (teiDoc.getResHeader() != null && teiDoc.getResHeader().getFullAuthors() != null) {
for (Person p : teiDoc.getResHeader().getFullAuthors()) {
if (p.getLayoutTokens() != null) {
String coordsString = LayoutTokensUtil.getCoordsString(p.getLayoutTokens());
for (String coords : coordsString.split(";")) {
annotatePage(document, coords, p.getLastName() == null ? 1 : p.getLastName().hashCode(), 1.0f);
}
}
}
}
=======
LOGGER.debug("totalBib: " + totalBib);
LOGGER.debug("totalMarkers1: " + totalMarkers1);
LOGGER.debug("totalMarkers2: " + totalMarkers2);
>>>>>>>
if (teiDoc.getResHeader() != null && teiDoc.getResHeader().getFullAuthors() != null) {
for (Person p : teiDoc.getResHeader().getFullAuthors()) {
if (p.getLayoutTokens() != null) {
String coordsString = LayoutTokensUtil.getCoordsString(p.getLayoutTokens());
for (String coords : coordsString.split(";")) {
annotatePage(document, coords, p.getLastName() == null ? 1 : p.getLastName().hashCode(), 1.0f);
}
}
}
}
LOGGER.debug("totalBib: " + totalBib);
LOGGER.debug("totalMarkers1: " + totalMarkers1);
LOGGER.debug("totalMarkers2: " + totalMarkers2);
<<<<<<<
private static void annotatePage(PDDocument document, String coords, long seed, float lineWidth) throws IOException {
System.out.println("Annotating for coordinates: " + coords);
if (StringUtils.isEmpty(coords)) {
return;
}
String[] split = coords.split(",");
=======
private static void annotatePage(PDDocument document,
String coords,
String teiId,
String uri,
float lineWidth,
boolean isMarker,
Map<String, Pair<Integer, Integer>> dictionary) throws IOException {
//System.out.println("Annotating for coordinates: " + coords);
/*long seed = 0L;
if (teiId != null)
seed = teiId.hashCode();*/
String[] split = coords.split(",");
>>>>>>>
private static void annotatePage(PDDocument document,
String coords,
String teiId,
String uri,
float lineWidth,
boolean isMarker,
Map<String, Pair<Integer, Integer>> dictionary) throws IOException {
//System.out.println("Annotating for coordinates: " + coords);
/*long seed = 0L;
if (teiId != null)
seed = teiId.hashCode();*/
if (StringUtils.isEmpty(coords)) {
return;
}
String[] split = coords.split(","); |
<<<<<<<
SubbuilderType withIndexCache(BlockCache indexCache);
=======
public SubbuilderType withIndexCache(BlockCache indexCache);
/**
* (Optional) set the file len cache to be used to optimize reads within the constructed reader.
*/
public SubbuilderType withFileLenCache(Cache<String,Long> fileLenCache);
>>>>>>>
SubbuilderType withIndexCache(BlockCache indexCache);
/**
* (Optional) set the file len cache to be used to optimize reads within the constructed reader.
*/
SubbuilderType withFileLenCache(Cache<String,Long> fileLenCache); |
<<<<<<<
SecurityUtil.serverLogin(SiteConfiguration.getInstance());
=======
final String app = "monitor";
Accumulo.setupLogging(app);
SecurityUtil.serverLogin(ServerConfiguration.getSiteConfiguration());
>>>>>>>
final String app = "monitor";
Accumulo.setupLogging(app);
SecurityUtil.serverLogin(SiteConfiguration.getInstance()); |
<<<<<<<
import org.restlet.ext.apispark.internal.firewall.FirewallFilter;
import org.restlet.ext.apispark.internal.firewall.handler.BlockingHandler;
import org.restlet.ext.apispark.internal.firewall.handler.policy.PerValueLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.handler.policy.RoleLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.handler.policy.UniqueLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.ConcurrentFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallIpFilteringRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallRule;
import org.restlet.ext.apispark.internal.firewall.rule.PeriodicFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.policy.HostDomainCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.IpAddressCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.UserCountingPolicy;
=======
import org.restlet.ext.apispark.internal.firewall.FirewallFilter;
import org.restlet.ext.apispark.internal.firewall.handler.BlockingHandler;
import org.restlet.ext.apispark.internal.firewall.handler.policy.PerValueLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.handler.policy.RoleLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.handler.policy.UniqueLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.ConcurrentFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallRule;
import org.restlet.ext.apispark.internal.firewall.rule.PeriodicFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.policy.HostDomainCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.IpAddressCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.UserCountingPolicy;
>>>>>>>
import org.restlet.ext.apispark.internal.firewall.FirewallFilter;
import org.restlet.ext.apispark.internal.firewall.handler.BlockingHandler;
import org.restlet.ext.apispark.internal.firewall.handler.policy.RoleLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.handler.policy.UniqueLimitPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.ConcurrentFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallIpFilteringRule;
import org.restlet.ext.apispark.internal.firewall.rule.FirewallRule;
import org.restlet.ext.apispark.internal.firewall.rule.PeriodicFirewallCounterRule;
import org.restlet.ext.apispark.internal.firewall.rule.policy.HostDomainCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.IpAddressCountingPolicy;
import org.restlet.ext.apispark.internal.firewall.rule.policy.UserCountingPolicy; |
<<<<<<<
private final int protocolVersion;
private final DerivedPasswordCache derivedPasswordCache;
private KeyStretchingFunction keyStretchingFunction;
private DefaultEncryptionProtocol(int protocolVersion, byte[] preferenceSalt, EncryptionFingerprint fingerprint,
StringMessageDigest stringMessageDigest, AuthenticatedEncryption authenticatedEncryption,
@AuthenticatedEncryption.KeyStrength int keyStrength, KeyStretchingFunction keyStretchingFunction,
DataObfuscator.Factory dataObfuscatorFactory, SecureRandom secureRandom,
boolean enableDerivedPasswordCaching, Compressor compressor) {
this.protocolVersion = protocolVersion;
=======
private DefaultEncryptionProtocol(EncryptionProtocolConfig defaultConfig, byte[] preferenceSalt,
EncryptionFingerprint fingerprint, StringMessageDigest stringMessageDigest,
SecureRandom secureRandom, List<EncryptionProtocolConfig> additionalDecryptionConfigs) {
this.defaultConfig = defaultConfig;
>>>>>>>
private final DerivedPasswordCache derivedPasswordCache;
private DefaultEncryptionProtocol(EncryptionProtocolConfig defaultConfig, byte[] preferenceSalt,
EncryptionFingerprint fingerprint, StringMessageDigest stringMessageDigest,
SecureRandom secureRandom, boolean enableDerivedPasswordCaching,
List<EncryptionProtocolConfig> additionalDecryptionConfigs) {
this.defaultConfig = defaultConfig;
<<<<<<<
this.derivedPasswordCache = new DerivedPasswordCache.Default(enableDerivedPasswordCaching, secureRandom);
=======
this.additionalDecryptionConfigs = additionalDecryptionConfigs;
>>>>>>>
this.derivedPasswordCache = new DerivedPasswordCache.Default(enableDerivedPasswordCaching, secureRandom);
this.additionalDecryptionConfigs = additionalDecryptionConfigs;
<<<<<<<
+ CONTENT_SALT_SIZE_LENGTH_BYTES + contentSalt.length
+ ENCRYPTED_CONTENT_SIZE_LENGTH_BYTES + encrypted.length);
buffer.putInt(protocolVersion);
=======
+ CONTENT_SALT_SIZE_LENGTH_BYTES + contentSalt.length
+ ENCRYPTED_CONTENT_SIZE_LENGTH_BYTES + encrypted.length);
buffer.putInt(defaultConfig.protocolVersion);
>>>>>>>
+ CONTENT_SALT_SIZE_LENGTH_BYTES + contentSalt.length
+ ENCRYPTED_CONTENT_SIZE_LENGTH_BYTES + encrypted.length);
buffer.putInt(defaultConfig.protocolVersion);
<<<<<<<
keyStretchingFunction = Objects.requireNonNull(function);
derivedPasswordCache.wipe();
=======
defaultConfig = EncryptionProtocolConfig.newBuilder(defaultConfig)
.keyStretchingFunction(Objects.requireNonNull(function))
.build();
>>>>>>>
defaultConfig = EncryptionProtocolConfig.newBuilder(defaultConfig)
.keyStretchingFunction(Objects.requireNonNull(function))
.build();
derivedPasswordCache.wipe();
<<<<<<<
byte[] stretched;
if ((stretched = derivedPasswordCache.get(contentSalt, password)) == null) {
stretched = keyStretchingFunction.stretch(contentSalt, password, STRETCHED_PASSWORD_LENGTH_BYTES);
derivedPasswordCache.put(contentSalt, password, stretched);
}
ikm = ikm.append(stretched);
=======
ikm = ikm.append(defaultConfig.keyStretchingFunction.stretch(contentSalt, password, STRETCHED_PASSWORD_LENGTH_BYTES));
>>>>>>>
byte[] stretched;
if ((stretched = derivedPasswordCache.get(contentSalt, password)) == null) {
stretched = defaultConfig.keyStretchingFunction.stretch(contentSalt, password, STRETCHED_PASSWORD_LENGTH_BYTES);
derivedPasswordCache.put(contentSalt, password, stretched);
}
ikm = ikm.append(stretched);
<<<<<<<
this.enableDerivedPasswordCaching = enableDerivedPasswordCaching;
this.compressor = compressor;
=======
this.additionalDecryptionConfigs = additionalDecryptionConfigs;
>>>>>>>
this.enableDerivedPasswordCaching = enableDerivedPasswordCaching;
this.additionalDecryptionConfigs = additionalDecryptionConfigs;
<<<<<<<
return new DefaultEncryptionProtocol(protocolVersion, preferenceSalt, fingerprint, stringMessageDigest,
authenticatedEncryption, keyStrength, keyStretchingFunction, dataObfuscatorFactory,
secureRandom, enableDerivedPasswordCaching, compressor);
=======
return new DefaultEncryptionProtocol(defaultConfig, preferenceSalt, fingerprint,
stringMessageDigest, secureRandom, additionalDecryptionConfigs);
>>>>>>>
return new DefaultEncryptionProtocol(defaultConfig, preferenceSalt, fingerprint,
stringMessageDigest, secureRandom, enableDerivedPasswordCaching, additionalDecryptionConfigs); |
<<<<<<<
=======
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
>>>>>>>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<<<<<<<
import lombok.AccessLevel;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
=======
>>>>>>>
import lombok.AccessLevel;
import lombok.Getter;
<<<<<<<
private String tenant;
=======
>>>>>>>
private String tenant;
<<<<<<<
this.authorityType = detectAuthorityType(authorityUrl);
=======
this.authorityType = detectAuthorityType();
>>>>>>>
this.authorityType = detectAuthorityType(authorityUrl);
<<<<<<<
static String getTenant(URL authorityUrl) {
String path = authorityUrl.getPath().substring(1);
return path.substring(0, path.indexOf("/"));
=======
void doInstanceDiscovery(boolean validateAuthority, final Map<String, String> headers,
final ServiceBundle serviceBundle)
throws Exception {
// instance discovery should be executed only once per context instance.
if (!instanceDiscoveryCompleted) {
// matching against static list failed
if (!doStaticInstanceDiscovery(validateAuthority)) {
// if authority must be validated and dynamic discovery request
// as a fall back is success
if (validateAuthority
&& !doDynamicInstanceDiscovery(validateAuthority, headers, serviceBundle)) {
throw new AuthenticationException(
AuthenticationErrorMessage.AUTHORITY_NOT_IN_VALID_LIST);
}
}
String msg = LogHelper.createMessage(
"Instance discovery was successful",
headers.get(ClientDataHttpHeaders.CORRELATION_ID_HEADER_NAME));
log.info(msg);
instanceDiscoveryCompleted = true;
}
}
boolean doDynamicInstanceDiscovery(boolean validateAuthority, final Map<String, String> headers,
ServiceBundle serviceBundle)
throws Exception {
final String json = HttpHelper.executeHttpGet(
log,
instanceDiscoveryEndpoint,
headers,
serviceBundle);
final InstanceDiscoveryResponse discoveryResponse = JsonHelper
.convertJsonToObject(json, InstanceDiscoveryResponse.class);
return !StringHelper.isBlank(discoveryResponse
.getTenantDiscoveryEndpoint());
}
boolean doStaticInstanceDiscovery(boolean validateAuthority) {
if (validateAuthority) {
return Arrays.asList(TRUSTED_HOST_LIST).contains(this.host);
}
return true;
>>>>>>>
static String getTenant(URL authorityUrl) {
String path = authorityUrl.getPath().substring(1);
return path.substring(0, path.indexOf("/")); |
<<<<<<<
TableId srcTableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
=======
validateArgumentCount(arguments, tableOp, 2);
String srcTableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
>>>>>>>
validateArgumentCount(arguments, tableOp, 2);
TableId srcTableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
<<<<<<<
final TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
=======
validateArgumentCount(arguments, tableOp, 1);
final String tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
String namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
>>>>>>>
validateArgumentCount(arguments, tableOp, 1);
final TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
<<<<<<<
final TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
=======
validateArgumentCount(arguments, tableOp, 1);
final String tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
String namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
>>>>>>>
validateArgumentCount(arguments, tableOp, 1);
final TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, NOT_ROOT_ID);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
<<<<<<<
TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
=======
validateArgumentCount(arguments, tableOp, 5);
String tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
>>>>>>>
validateArgumentCount(arguments, tableOp, 5);
TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
<<<<<<<
TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
=======
validateArgumentCount(arguments, tableOp, 1);
String tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
String namespaceId = getNamespaceIdFromTableId(tableOp, tableId);
>>>>>>>
validateArgumentCount(arguments, tableOp, 1);
TableId tableId = validateTableIdArgument(arguments.get(0), tableOp, null);
NamespaceId namespaceId = getNamespaceIdFromTableId(tableOp, tableId); |
<<<<<<<
public static final String SESSION_ID = "sessionId";
public static final String USER_ID = "userId";
public static final String AUTH_TOKEN = "authToken";
public static final String TIMEOUT = "timeout";
=======
private AuthUtil() {
}
>>>>>>>
public static final String SESSION_ID = "sessionId";
public static final String USER_ID = "userId";
public static final String AUTH_TOKEN = "authToken";
public static final String TIMEOUT = "timeout";
private AuthUtil() {
} |
<<<<<<<
import javafx.beans.property.*;
=======
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ChangeListener;
>>>>>>>
import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
<<<<<<<
import javafx.util.StringConverter;
=======
>>>>>>>
<<<<<<<
private static <T> DoubleProperty getLowerBoundProperty( Axis<T> axis ) {
=======
private static <T> DoubleProperty getLowerBoundProperty(Axis<T> axis) {
>>>>>>>
private static <T> DoubleProperty getLowerBoundProperty( Axis<T> axis ) {
<<<<<<<
private static <T> DoubleProperty getUpperBoundProperty( Axis<T> axis ) {
=======
private static <T> DoubleProperty getUpperBoundProperty(Axis<T> axis) {
>>>>>>>
private static <T> DoubleProperty getUpperBoundProperty( Axis<T> axis ) {
<<<<<<<
private static <T> DoubleProperty toDoubleProperty( final Axis<T> axis, Property<T> property ) {
final StringProperty stringProperty = new SimpleStringProperty();
final DoubleProperty doubleProperty = new SimpleDoubleProperty() {
// keep a reference so that the stringProperty doesn't get garbage-collected
private final StringProperty stringProp = stringProperty;
};
stringProperty.bindBidirectional(
doubleProperty,
new StringConverter<Number>() {
@Override
public String toString(Number val) {
return val == null ? null : Double.toString(val.doubleValue());
}
=======
private static <T> DoubleProperty toDoubleProperty(Axis<T> axis, Property<T> property) {
final ChangeListener<Number>[] doubleChangeListenerAry = new ChangeListener[1];
final ChangeListener<T>[] realValListenerAry = new ChangeListener[1];
>>>>>>>
private static <T> DoubleProperty toDoubleProperty( final Axis<T> axis, Property<T> property ) {
final ChangeListener<Number>[] doubleChangeListenerAry = new ChangeListener[1];
final ChangeListener<T>[] realValListenerAry = new ChangeListener[1];
<<<<<<<
@SuppressWarnings( "unchecked" )
private static <T> Property<T> getProperty( Object object, String method ) {
=======
private static <T> Property<T> getProperty(Object object, String method) {
>>>>>>>
@SuppressWarnings( "unchecked" )
private static <T> Property<T> getProperty( Object object, String method ) { |
<<<<<<<
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype") + I18nUtil.getString("system_invalid")));
=======
return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype") + I18nUtil.getString("system_unvalid")));
>>>>>>>
return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_gluetype") + I18nUtil.getString("system_invalid")));
<<<<<<<
return new ReturnT<String>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup") + I18nUtil.getString("system_invalid")));
=======
return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup") + I18nUtil.getString("system_unvalid")));
>>>>>>>
return new ReturnT<>(ReturnT.FAIL_CODE, (I18nUtil.getString("jobinfo_field_jobgroup") + I18nUtil.getString("system_invalid"))); |
<<<<<<<
public void setImage(Bitmap newImage) {
this.mBitmapImage = newImage;
this.invalidate();
}
=======
public void setIsViewSelectable(boolean viewSelectable) {
isViewSelectable = viewSelectable;
}
//TODO change background color
public void selectView() {
if (isViewSelectable && !getIsViewSelected()) {
this.isViewSelected = true;
postInvalidate();
}
}
public void deselectView() {
if (isViewSelectable && getIsViewSelected()) {
this.isViewSelected = false;
postInvalidate();
}
}
>>>>>>>
public void setImage(Bitmap newImage) {
this.mBitmapImage = newImage;
this.invalidate();
}
public void setIsViewSelectable(boolean viewSelectable) {
isViewSelectable = viewSelectable;
}
//TODO change background color
public void selectView() {
if (isViewSelectable && !getIsViewSelected()) {
this.isViewSelected = true;
postInvalidate();
}
}
public void deselectView() {
if (isViewSelectable && getIsViewSelected()) {
this.isViewSelected = false;
postInvalidate();
}
} |
<<<<<<<
class ThriftTransportKey {
private final HostAndPort server;
=======
import com.google.common.annotations.VisibleForTesting;
@VisibleForTesting
public class ThriftTransportKey {
private final String location;
private final int port;
>>>>>>>
@VisibleForTesting
public class ThriftTransportKey {
private final HostAndPort server;
<<<<<<<
ThriftTransportKey(HostAndPort server, long timeout, ClientContext context) {
checkNotNull(server, "location is null");
this.server = server;
=======
@VisibleForTesting
public ThriftTransportKey(String location, long timeout, SslConnectionParams sslParams) {
ArgumentChecker.notNull(location);
String[] locationAndPort = location.split(":", 2);
if (locationAndPort.length == 2) {
this.location = locationAndPort[0];
this.port = Integer.parseInt(locationAndPort[1]);
} else
throw new IllegalArgumentException("Location was expected to contain port but did not. location=" + location);
>>>>>>>
@VisibleForTesting
public ThriftTransportKey(HostAndPort server, long timeout, ClientContext context) {
checkNotNull(server, "location is null");
this.server = server; |
<<<<<<<
@SerializedName("query")
private String query;
=======
@SerializedName("constraints")
private List<ConstraintDto> constraints = new ArrayList<>();
>>>>>>>
@SerializedName("query")
private String query;
@SerializedName("constraints")
private List<ConstraintDto> constraints = new ArrayList<>();
<<<<<<<
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
=======
public List<ConstraintDto> getConstraints() {
return constraints;
}
public void setConstraints(List<ConstraintDto> constraints) {
this.constraints = constraints;
}
>>>>>>>
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public List<ConstraintDto> getConstraints() {
return constraints;
}
public void setConstraints(List<ConstraintDto> constraints) {
this.constraints = constraints;
} |
<<<<<<<
Utils.toggleRoot(((CompoundButton) toggle).isChecked());
new updateUI().execute();
});
autoRootToggle.setOnClickListener(toggle -> {
ToggleAutoRoot(autoRootToggle.isChecked());
new Handler().postDelayed(() -> new updateUI().execute(), 1000);
=======
Utils.toggleRoot(((CompoundButton) toggle).isChecked());
new updateUI().execute();
>>>>>>>
Utils.toggleRoot(((CompoundButton) toggle).isChecked());
new updateUI().execute();
});
autoRootToggle.setOnClickListener(toggle -> {
ToggleAutoRoot(autoRootToggle.isChecked());
new Handler().postDelayed(() -> new updateUI().execute(), 1000);
<<<<<<<
if (autoRootStatus) {
rootStatusContainer.setBackgroundColor(green500);
rootStatusIcon.setImageResource(statusAuto);
rootStatusIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
rootStatus.setTextColor(green500);
rootStatus.setText(R.string.root_auto_unmounted);
rootToggle.setEnabled(false);
safetyNetStatusIcon.setImageResource(statusOK);
safetyNetStatus.setText(R.string.root_auto_unmounted_info);
break;
} else {
rootToggle.setEnabled(true);
if (new File("/magisk/.core/bin/su").exists()) {
// Mounted
=======
if (Utils.rootEnabled()) {
// Enabled
>>>>>>>
if (autoRootStatus) {
rootStatusContainer.setBackgroundColor(green500);
rootStatusIcon.setImageResource(statusAuto);
rootStatusIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
rootStatus.setTextColor(green500);
rootStatus.setText(R.string.root_auto_unmounted);
rootToggle.setEnabled(false);
safetyNetStatusIcon.setImageResource(statusOK);
safetyNetStatus.setText(R.string.root_auto_unmounted_info);
break;
} else {
rootToggle.setEnabled(true);
if (Utils.rootEnabled()) {
// Mounted
<<<<<<<
} else {
// Not Mounted
=======
} else {
// Disabled
>>>>>>>
} else {
// Disabled |
<<<<<<<
public static boolean rootStatus() {
try {
String rootStatus = Shell.su("getprop magisk.root").toString();
String fuckyeah = Shell.sh("which su").toString();
Log.d("Magisk","Utils: Rootstatus Checked, " + rootStatus + " and " + fuckyeah);
if (rootStatus.contains("0") && !fuckyeah.contains("su")) {
return false;
} else {
return true;
}
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
=======
>>>>>>>
public static boolean rootStatus() {
try {
String rootStatus = Shell.su("getprop magisk.root").toString();
String fuckyeah = Shell.sh("which su").toString();
Log.d("Magisk", "Utils: Rootstatus Checked, " + rootStatus + " and " + fuckyeah);
if (rootStatus.contains("0") && !fuckyeah.contains("su")) {
return false;
} else {
return true;
}
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
<<<<<<<
Log.d("Magisk", "Utils: FlashZip Running, " + docId + " and " + mUri.toString());
String[] split = docId.split(":");
mName = split[1];
if (mName.contains("/")) {
split = mName.split("/");
}
if (split[1].contains(".zip")) {
file = mContext.getFilesDir() + "/" + split[1];
=======
Log.d("Magisk","Utils: FlashZip Running, " + docId + " and " + mUri.toString());
if (docId.contains(":"))
mName = docId.split(":")[1];
else mName = docId;
if (mName.contains("/"))
mName = mName.substring(mName.lastIndexOf('/') + 1);
if (mName.contains(".zip")) {
file = mContext.getFilesDir() + "/" + mName;
>>>>>>>
Log.d("Magisk", "Utils: FlashZip Running, " + docId + " and " + mUri.toString());
if (docId.contains(":"))
mName = docId.split(":")[1];
else mName = docId;
if (mName.contains("/"))
mName = mName.substring(mName.lastIndexOf('/') + 1);
if (mName.contains(".zip")) {
file = mContext.getFilesDir() + "/" + mName; |
<<<<<<<
import android.app.AppOpsManager;
import android.content.Context;
=======
>>>>>>>
<<<<<<<
if (!prefs.contains("hasCachedRepos")) {
new Utils.LoadModules(this, true).execute();
new Utils.LoadRepos(this, true, delegate).execute();
} else {
new Utils.LoadModules(getApplication(), false).execute();
new Utils.LoadRepos(this, false, delegate).execute();
}
=======
if (!prefs.contains("oauth_key")) {
}
new Utils.LoadModules(this).execute();
new Utils.LoadRepos(this, !prefs.contains("hasCachedRepos"), delegate).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
>>>>>>>
new Utils.LoadModules(this).execute();
new Utils.LoadRepos(this, true, delegate).execute();
new Utils.LoadRepos(this, !prefs.contains("hasCachedRepos"), delegate).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
new Utils.LoadModules(getApplication()).execute();
new Utils.LoadRepos(this, false, delegate).execute(); |
<<<<<<<
=======
import com.github.javiersantos.appupdater.AppUpdater;
import com.github.javiersantos.appupdater.enums.UpdateFrom;
import com.topjohnwu.magisk.utils.Utils;
>>>>>>>
import com.github.javiersantos.appupdater.AppUpdater;
import com.github.javiersantos.appupdater.enums.UpdateFrom;
<<<<<<<
=======
>>>>>>> |
<<<<<<<
WifiUtils.forwardLog((priority, tag, message) -> {
String customTag = tag + "_" + MainActivity.class.getSimpleName();
Log.i(customTag, message);
});
=======
final Button buttonCheck = findViewById(R.id.button_check);
buttonCheck.setOnClickListener(v -> checkWifi());
>>>>>>>
final Button buttonCheck = findViewById(R.id.button_check);
buttonCheck.setOnClickListener(v -> checkWifi());
WifiUtils.forwardLog((priority, tag, message) -> {
String customTag = tag + "_" + MainActivity.class.getSimpleName();
Log.i(customTag, message);
}); |
<<<<<<<
* See {@link FileUtils#relativizePath(String, String, String, boolean)}.
=======
* A token representing a file created by
* {@link #createNewFileAtomic(File)}. The token must be retained until the
* file has been deleted in order to guarantee that the unique file was
* created atomically. As soon as the file is no longer needed the lock
* token must be closed.
*
* @since 4.7
*/
public static class LockToken implements Closeable {
private boolean isCreated;
private Optional<Path> link;
LockToken(boolean isCreated, Optional<Path> link) {
this.isCreated = isCreated;
this.link = link;
}
/**
* @return {@code true} if the file was created successfully
*/
public boolean isCreated() {
return isCreated;
}
@Override
public void close() {
if (link.isPresent()) {
try {
Files.delete(link.get());
} catch (IOException e) {
LOG.error(MessageFormat.format(JGitText.get().closeLockTokenFailed,
this), e);
}
}
}
@Override
public String toString() {
return "LockToken [lockCreated=" + isCreated + //$NON-NLS-1$
", link=" //$NON-NLS-1$
+ (link.isPresent() ? link.get().getFileName() + "]" //$NON-NLS-1$
: "<null>]"); //$NON-NLS-1$
}
}
/**
* Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
* of this class may take care to provide a safe implementation for this
* even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
*
* @param path
* the file to be created
* @return LockToken this token must be closed after the created file was
* deleted
* @throws IOException
* @since 4.7
*/
public LockToken createNewFileAtomic(File path) throws IOException {
return new LockToken(path.createNewFile(), Optional.empty());
}
/**
* See {@link FileUtils#relativize(String, String)}.
>>>>>>>
* A token representing a file created by
* {@link #createNewFileAtomic(File)}. The token must be retained until the
* file has been deleted in order to guarantee that the unique file was
* created atomically. As soon as the file is no longer needed the lock
* token must be closed.
*
* @since 4.7
*/
public static class LockToken implements Closeable {
private boolean isCreated;
private Optional<Path> link;
LockToken(boolean isCreated, Optional<Path> link) {
this.isCreated = isCreated;
this.link = link;
}
/**
* @return {@code true} if the file was created successfully
*/
public boolean isCreated() {
return isCreated;
}
@Override
public void close() {
if (link.isPresent()) {
try {
Files.delete(link.get());
} catch (IOException e) {
LOG.error(MessageFormat.format(JGitText.get().closeLockTokenFailed,
this), e);
}
}
}
@Override
public String toString() {
return "LockToken [lockCreated=" + isCreated + //$NON-NLS-1$
", link=" //$NON-NLS-1$
+ (link.isPresent() ? link.get().getFileName() + "]" //$NON-NLS-1$
: "<null>]"); //$NON-NLS-1$
}
}
/**
* Create a new file. See {@link java.io.File#createNewFile()}. Subclasses
* of this class may take care to provide a safe implementation for this
* even if {@link #supportsAtomicCreateNewFile()} is <code>false</code>
*
* @param path
* the file to be created
* @return LockToken this token must be closed after the created file was
* deleted
* @throws IOException
* @since 4.7
*/
public LockToken createNewFileAtomic(File path) throws IOException {
return new LockToken(path.createNewFile(), Optional.empty());
}
/**
* See {@link FileUtils#relativizePath(String, String, String, boolean)}. |
<<<<<<<
Map<String, Ref> refsToSend;
if (req.getRefPrefixes().isEmpty()) {
refsToSend = getAdvertisedOrDefaultRefs();
} else {
refsToSend = new HashMap<>();
String[] prefixes = req.getRefPrefixes().toArray(new String[0]);
for (Ref ref : db.getRefDatabase().getRefsByPrefix(prefixes)) {
refsToSend.put(ref.getName(), ref);
}
}
=======
Map<String, Ref> refsToSend = getFilteredRefs(req.getRefPrefixes());
>>>>>>>
Map<String, Ref> refsToSend = getFilteredRefs(req.getRefPrefixes());
<<<<<<<
FetchV2Request req = parser.parseFetchRequest(pckIn,
db.getRefDatabase());
currentRequest = req;
=======
FetchV2Request req = parser.parseFetchRequest(pckIn);
>>>>>>>
FetchV2Request req = parser.parseFetchRequest(pckIn);
currentRequest = req; |
<<<<<<<
import org.eclipse.jgit.lib.CommitBuilder;
=======
import org.eclipse.jgit.junit.time.TimeUtil;
>>>>>>>
import org.eclipse.jgit.junit.time.TimeUtil;
import org.eclipse.jgit.lib.CommitBuilder; |
<<<<<<<
import java.nio.file.Files;
import java.nio.file.Path;
=======
import java.nio.file.attribute.BasicFileAttributes;
>>>>>>>
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes; |
<<<<<<<
new Git(db).branchCreate().setName("initial").call();
RevCommit second = new Git(db).commit().setMessage("second commit")
.call();
assertEquals(toString(" initial", "* master"),
toString(execute("git branch --contains 6fd41be")));
assertEquals("* master",
toString(execute("git branch --contains " + second.name())));
=======
try (Git git = new Git(db)) {
git.branchCreate().setName("initial").call();
RevCommit second = git.commit().setMessage("second commit")
.call();
assertArrayOfLinesEquals(new String[] { " initial", "* master", "" },
execute("git branch --contains 6fd41be"));
assertArrayOfLinesEquals(new String[] { "* master", "" },
execute("git branch --contains " + second.name()));
}
>>>>>>>
try (Git git = new Git(db)) {
git.branchCreate().setName("initial").call();
RevCommit second = git.commit().setMessage("second commit")
.call();
assertEquals(toString(" initial", "* master"),
toString(execute("git branch --contains 6fd41be")));
assertEquals("* master",
toString(execute("git branch --contains " + second.name())));
} |
<<<<<<<
import java.util.StringTokenizer;
=======
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
>>>>>>>
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.StringTokenizer;
<<<<<<<
private static final String CONTENT3 = "[" + USER + "]\n\t" + NAME + " = "
+ ALICE + "\n" + "[" + USER + "]\n\t" + EMAIL + " = " + ALICE_EMAIL;
private File trash;
=======
private Path trash;
>>>>>>>
private static final String CONTENT3 = "[" + USER + "]\n\t" + NAME + " = "
+ ALICE + "\n" + "[" + USER + "]\n\t" + EMAIL + " = " + ALICE_EMAIL;
private Path trash;
<<<<<<<
assertArrayEquals(CONTENT2.getBytes(UTF_8), IO.readFully(file));
=======
assertArrayEquals(CONTENT2.getBytes(), IO.readFully(file.toFile()));
>>>>>>>
assertArrayEquals(CONTENT2.getBytes(UTF_8), IO.readFully(file.toFile()));
<<<<<<<
bos2.write(" \n\t".getBytes(UTF_8));
bos2.write(CONTENT2.getBytes(UTF_8));
assertArrayEquals(bos2.toByteArray(), IO.readFully(file));
=======
bos2.write(" \n\t".getBytes());
bos2.write(CONTENT2.getBytes());
assertArrayEquals(bos2.toByteArray(), IO.readFully(file.toFile()));
>>>>>>>
bos2.write(" \n\t".getBytes(UTF_8));
bos2.write(CONTENT2.getBytes(UTF_8));
assertArrayEquals(bos2.toByteArray(), IO.readFully(file.toFile()));
<<<<<<<
@Test
public void testIncludeDontInlineIncludedLinesOnSave()
throws IOException, ConfigInvalidException {
// use a content with multiple sections and multiple key/value pairs
// because code for first line works different than for subsequent lines
final File includedFile = createFile(CONTENT3.getBytes(UTF_8), "dir1");
final File file = createFile(new byte[0], "dir2");
FileBasedConfig config = new FileBasedConfig(file, FS.DETECTED);
config.setString("include", null, "path",
("../" + includedFile.getParentFile().getName() + "/"
+ includedFile.getName()));
// just by setting the include.path, it won't be included
assertEquals(null, config.getString(USER, null, NAME));
assertEquals(null, config.getString(USER, null, EMAIL));
config.save();
// and it won't be included after saving
assertEquals(null, config.getString(USER, null, NAME));
assertEquals(null, config.getString(USER, null, EMAIL));
final String expectedText = config.toText();
assertEquals(2,
new StringTokenizer(expectedText, "\n", false).countTokens());
config = new FileBasedConfig(file, FS.DETECTED);
config.load();
String actualText = config.toText();
assertEquals(expectedText, actualText);
// but it will be included after (re)loading
assertEquals(ALICE, config.getString(USER, null, NAME));
assertEquals(ALICE_EMAIL, config.getString(USER, null, EMAIL));
config.save();
actualText = config.toText();
assertEquals(expectedText, actualText);
// and of course preserved after saving
assertEquals(ALICE, config.getString(USER, null, NAME));
assertEquals(ALICE_EMAIL, config.getString(USER, null, EMAIL));
}
private File createFile(byte[] content) throws IOException {
=======
private Path createFile(byte[] content) throws IOException {
>>>>>>>
@Test
public void testIncludeDontInlineIncludedLinesOnSave()
throws IOException, ConfigInvalidException {
// use a content with multiple sections and multiple key/value pairs
// because code for first line works different than for subsequent lines
final Path includedFile = createFile(CONTENT3.getBytes(UTF_8), "dir1");
final Path file = createFile(new byte[0], "dir2");
FileBasedConfig config = new FileBasedConfig(file.toFile(),
FS.DETECTED);
config.setString("include", null, "path",
("../" + includedFile.getParent().getFileName() + "/"
+ includedFile.getFileName()));
// just by setting the include.path, it won't be included
assertEquals(null, config.getString(USER, null, NAME));
assertEquals(null, config.getString(USER, null, EMAIL));
config.save();
// and it won't be included after saving
assertEquals(null, config.getString(USER, null, NAME));
assertEquals(null, config.getString(USER, null, EMAIL));
final String expectedText = config.toText();
assertEquals(2,
new StringTokenizer(expectedText, "\n", false).countTokens());
config = new FileBasedConfig(file.toFile(), FS.DETECTED);
config.load();
String actualText = config.toText();
assertEquals(expectedText, actualText);
// but it will be included after (re)loading
assertEquals(ALICE, config.getString(USER, null, NAME));
assertEquals(ALICE_EMAIL, config.getString(USER, null, EMAIL));
config.save();
actualText = config.toText();
assertEquals(expectedText, actualText);
// and of course preserved after saving
assertEquals(ALICE, config.getString(USER, null, NAME));
assertEquals(ALICE_EMAIL, config.getString(USER, null, EMAIL));
}
private Path createFile(byte[] content) throws IOException { |
<<<<<<<
public final class DfsPackFile extends BlockBasedFile {
=======
public final class DfsPackFile {
/**
* File offset used to cache {@link #index} in {@link DfsBlockCache}.
* <p>
* To better manage memory, the forward index is stored as a single block in
* the block cache under this file position. A negative value is used
* because it cannot occur in a normal pack file, and it is less likely to
* collide with a valid data block from the file as the high bits will all
* be set when treated as an unsigned long by the cache code.
*/
private static final long POS_INDEX = -1;
/** Offset used to cache {@link #reverseIndex}. See {@link #POS_INDEX}. */
private static final long POS_REVERSE_INDEX = -2;
/** Offset used to cache {@link #bitmapIndex}. See {@link #POS_INDEX}. */
private static final long POS_BITMAP_INDEX = -3;
/** Cache that owns this pack file and its data. */
private final DfsBlockCache cache;
/** Description of the pack file's storage. */
private final DfsPackDescription packDesc;
/** Unique identity of this pack while in-memory. */
final DfsPackKey key;
/**
* Total number of bytes in this pack file.
* <p>
* This field initializes to -1 and gets populated when a block is loaded.
*/
volatile long length;
/**
* Preferred alignment for loading blocks from the backing file.
* <p>
* It is initialized to 0 and filled in on the first read made from the
* file. Block sizes may be odd, e.g. 4091, caused by the underling DFS
* storing 4091 user bytes and 5 bytes block metadata into a lower level
* 4096 byte block on disk.
*/
private volatile int blockSize;
/** True once corruption has been detected that cannot be worked around. */
private volatile boolean invalid;
/** Exception that caused the packfile to be flagged as invalid */
private volatile Exception invalidatingCause;
>>>>>>>
public final class DfsPackFile extends BlockBasedFile {
<<<<<<<
if (invalid)
throw new PackInvalidException(getFileName());
=======
if (invalid) {
throw new PackInvalidException(getPackName(), invalidatingCause);
}
>>>>>>>
if (invalid) {
throw new PackInvalidException(getFileName(), invalidatingCause);
}
<<<<<<<
throw new IOException(MessageFormat.format(
=======
invalidatingCause = e;
IOException e2 = new IOException(MessageFormat.format(
>>>>>>>
invalidatingCause = e;
throw new IOException(MessageFormat.format(
<<<<<<<
throw new IOException(MessageFormat.format(
=======
invalidatingCause = e;
IOException e2 = new IOException(MessageFormat.format(
>>>>>>>
invalidatingCause = e;
throw new IOException(MessageFormat.format(
<<<<<<<
return new IOException(MessageFormat.format(
JGitText.get().packfileIsTruncated, getFileName()));
=======
IOException exc = new IOException(MessageFormat.format(
JGitText.get().packfileIsTruncated, getPackName()));
invalidatingCause = exc;
return exc;
>>>>>>>
IOException exc = new IOException(MessageFormat.format(
JGitText.get().packfileIsTruncated, getFileName()));
invalidatingCause = exc;
return exc;
<<<<<<<
=======
long alignToBlock(long pos) {
int size = blockSize;
if (size == 0)
size = cache.getBlockSize();
return (pos / size) * size;
}
DfsBlock getOrLoadBlock(long pos, DfsReader ctx) throws IOException {
return cache.getOrLoad(this, pos, ctx);
}
DfsBlock readOneBlock(long pos, DfsReader ctx)
throws IOException {
if (invalid) {
throw new PackInvalidException(getPackName(), invalidatingCause);
}
ctx.stats.readBlock++;
long start = System.nanoTime();
ReadableChannel rc = ctx.db.openFile(packDesc, PACK);
try {
int size = blockSize(rc);
pos = (pos / size) * size;
// If the size of the file is not yet known, try to discover it.
// Channels may choose to return -1 to indicate they don't
// know the length yet, in this case read up to the size unit
// given by the caller, then recheck the length.
long len = length;
if (len < 0) {
len = rc.size();
if (0 <= len)
length = len;
}
if (0 <= len && len < pos + size)
size = (int) (len - pos);
if (size <= 0)
throw new EOFException(MessageFormat.format(
DfsText.get().shortReadOfBlock, Long.valueOf(pos),
getPackName(), Long.valueOf(0), Long.valueOf(0)));
byte[] buf = new byte[size];
rc.position(pos);
int cnt = read(rc, ByteBuffer.wrap(buf, 0, size));
ctx.stats.readBlockBytes += cnt;
if (cnt != size) {
if (0 <= len) {
throw new EOFException(MessageFormat.format(
DfsText.get().shortReadOfBlock,
Long.valueOf(pos),
getPackName(),
Integer.valueOf(size),
Integer.valueOf(cnt)));
}
// Assume the entire thing was read in a single shot, compact
// the buffer to only the space required.
byte[] n = new byte[cnt];
System.arraycopy(buf, 0, n, 0, n.length);
buf = n;
} else if (len < 0) {
// With no length at the start of the read, the channel should
// have the length available at the end.
length = len = rc.size();
}
return new DfsBlock(key, pos, buf);
} finally {
rc.close();
ctx.stats.readBlockMicros += elapsedMicros(start);
}
}
private int blockSize(ReadableChannel rc) {
// If the block alignment is not yet known, discover it. Prefer the
// larger size from either the cache or the file itself.
int size = blockSize;
if (size == 0) {
size = rc.blockSize();
if (size <= 0)
size = cache.getBlockSize();
else if (size < cache.getBlockSize())
size = (cache.getBlockSize() / size) * size;
blockSize = size;
}
return size;
}
private static int read(ReadableChannel rc, ByteBuffer buf)
throws IOException {
int n;
do {
n = rc.read(buf);
} while (0 < n && buf.hasRemaining());
return buf.position();
}
>>>>>>> |
<<<<<<<
/***/ public String gitmodulesNotFound;
/***/ public String gpgFailedToParseSecretKey;
/***/ public String gpgNoCredentialsProvider;
/***/ public String gpgNoKeyring;
/***/ public String gpgNoKeyInLegacySecring;
/***/ public String gpgNoPublicKeyFound;
/***/ public String gpgNoSecretKeyForPublicKey;
/***/ public String gpgKeyInfo;
/***/ public String gpgSigningCancelled;
=======
>>>>>>>
/***/ public String gpgFailedToParseSecretKey;
/***/ public String gpgNoCredentialsProvider;
/***/ public String gpgNoKeyring;
/***/ public String gpgNoKeyInLegacySecring;
/***/ public String gpgNoPublicKeyFound;
/***/ public String gpgNoSecretKeyForPublicKey;
/***/ public String gpgKeyInfo;
/***/ public String gpgSigningCancelled; |
<<<<<<<
/***/ public String userConfigFileInvalid;
/***/ public String validatingGitModules;
=======
/***/ public String userConfigInvalid;
>>>>>>>
/***/ public String userConfigInvalid;
/***/ public String validatingGitModules; |
<<<<<<<
private void fetchObjects(ProgressMonitor monitor)
=======
private void addUpdateBatchCommands(FetchResult result,
BatchRefUpdate batch) throws TransportException {
Map<String, ObjectId> refs = new HashMap<>();
for (TrackingRefUpdate u : localUpdates) {
// Try to skip duplicates if they'd update to the same object ID
ObjectId existing = refs.get(u.getLocalName());
if (existing == null) {
refs.put(u.getLocalName(), u.getNewObjectId());
result.add(u);
batch.addCommand(u.asReceiveCommand());
} else if (!existing.equals(u.getNewObjectId())) {
throw new TransportException(MessageFormat
.format(JGitText.get().duplicateRef, u.getLocalName()));
}
}
}
private void fetchObjects(final ProgressMonitor monitor)
>>>>>>>
private void addUpdateBatchCommands(FetchResult result,
BatchRefUpdate batch) throws TransportException {
Map<String, ObjectId> refs = new HashMap<>();
for (TrackingRefUpdate u : localUpdates) {
// Try to skip duplicates if they'd update to the same object ID
ObjectId existing = refs.get(u.getLocalName());
if (existing == null) {
refs.put(u.getLocalName(), u.getNewObjectId());
result.add(u);
batch.addCommand(u.asReceiveCommand());
} else if (!existing.equals(u.getNewObjectId())) {
throw new TransportException(MessageFormat
.format(JGitText.get().duplicateRef, u.getLocalName()));
}
}
}
private void fetchObjects(ProgressMonitor monitor) |
<<<<<<<
import org.apache.accumulo.server.AccumuloServerContext;
import org.apache.accumulo.server.conf.NamespaceConfiguration;
=======
import org.apache.accumulo.server.conf.ServerConfiguration;
>>>>>>>
import org.apache.accumulo.server.AccumuloServerContext;
import org.apache.accumulo.server.conf.NamespaceConfiguration;
<<<<<<<
init(new AccumuloServerContext(instance, factory));
Assert.assertEquals("OOB check interval value is incorrect", 2000, this.getOobCheckMillis());
=======
init(factory);
Assert.assertEquals("OOB check interval value is incorrect", 7000, this.getOobCheckMillis());
@SuppressWarnings("deprecation")
long poolRecheckMillis = this.getPoolRecheckMillis();
Assert.assertEquals("Pool check interval value is incorrect", 0, poolRecheckMillis);
Assert.assertEquals("Max migrations is incorrect", 4, this.getMaxMigrations());
Assert.assertEquals("Max outstanding migrations is incorrect", 10, this.getMaxOutstandingMigrations());
>>>>>>>
init(new AccumuloServerContext(instance, factory));
Assert.assertEquals("OOB check interval value is incorrect", 7000, this.getOobCheckMillis());
Assert.assertEquals("Max migrations is incorrect", 4, this.getMaxMigrations());
Assert.assertEquals("Max outstanding migrations is incorrect", 10, this.getMaxOutstandingMigrations());
<<<<<<<
public void testBalanceWithMigrations() {
List<TabletMigration> migrations = new ArrayList<>();
init(new AccumuloServerContext(instance, factory));
long wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(2)), Collections.singleton(new KeyExtent()), migrations);
=======
public void testBalance() {
init((ServerConfiguration) factory);
Set<KeyExtent> migrations = new HashSet<KeyExtent>();
List<TabletMigration> migrationsOut = new ArrayList<TabletMigration>();
long wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the other tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the other tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// no more balancing to do
Assert.assertEquals(0, migrationsOut.size());
}
@Test
public void testBalanceWithTooManyOutstandingMigrations() {
List<TabletMigration> migrationsOut = new ArrayList<>();
init(factory);
// lets say we already have migrations ongoing for the FOO and BAR table extends (should be 5 of each of them) for a total of 10
Set<KeyExtent> migrations = new HashSet<KeyExtent>();
migrations.addAll(tableExtents.get(FOO.getTableName()));
migrations.addAll(tableExtents.get(BAR.getTableName()));
long wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
>>>>>>>
public void testBalance() {
init(new AccumuloServerContext(instance, factory));
Set<KeyExtent> migrations = new HashSet<>();
List<TabletMigration> migrationsOut = new ArrayList<>();
long wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the other tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// should balance four tablets in one of the other tables before reaching max
Assert.assertEquals(4, migrationsOut.size());
// now balance again passing in the new migrations
for (TabletMigration m : migrationsOut) {
migrations.add(m.tablet);
}
migrationsOut.clear();
wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut);
Assert.assertEquals(20000, wait);
// no more balancing to do
Assert.assertEquals(0, migrationsOut.size());
}
@Test
public void testBalanceWithTooManyOutstandingMigrations() {
List<TabletMigration> migrationsOut = new ArrayList<>();
init(new AccumuloServerContext(instance, factory));
// lets say we already have migrations ongoing for the FOO and BAR table extends (should be 5 of each of them) for a total of 10
Set<KeyExtent> migrations = new HashSet<>();
migrations.addAll(tableExtents.get(FOO.getTableName()));
migrations.addAll(tableExtents.get(BAR.getTableName()));
long wait = this.balance(Collections.unmodifiableSortedMap(createCurrent(15)), migrations, migrationsOut); |
<<<<<<<
assertStringArrayEquals(
"fatal: A branch named 'master' already exists.",
executeUnchecked("git checkout -b master"));
=======
assertStringArrayEquals(
"fatal: A branch named 'master' already exists.",
execute("git checkout -b master"));
}
>>>>>>>
assertStringArrayEquals(
"fatal: A branch named 'master' already exists.",
executeUnchecked("git checkout -b master"));
} |
<<<<<<<
public PackInvalidException(File path) {
this(path.getAbsolutePath());
=======
@Deprecated
public PackInvalidException(final File path) {
this(path, null);
}
/**
* Construct a pack invalid error with cause.
*
* @param path
* path of the invalid pack file.
* @param cause
* cause of the pack file becoming invalid.
* @since 4.5.7
*/
public PackInvalidException(final File path, Throwable cause) {
this(path.getAbsolutePath(), cause);
>>>>>>>
@Deprecated
public PackInvalidException(File path) {
this(path, null);
}
/**
* Construct a pack invalid error with cause.
*
* @param path
* path of the invalid pack file.
* @param cause
* cause of the pack file becoming invalid.
* @since 4.5.7
*/
public PackInvalidException(File path, Throwable cause) {
this(path.getAbsolutePath(), cause);
<<<<<<<
public PackInvalidException(String path) {
super(MessageFormat.format(JGitText.get().packFileInvalid, path));
=======
@Deprecated
public PackInvalidException(final String path) {
this(path, null);
}
/**
* Construct a pack invalid error with cause.
*
* @param path
* path of the invalid pack file.
* @param cause
* cause of the pack file becoming invalid.
* @since 4.5.7
*/
public PackInvalidException(final String path, Throwable cause) {
super(MessageFormat.format(JGitText.get().packFileInvalid, path), cause);
>>>>>>>
@Deprecated
public PackInvalidException(String path) {
this(path, null);
}
/**
* Construct a pack invalid error with cause.
*
* @param path
* path of the invalid pack file.
* @param cause
* cause of the pack file becoming invalid.
* @since 4.5.7
*/
public PackInvalidException(String path, Throwable cause) {
super(MessageFormat.format(JGitText.get().packFileInvalid, path), cause); |
<<<<<<<
=======
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
>>>>>>>
import com.google.common.collect.Iterables; |
<<<<<<<
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
=======
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto;
>>>>>>>
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyRequestProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.GetDataEncryptionKeyResponseProto; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.